Learn Practice Daily golf Reference

How to set the tab size and use spaces in Vim

For four-space indents, type :set tabstop=4 shiftwidth=4 expandtab and press ↵. tabstop is how wide a tab looks, shiftwidth is one level of indent, and expandtab makes Tab insert spaces.

Option or commandWhat it sets
tabstop (ts)How many columns a tab character takes up on screen. Vim starts at 8.
shiftwidth (sw)One level of indent: what >>, << and automatic indenting use. 0 means "the same as tabstop".
softtabstop (sts)How far Tab and ⌫ move in Insert mode. -1 means "the same as shiftwidth".
expandtab (et)Insert spaces instead of tab characters, for Tab and for indenting. noexpandtab goes back to tabs.
:retab ↵With expandtab on, turn every tab already in the file into spaces.
:retab! ↵With noexpandtab, also turn runs of spaces into tabs where they fit.
:set list ↵Show the tabs, so you can see what the file uses (:set nolist hides them again).
:set shiftwidth? ↵Show an option's current value.
Practise the keys

Tabs and spaces, from memory

Type each command as you would in Vim, Enter included, with the option names spelled out in full.

Make a tab character show as 4 columns wide.
scroll here, then press the keys15 keys
1 of 5
Make a tab character show as 4 columns wide.

Three widths, and spaces or tabs

tabstop only changes how a tab character looks; it doesn't change the file. shiftwidth is the size of the indents Vim makes for you. expandtab decides whether those indents are written as spaces or as tabs. For most code you want all of them to agree. In ~/.vimrc:

  • set tabstop=4 shiftwidth=4 expandtab for four spaces
  • set tabstop=2 shiftwidth=2 expandtab for two spaces
  • set tabstop=4 shiftwidth=4 noexpandtab for real tabs, shown four columns wide

In Neovim's init.lua the same settings are vim.opt.tabstop = 4, vim.opt.shiftwidth = 4 and vim.opt.expandtab = true. These only affect new indents. To convert a file that already has tabs, set the options and then run :retab.

Different sizes for different languages

Settings in your config apply to every file. For one language, put setlocal lines in a file type plugin in the after folder, which runs after Vim's own one for that language: ~/.vim/after/ftplugin/javascript.vim with setlocal shiftwidth=2 softtabstop=2 expandtab. In Neovim the folder is ~/.config/nvim/after/ftplugin/, and a javascript.lua file there can say vim.opt_local.shiftwidth = 2. In a ~/.vimrc you can also write autocmd FileType javascript setlocal shiftwidth=2 expandtab after the filetype plugin indent on line.

EditorConfig

Many projects carry a .editorconfig file that says how their code is indented (indent_style = space, indent_size = 2), so every editor follows the same rules. Neovim applies it by default, since version 0.9. Vim 9.1 ships the plugin as an optional package: add packadd! editorconfig to ~/.vimrc.