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

How do I use a macro to align text on a specific character like the equals sign?

Answer

qa0f=20i <Esc>20|C= <Esc>lDjq

Explanation

How it works

Aligning text on a delimiter such as = without plugins requires a clever macro technique. The strategy is to add excessive padding before the delimiter, then trim to a fixed column.

The command qa0f=20i <Esc>20|C= <Esc>lDjq breaks down as:

  • qa -- start recording into register a
  • 0 -- go to the beginning of the line
  • f= -- find the first = on the line
  • 20i <Esc> -- insert 20 spaces before the = (creating excess padding)
  • 20| -- move to column 20 (the desired alignment column)
  • C= -- change from cursor to end of line, replacing with = and whatever follows

Wait -- that last step needs refinement. Here is a cleaner approach:

  1. 0 -- go to start of line
  2. f= -- find the equals sign
  3. Insert spaces before it by pressing i then multiple spaces, then <Esc>
  4. Jump to the target column with 20|
  5. Delete everything between the cursor and the = to clean up extra spaces
  6. j -- move down to next line

Example

Given unaligned assignments:

x = 1
longname = 2
y = 3

After running the macro on each line (with column 20 as the target), you get:

x                  = 1
longname           = 2
y                  = 3

Adjust the column number (20 in this example) to match your desired alignment point. For different delimiters, change f= to f: or f, as needed. This technique works entirely without plugins in vanilla Vim.

Next

How do you yank a single word into a named register?