Vim Tips Wiki
Advertisement
Tip 398 Printable Monobook Previous Next

created 2003 · complexity basic · author torelg · version 6.0


In Vim, the word "macro" may refer to:

  • Commands recorded in a register.
  • A mapping to expand a sequence of typed keys to a longer sequence.
  • A script written in the Vim script language (stored in a file with extension .vim).

This tip is concerned with the first meaning (recording a command into a register).

There are often many ways to accomplish a task in Vim. Recording a macro is a great way to accomplish a one-time task, to get things done quickly when you don't want to mess with Vim script or mappings, or if you just plain don't know how to do it more elegantly (yet).

Recording a macro

Each register is identified by a letter a to z.

To enter a macro, type:

q<letter><commands>q

To execute the macro <number> times (once by default), type:

<number>@<letter>

qq # record to q

your complex series of commands

q

@q to execute

@@ to repeat

Quickly run a macro

Use this mapping as a convenient way to play a recorded macro:

:nnoremap <Space> @q

Start recording keystrokes by typing qq.

End recording with q (first press Escape if you're in insert mode).

Play the recorded keystrokes by hitting space.

References

Comments

 TO DO 


Octopusgrabbus wrote the following:

Note: When you exit without quitting -- for example :x, :wq, your macro will be saved in .vminfo. Using :q results in the macro not being saved.

:help 'viminfo' mentions nothing about this special case, it just says that the viminfo file will be saved when Vim exits. For example,

gvim -N -u NONE
qaabcdef<esc>qu
:q
gvim -N -u NONE
:reg

This will record a macro to enter "abcdef" into register a, then quit Vim using :q. :reg shows that the contents of register a are still there after restarting Vim, which means it was saved in the viminfo file.

I will delete this comment after a few days if no-one has responded defending the claim that the viminfo file is not saved when using :q.

--Fritzophrenic 14:20, 24 May 2009 (UTC)

Advertisement