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

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 press gr*, 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
  • rx gives: NamexAge — alignment destroyed
  • grx gives: Namex Age — alignment preserved (3 spaces fill the remaining tab width)

Tips

  • gR enters continuous virtual replace mode (the gr equivalent of R), 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 — gr accounts for double-width characters

Next

How do I jump to a tag in Vim and automatically choose if there is only one match?