Vim Tricks 3: Indenting August 6, 2008

For a long time now I have known how to indent using Vim’s > command to indent a block of text. I have learnt a few new tricks that might speed me up a bit.

In my .vimrc I have set shiftwidth=4 this means that when I indent by pressing tab, using the > command or using the new trick I’ll show in a second it is the width of 4 characters and because I have set expandtab it uses four spaces rather than a tab character. Without getting into the whole debate over which is better, spaces or tabs, the reason I do this is because I like to follow PEP 8 when I code Python which is the programming language I use most. PEP 8 states, amongst a whole load of other things, “Use 4 spaces per indentation level” and “Never mix tabs and spaces”.

So you can indent 4 lines in “Normal mode” by sticking the cursor on the first line, then type either >4> or 4>>. To indent just the one line you can do >> without specifying the number. You can also press > followed by a movement (in vim use :help usr_03.txt to learn more about that) so to indent everything from this current line to the first blank line below the current line I would type >/^$ and press enter.

If you are in insert mode editing text it can be annoying to have to go into “normal mode” and back to editing again afterwards just to indent or unindent a line. So to indent the current line whilst editing press Ctrl+T anywhere on that line and to unindent press Ctrl+D, easy. Unfortunately you can only do one line at a time that way.