Emacs-ifying vim's autoindent

Tagged:  •    •  

I switch very often between Emacs and vim for my editing, and for this reason I've set up Emacs to use viper (vi emulation) and a couple more hacks that emulate vim's visual mode as well.

However, I've always been dissatisfied with the way vim's autoindent works. I find Emacs's usage of Tab to indent the current line very easy to use and intuitive. I ended up disabling it completely; recently I found a hint in the cinkeys-format help entry about setting up Emacs-style autoindent, and even though my vimrc skills are close to zero, I managed to improve it to behave more or less as in viper.

First of all, I make Tab have the desired effect in insert mode by putting this in my .vimrc file (this is the part I found in vim's help):

set cinkeys=0{,0},0),0#,!<Tab>,;,:,o,O,e
set indentkeys=!<Tab>,o,O

Then I add a new normal mode command for <Tab> like this: it goes into insert mode just to do <Tab> and then moves to the first non-space character of the line:

map <Tab> i<Tab><Esc>^

To enable autoindent completely, you need a couple more options to set the per-type indentation and to set up the C indentation options to the style you like by default, for example:

filetype indent on
set cinoptions=:0,(0,u0,W1s

These cinoptions correspond to kernel-style indentation, not GNU-style. For GNU-style you need

set cinoptions={1s,>2s,e-1s,^-1s,n-1s,:1s,p5,i4,(0,u0,W1s shiftwidth=2

and it's fun to see why it works. :-)

Unfortunately, this is still not enough because some ill-behaved vim files reset indentkeys instead of adding to it. For this I used the following shell snippet:

for i in tcl gitconfig ruby html xml php rst css make dtd xinetd yacc; do
  echo 'setlocal indentkeys+=!<Tab>' > .vim/after/indent/$i

This does not cover all vim format files, just the ones I'm somewhat likely to ever use.

This is awesome! Thank you very much for this.
It works perfect for me. I am in transition
phase from Emacs to VIM and this is one of the
parts that bugs me as well.. I also need better
Tcl syntax/indentation stuff but this is very
diffucult to find. At least I have a good solution
for the C code! YEAH!

Thank you so much for this ... I quit using vim for a while just because I didn't have the tab auto-indent


autocmd FileType * setlocal indentkeys+=!<Tab>

in your .vimrc instead of putting a zillion one-liner files in .vim/after.

Aristotle Pagaltzis

User login