Convert Existing Tabs to Spaces in Vim
Step-by-step Vim instructions for replacing existing tabs with spaces, setting tab width, and checking the result in plain text files.
Before you start
This task works directly on a local text file in Vim. It does not require a service or an internet connection. Make a copy of the file if you want to keep the original tab-based version, because changing tab characters affects the whole file.
Step-by-step instructions
Open a file in Vim with its normal command, then set the desired number of spaces for one tab. If the file should use four spaces per tab, enter :set tabstop=4 shiftwidth=4 expandtab and press Enter. These settings do not change the file by themselves; they prepare the replacement.
Replace existing tabs with :retab. This replaces tab characters with spaces according to the current tabstop setting. To apply it to the entire file, enter :retab and press Enter.
Keep the replacement reversible while the file is open: check the result with :set list or another display option, and use u to undo if the spacing is wrong. Version differences are small, but some older Vim builds may treat retab options differently, so confirm the retab result before saving.
Check the output
Use :set list to display tabs and line endings so you can verify that tab characters are gone. Tabs may appear as ^I by default, while spaces remain as blanks. Another check is to search for a tab character with /\t; if the search finds no match, the conversion worked for the whole file.
This method changes tab width only for the open file unless the settings are saved in a Vim configuration file. Visual alignment may differ if the original file used mixed tab stops or spaces.
Common problems and next steps
If :retab does not change anything, confirm expandtab is enabled and verify that the file contains actual tab characters rather than spaces that only look like a tab.
For a Python file, spacing rules are strict. The retab command can replace tabs with spaces, but mixed indentation may still be invalid. After conversion, use Python's own syntax check or another linter to confirm the file is readable.
If only part of the file should be converted, select the lines in Visual mode and enter :retab. This applies the change to the selected range instead of the entire file. Save only after checking the line indentation.