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

How do I convert all tabs to spaces in a file in Vim?

Answer

:retab

Explanation

How it works

The :retab command replaces all tab characters in the current buffer with the appropriate number of spaces, based on your current tabstop and expandtab settings.

To convert tabs to spaces:

  1. Set the desired tab width: :set tabstop=4
  2. Enable space expansion: :set expandtab
  3. Run :retab

This replaces every tab character with enough spaces to maintain the same visual alignment. For example, a tab at the beginning of a line with tabstop=4 becomes 4 spaces.

You can also convert spaces back to tabs by doing the reverse:

  1. Set the tab width: :set tabstop=4
  2. Disable space expansion: :set noexpandtab
  3. Run :retab! (the ! forces conversion of spaces to tabs)

Example

Suppose you receive a file that uses tabs for indentation but your project style guide requires spaces:

\tfunction hello() {
\t\tconsole.log("hi");
\t}

Run:

:set tabstop=4 expandtab
:retab

The result:

    function hello() {
        console.log("hi");
    }

All tabs are now replaced with 4 spaces each.

Tips

  • You can apply :retab to a range: :'<,'>retab converts tabs only in the selected lines.
  • To prevent future tabs from being inserted, keep expandtab set. New Tab key presses will insert spaces.
  • Use :set list to make tabs visible as ^I characters so you can verify the conversion worked.
  • The :retab command without ! only converts tabs. The :retab! variant also converts sequences of spaces to tabs when noexpandtab is set.

Next

How do you yank a single word into a named register?