How do I make the indent width automatically match the tabstop setting without keeping them in sync manually?
Answer
:set shiftwidth=0
Explanation
Setting shiftwidth=0 tells Vim to use the value of tabstop wherever shiftwidth would normally be consulted — for the > and < operators, <C-t> and <C-d> in insert mode, and auto-indent. This eliminates the common frustration of having tabstop and shiftwidth drift out of sync when switching between projects with different indent styles.
How it works
- Normally
shiftwidthcontrols indent size andtabstopcontrols how wide a tab character renders. They are independent, so you must set both. - When
shiftwidth=0, Vim substitutestabstopforshiftwidthinternally — the two are always equal, automatically. - You only need to set
tabstop(orsofttabstopif you use space-based indentation) and the shift operators will follow.
Example
Instead of:
set tabstop=4 shiftwidth=4 expandtab
You can write:
set tabstop=4 shiftwidth=0 expandtab
Now if you later change tabstop to 2 for a different file, > and < will automatically indent by 2 — no need to update shiftwidth.
Tips
- This is especially useful in
FileTypeautocmds:setlocal tabstop=2 shiftwidth=0applies one setting and indentation follows automatically - To check the effective shiftwidth at runtime:
:echo shiftwidth()— theshiftwidth()function respects the zero-fallback and returns the actual value that will be used - The zero-value behavior was added in Vim 7.3.693 and is available in all modern Vim/Neovim versions