Wednesday, 14 April 2010

Stata indenting in Vim

Yesterday I decided to look into vim indenting for Stata do-files.

Pretty much every programmer likes to indent their code to make it more legible. Many do it by hand, but it is mostly a routine task, and it is easy to have the text editor do it instead.

Vim, however, isn't known for its user-friendliness; its extreme customizability sometimes comes at the cost of clarity. Indenting, I find, is one such example.

Basically, indenting is filetype specific; every major language has its own file in $VIMRUNTIME/indent. Stata doesn't, and I don't think anyone bothered to make one.

There isn't much indenting needed in Stata--the most crucial thing is to indent between curly brackets. However, by default (i.e. when it doesn't find a specific indent file) VIM indents according to the C rules; so we need to customize this a bit, as stata code indented according to C rules will sometimes give strange results.

I find that the following options work well for me:

set shiftwidth=5
set cinoptions=>s,e0,n0,f0,{0,}0,^0,:0,=0,l0,b0,g0,h0,p0,t0,i0,+0,c0,C0,/0,(0,u0,U0,w0,W0,m0,j0,)20,*30,#0
set cinwords=

You can find the help for each of these by just typing :help cinoptions and :help shiftwidth. More general help on indenting is :help C-indenting.
For a bit more on indenting commands, have a look at this Vimcast.

Then to have a block of text indented automatically in your do-file, you can select it and type =. To do it for the whole file, gg=G works like a charm.

EDIT:
If you want a quick workaround, just put this (very simple) indent file in the /indent directory of your runtimepath. It contains the shiftwidth and cinoptions values I gave above.

1 comment:

  1. Hi there,

    why / how does indenting change the results in Stata?

    kind regards, Benzhi

    ReplyDelete