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 registera0-- go to the beginning of the linef=-- find the first=on the line20i <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:
0-- go to start of linef=-- find the equals sign- Insert spaces before it by pressing
ithen multiple spaces, then<Esc> - Jump to the target column with
20| - Delete everything between the cursor and the
=to clean up extra spaces 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.