How do I set the tab width in Vim?
Answer
:set tabstop=4 shiftwidth=4 expandtab
Explanation
The :set tabstop=4 shiftwidth=4 expandtab command configures Vim to use 4-space indentation with spaces instead of tab characters. These three settings work together to control how indentation looks and behaves in your files.
The three key settings
tabstop(orts) — how many columns a literal tab character (\t) occupies on screenshiftwidth(orsw) — how many columns to indent when using>>,<<, or auto-indentexpandtab(oret) — when enabled, pressing<Tab>inserts spaces instead of a literal tab character
Example configurations
For 4-space indentation with spaces (most common for Python, JavaScript, Go):
:set tabstop=4 shiftwidth=4 expandtab
For 2-space indentation with spaces (common for Ruby, YAML, HTML):
:set tabstop=2 shiftwidth=2 expandtab
For real tabs displayed as 4 columns wide (common for Go, Makefiles):
:set tabstop=4 shiftwidth=4 noexpandtab
Making it permanent
Add the settings to your ~/.vimrc (or ~/.config/nvim/init.vim for Neovim):
set tabstop=4
set shiftwidth=4
set expandtab
Tips
- Use
softtabstop(orsts) to control how many columns the<Tab>key moves in insert mode — set it equal toshiftwidthfor consistent behavior - Use
:retabto convert all existing tabs in the file to spaces (whenexpandtabis on) or vice versa - Use
:set listto make tab characters visible as^Iso you can see whether a file uses tabs or spaces - Use filetype-specific settings in your vimrc for different languages:
autocmd FileType python setlocal tabstop=4 shiftwidth=4 expandtab
autocmd FileType html setlocal tabstop=2 shiftwidth=2 expandtab
autocmd FileType go setlocal tabstop=4 shiftwidth=4 noexpandtab
- Use an
.editorconfigfile with theeditorconfigplugin to share indentation settings across a team - Use
:set ts? sw? et?to check the current values of these settings