Want to use the tab key in Vim to substitute 2, 4, or 8 spaces for the tab character (t)? Let’s examine the configurations that must be made in order to accomplish this:
:set expandtab 1. - When the tab key is pressed, inserts the proper number of spaces instead of the tab character (t). If it is disabled (:set noexpandtab), tab characters rather than spaces are entered whenever the tab key is pressed. When enabled, the tabstop and softtabstop settings (discussed below) determine the width (number of spaces to insert in place of the t) character rather than whether the tab (t) character is enabled or disabled.
:set shiftwidth=2 - The shiftwidth parameter determines how many spaces are automatically inserted for indentation, so when you click enter to move to the next line, you can assume that it to be indented (with one or more tabs inserted). In this instance, there will be a 2-space indentation.
:set tabstop=2 When expandtab is turned on, the tabstop setting determines how wide the tab character (t) will be and how many space characters will be inserted. If expandtab is enabled, then anytime you press the tab key, 2 spaces will be added.
:set softtabstop=2 - When pressing the tab key, the softtabstop setting inserts the provided number of spaces. Similar to tabstop in several ways, but with a few caveats:
For tab key strokes, its value sort of supersedes that of tabstop.
When you use the backspace key, it also deletes the same number of spaces. This is a need!
Even if set:noexpandtab is set, which is supposed to insert a tab (t) when the tab key is pressed, it will still insert spaces.
When given a value of 0, it is disabled, and when given a value of 0, shiftwidth is used as a fallback.
The amount of spaces that will be added when the tab key is pressed in the instances above has always been 2. That can be changed to 4, 8, or anything else you like.
The tabs you put after they have been configured will be impacted by all of the settings above. What about the indentations from the previous tabs? You would also want to substitute spaces for them, right? Simply type the:retab command to accomplish this, which will replace all tabs with tabstop number of spaces.
1
2
3
4
" If tabstop=4 then replace all tabs with 4 spaces:retab" Set tabstop=2 and then replace all tabs with 2 spaces:retab2
In essence, autoindent instructs vim to carry over the indentation from the current line to the following one. This is done by pressing enter in insert mode or O or o in normal mode.
When modifying code, smartindent responds to the syntax and style (particularly for C). You must also turn on autoindent while it is turned on.
:help autointent Two other options are mentioned by autoindent: cindent and indentexpr, both of which instruct vim to disregard the value of smartindent.