DEV Community

Guilherme
Guilherme

Posted on

VIM - Macros

Macros are a sequence of commands recorded to a register.

Recording a macro:

Type the q key followed by the register.
I.e: To start recording a macro in the register a, type: q a

You should see a message in the status line at the bottom of the VIM: recording @a

To stop recording a macro, just type q.

To check what is recorded in the register @a for example, you can type:

:reg a
Enter fullscreen mode Exit fullscreen mode

To replay a macro that is recorded on register a, type @ a , you can also use @ @ to repeat the last macro used.

Macro best practices

  • Normalize the cursor position: 0
  • Perform edits and operation
  • Position your cursor to enable easy replays: j

TIP: You can apply the macro to multiple line using count.

I.e: Applying the macro to the next 5 lines {count}{@}{macro} : 5 @ a

Example using Macros

Let's say you having the following text:

1 FIRST NAME: Joseph LAST NAME: Andrews
2 FIRST NAME: Scott LAST NAME: Young
3 FIRST NAME: Jessica LAST NAME: Smith
4 FIRST NAME: Shirley LAST NAME: Landers
5 FIRST NAME: Pamela LAST NAME: Lewis
Enter fullscreen mode Exit fullscreen mode

And you want to remove FIRST NAME: and LAST NAME, the result should be:

1 Joseph Andrews
2 Scott Young
3 Jessica Smith
4 Shirley Landers
5 Pamela Lewis
Enter fullscreen mode Exit fullscreen mode

Steps

  1. Start recording a macro at register b: q b
  2. Position the cursor at the first character in the line: 0
  3. Delete the first 2 words: 2 d W
  4. Move your cursor to the next word: W
  5. Repeat the last operation: .
  6. Move your cursor to the next line: j
  7. Stop recording: q
  8. Apply the macro to the next 4 lines: 4 @ b

Or you could use global command:

:g/\(FIRST\|LAST\) NAME: /norm 2dWW.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)