Table of Contents

VIM - Macros

Vim macros allows the recording of any typed characters so that they can then be replayed again.


How to record a macro

NOTE: A register is a single character from: {0-9a-zA-Z“}.

  • Use an uppercase letter to append.

TIP: A suggestion is to use the q register.

  • It is the quickest way to start recording a macro, as your finger is already over the q key to start recording anyway.
    • Example: To record into the q register, type
      qq

How to include the q character into a macro recording

What happens if the macro steps need to include the q character - as that character is what stops a macro recording?

Example: Record a macro that deletes all occurrences of the letter q from the current line:

qq0V:s/q//g<Enter>q

NOTE: The break-down of these steps:

  • qq: Record into the q register.
  • 0: Move to the start of the line.
  • V: Select the entire line.
  • :: Start Ex mode.
  • s/q//g: A substitution that deletes q globally.
  • <Enter>: Press the <Enter> key to have the substitution applied to the current line.
  • q: Stop recording.

Check what a Register Contains

Display what a register contains:

:reg

returns:

0V:s/q//g^M

Run a Macro

@q

NOTE: The q is the Register that contains the macro to run.

  • Once a macro has been replayed it can be trigger again without having to specify the register by typing:
    @@
  • If you need to run a macro a certain number of times then just prefix it with that number.
    • For example, to run a macro six times type 6@<register>

References

https://vimhelp.org/repeat.txt.html#recording