Record, save and reuse macro in VIM

Editing macro is a great help when you need to do some repetitive editing tasks, for example, add parenthesis, double quotes, brackets to wrap a line of text, or decorate a keyword with HTML tag like strong.

To start recording macro, press "q" in normal mode. The next step is to give it a name, because in VIM the macro is stored in a register, a register name can be any character of A-Z and a-z. Suppose you want to use register "a", press "qa" and the recording started.

Then start typing, in this example, we move cursor to the beginning of the line, insert left parenthesis and go to end of the line and insert right parenthesis. When you are done press "q" again to finish recording. Now your macro should be saved in register "a".

To see the content of the register, execute

 
:register
 

Press "@a" to execute the macro, "@@" execute last executed macro.

By default, everything in register is saved when you exit VIM, your macros are available when you start VIM next time. But if you start a new VIM instance before close current one, you don't have access to macros in new instance.

There are some differences between VIM macros and Emaca macros. In Emacs, a macro is a LISP object which is just a piece of LISP code, and it can be easily wrapped in a function. This makes Emacs macro easy to name and save.

An Emacs macro example

 
(fset 'tt
   (lambda (&optional arg) "Keyboard macro."
     (interactive "p")     
     (kmacro-exec-ring-item (quote ([60 62 10 116 116 67108923 60 62 10 47 116 116 10 10 10 10] 0 "%d")) arg)))
 

The second useful keyboard macro in VIM is add HTML tags to keywords phrase. I do this quite a lot, to bold a phrase, I usually add a strong tag around the phrase.

I use s to store the macro, first select the keywords phrase in visual mode and then press "qs", the recording started, then press d to delete the phrase, and insert

 
<strong></stong>
 

and move the cursor between the tag and then press "p" to paste the phrase just deleted. Now press "q" to finish macro recording.

To use the macro , select the text and press "@s". This saves me a lot of typing and time.