vimtricks.wiki Concise Vim tricks, one at a time.

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 (or ts) — how many columns a literal tab character (\t) occupies on screen
  • shiftwidth (or sw) — how many columns to indent when using >>, <<, or auto-indent
  • expandtab (or et) — 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 (or sts) to control how many columns the <Tab> key moves in insert mode — set it equal to shiftwidth for consistent behavior
  • Use :retab to convert all existing tabs in the file to spaces (when expandtab is on) or vice versa
  • Use :set list to make tab characters visible as ^I so 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 .editorconfig file with the editorconfig plugin to share indentation settings across a team
  • Use :set ts? sw? et? to check the current values of these settings

Next

How do I edit multiple lines at once using multiple cursors in Vim?