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 (ifexpandtabis 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
tabstopvalue
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
tabstopbefore retabbing::set ts=2 | retab - To convert spaces to tabs:
:set noexpandtab | retab! - Combine with
gg=Gfor full re-indentation after converting