Firstly, do not use the Tab key in Vim for manual indentation. Vim has a pair of commands in insert mode for manually increasing or decreasing the indentation amount. Those commands are Ctrl-T and Ctrl-D. These commands observe the values of tabstop
, shiftwidth
and expandtab
, and maintain the correct mixture of spaces and tabs (maximum number of tabs followed by any necessary number of spaces).
Secondly, these manual indenting keys don't have to be used very much anyway if you use automatic indentation.
If Ctrl-T instead of Tab bothers you, you can remap it:
:imap <Tab> ^T
You can also remap Shift-Tab to do the Ctrl-D deindent:
:imap <S-Tab> ^D
Here ^T and ^D are literal control characters that can be inserted as Ctrl-VCtrl-T.
With this mapping in place, you can still type literal Tab into the buffer using Ctrl-VTab. Note that if you do this, even if :set expandtab
is on, you get an unexpanded tab character.
A similar effect to the <Tab>
map is achieved using :set smarttab
, which also causes backspace at the front of a line to behave smart.
In smarttab
mode, when Tab is used not at the start of a line, it has no special meaning. That's different from my above mapping of Tab to Ctrl-T, because a Ctrl-T used anywhere in a line (in insert mode) will increase that line's indentation.
Other useful mappings may be:
:map <Tab> >
:map <S-Tab> <
Now we can do things like select some lines, and hit Tab to indent them over. Or hit Tab twice on a line (in command mode) to increase its indentation.
If you use the proper indentation management commands, then everything is controlled by the three parameters: shiftwidth
, tabstop
and expandtab
.
The shiftwidth
parameter controls your indentation size; if you want four space indents, use :set shiftwidth=4
, or the abbreviation :set sw=4
.
If only this is done, then indentation will be created using a mixture of spaces and tabs, because noexpandtab
is the default. Use :set expandtab
. This causes tab characters which you type into the buffer to expand into spaces, and for Vim-managed indentation to use only spaces.
When expandtab
is on, and if you manage your indentation through all the proper Vim mechanisms, the value of tabstop
becomes irrelevant. It controls how tabs appear if they happen to occur in the file. If you have set tabstop=8 expandtab
and then sneak a hard tab into the file using Ctrl-VTab, it will produce an alignment to the next 8-column-based tab position, as usual.