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

How do I convert between tabs and spaces in a visual selection?

Answer

:'<,'>retab!

Explanation

The :retab! command converts between tabs and spaces based on your expandtab setting. When applied to a visual selection, it only affects the selected lines, allowing targeted whitespace conversion without modifying the entire file.

How it works

  • :retab — replaces tabs with spaces (if expandtab is set) in leading whitespace
  • :retab! — replaces ALL tabs/spaces (including within strings), not just leading whitespace
  • :'<,'>retab! — applies only to the visual selection
  • The conversion uses the current tabstop value

Example

:set expandtab tabstop=4
:'<,'>retab!
Before (tabs shown as →):
→   if (condition) {
→   →   return true;
→   }

After (tabs converted to 4 spaces each):
    if (condition) {
        return true;
    }

Tips

  • Use :retab (without !) to only convert leading whitespace, preserving tabs in strings
  • Set tabstop before retabbing: :set ts=2 | retab
  • To convert spaces to tabs: :set noexpandtab | retab!
  • Combine with gg=G for full re-indentation after converting

Next

How do I return to normal mode from absolutely any mode in Vim?