How do I make my macros robust regardless of cursor position?
Answer
0 or ^ at start of macro
Explanation
A common macro pitfall is assuming the cursor starts at a specific column. Adding a positioning command at the beginning of your macro makes it work reliably regardless of where the cursor happens to be.
The problem
If you record a macro with the cursor at column 1, but replay it when the cursor is at column 15, the macro may operate on the wrong text.
The solution
Start every macro with a positioning command:
" Jump to first column
qq 0 ... q
" Jump to first non-blank character
qq ^ ... q
" Jump to end of line
qq $ ... q
" Jump to specific search match
qq /pattern<CR> ... q
Example: Wrap each line in quotes
Bad macro (breaks if cursor isn't at column 1):
qq i"<Esc>A"<Esc>j q
Robust macro:
qq 0i"<Esc>A"<Esc>j q
Other robustness tips
" End on the next line's first column for repeatable macros
qq 0 ... j q
" Use text objects instead of motions for resilience
qq ciw"replacement"<Esc>j q
" Use f/t for character-based navigation within the line
qq 0f:r=j q
Tips
- Always end the macro with
j(or movement to the next target) for easy repetition with10@q - Use
0for column-aware operations,^for indentation-aware ones - Prefer text objects (
iw,i",it) over movement counts for reliability - Test with
@@(repeat last macro) on several lines before running in bulk