My current setting assumes 8 spaces; how could I redefine it?
It depends on what you mean.
Depending on which behavior you need, one of the following sets of settings should work:
set tabstop=4
If your code requires use of actual tab characters these settings prevent unintentional insertion of spaces (these are the defaults, but you may want to set them defensively):
set softtabstop=0 noexpandtab
If you also want to use tab characters for indentation, you should also set shiftwidth
to be the same as tabstop
:
set shiftwidth=4
To make any of these settings permanent add them to your vimrc.
First, tell vim to use 4-space indents, and to intelligently use the Tab key for indentation instead of for inserting tab characters (when at the beginning of a line):
set shiftwidth=4 smarttab
If you'd also like vim to only use space caharacters, never tab characters:
set expandtab
Finally, I also recommend setting tab stops to be different from the indentation width, in order to reduce the chance of tab characters masquerading as proper indents:
set tabstop=8 softtabstop=0
To make any of these settings permanent add them to your vimrc.
In case you need to make adjustments, or would simply like to understand what these options all mean, here's a breakdown of what each option means, along with links their the full documentation.
tabstop
The width of a hard tabstop measured in "spaces" — effectively the (maximum) width of an actual tab character.
shiftwidth
The size of an "indent". It's measured in spaces, so if your codebase indents with tab characters then you want shiftwidth
to equal tabstop
. This is also used by commands like =
, >
and <
.
expandtab
Enabling this will make the Tab key (in insert mode) insert spaces instead of tab characters. This also affects the behavior of the :retab
command.
If you have this enabled you can enter a literal tab character by typing ctrlV followed by Tab. (mnemonic "verbatim tab")
smarttab
Enabling this will cause the Tab key (in insert mode) go to the next indent (as set by 'shiftwidth'
) instead of the next tab stop (or soft tabstop), but only when the cursor is at the beginning of a line (i.e. the only preceding characters are whitespace). Spaces and/or tabs will be used depending on the values of other options.
softtabstop
Setting this to a non-zero value other than tabstop
will make the tab key (in insert mode) insert a combination of spaces (and possibly tabs) to simulate tab stops at this width. Codebases where setting this to something other than 0 is desired are extremely rare.
For further details on any of these you can also use :help 'optionname'
in vim (e.g. :help 'tabstop'
).