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

How do I convert space-indented code to tab-indented code in Vim?

Answer

:set noexpandtab | retab!

Explanation

When you inherit space-indented code and need to switch to tabs, :retab! (with the bang) converts groups of spaces into tabs throughout the file. Without the !, :retab only retabulates existing tabs — it won't touch spaces. The ! flag tells Vim to also treat sequences of spaces as candidates for conversion.

How it works

  • :set noexpandtab — tells Vim to use real tab characters going forward
  • :set tabstop=N — set N to match the current space-indent width (e.g., 4 for 4-space indents)
  • :retab! — scans the file and collapses runs of spaces (in multiples of tabstop) into tab characters

The reverse — tabs to spaces — is simpler: :set expandtab then :retab (no bang needed).

Example

File indented with 4 spaces:

function hello() {
    return 42;
}

After :set noexpandtab | set tabstop=4 | retab!:

function hello() {
→   return 42;
}

(where represents a tab character)

Tips

  • Use :set list and :set listchars=tab:→\ to visualize tab characters before and after
  • To convert only a range, use :'<,'>retab! on a visual selection
  • If the file mixes 2-space and 4-space indentation, normalize first with a substitution before retabbing
  • :retab! 2 overrides tabstop inline: treats every 2 spaces as one tab level

Next

How do I enable matchit so % jumps between if/else/end style pairs?