User Tools

Site Tools


vim:macros

VIM - Macros

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

  • This makes applying a set of complex changes multiple times across a code base much easier.

How to record a macro

  • Press q followed by any valid register to start recording (you should see something like recording @<register> in the status bar).
  • Start typing the changes you need to make.
  • Press q again to stop recording.
  • Press @<register> to replay the recorded steps.

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?

  • Luckily, q only triggers the macro to stop recording if it is the first character pressed as part of a new operation.

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

vim/macros.txt · Last modified: 2022/10/18 10:53 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki