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

How do I use marks inside a macro to return to a specific position?

Answer

qama{edits}'aq

Explanation

How it works

When a macro needs to jump to different parts of the file and then return to a starting position, marks are the perfect tool. By setting a mark at the beginning of the macro, you can always jump back after making edits elsewhere.

The pattern qama{edits}'aq breaks down as:

  • qa -- start recording into register a
  • ma -- set mark a at the current cursor position
  • {edits} -- perform any edits, searches, or jumps you need
  • 'a -- return to the line of mark a (use backtick-a for exact column)
  • q -- stop recording

This technique is essential when your macro needs to:

  • Copy text from one location and paste it at another
  • Look up a value elsewhere in the file and bring it back
  • Make changes in a header or footer section and return to working position

Example

Suppose you want a macro that copies the current line's first word and appends it to line 1 as a comma-separated list:

  1. Record: qamayiw1GP$a, <Esc>p'ajq
  2. Breakdown:
    • ma -- mark current position
    • yiw -- yank the inner word
    • 1G -- go to line 1
    • $ -- go to end of line 1
    • a, <Esc>p -- append comma, space, then paste the word
    • 'a -- return to the marked line
    • j -- move down to the next line for the next iteration
  3. Run 5@a to collect words from the next 5 lines

Using marks inside macros makes them far more versatile, allowing complex multi-location edits in a single recording.

Next

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