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:
- Set the desired tab width:
:set tabstop=4 - Enable space expansion:
:set expandtab - 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:
- Set the tab width:
:set tabstop=4 - Disable space expansion:
:set noexpandtab - 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
:retabto a range::'<,'>retabconverts tabs only in the selected lines. - To prevent future tabs from being inserted, keep
expandtabset. New Tab key presses will insert spaces. - Use
:set listto make tabs visible as^Icharacters so you can verify the conversion worked. - The
:retabcommand without!only converts tabs. The:retab!variant also converts sequences of spaces to tabs whennoexpandtabis set.