How do I replace a character while preserving screen column alignment when tabs are involved?
Answer
gr{char}
Explanation
The gr{char} command is Vim's virtual replace variant of r{char}. While r replaces a single byte with another, gr replaces in terms of screen columns, inserting padding spaces as needed to maintain visual alignment. This is especially valuable when editing tabbed or fixed-width data.
How it works
r{char}— replaces the byte under the cursor with{char}. Replacing a tab (which occupies multiple columns) with a single character collapses the visual width.gr{char}— replaces the screen columns occupied by the character under the cursor. If a tab takes 4 columns and you pressgr*, Vim inserts*followed by enough spaces to fill those 4 columns, preserving the position of all subsequent characters.
Example
With tabstop=4, if the cursor is on a \t separating two columns:
Name\tAge
rxgives:NamexAge— alignment destroyedgrxgives:Namex Age— alignment preserved (3 spaces fill the remaining tab width)
Tips
gRenters continuous virtual replace mode (thegrequivalent ofR), letting you overtype multiple characters while preserving column widths- Useful when editing aligned code, ASCII tables, or any content where vertical alignment matters
- Works correctly with multi-byte Unicode characters too —
graccounts for double-width characters