meisterluk’s advent calendar: macros

Sometimes commands are really long. And sometimes you have to execute them several times. I mentioned that you can access older ex commands by using <Up> in command-line mode. This is not available for Vim commands. The solution to this problem are recorded sequences of commands: macros.

Open Vim and write plain text (make sure that noexpandtab is set)

Guido	python
Rasmus	PHP
Dennis	C

We will replace this tab-separated table with rows in HTML syntax. Frist of all, jump to the first row. To start a macro type “q” and a name for a register (eg. “q”; type “q” simply two times). Type this list of keys:

0i  <tr><td><Esc>/<Tab><Enter>xi</td> <td><Esc>$a</td></tr><Esc><Enter>

Of course <Esc>, <Tab> and <Enter> are pressed keys and <tr> is a list of characters to type. End the macros by pressing “q” (the “q” to introduce macros and not the register name) again. With this command the first line looks like this:

<tr><td>Guido</td> <td>python</td></tr>

To execute this commands to the 2 other lines, jump to the second line and type “2@q”. This executes (@) the macro in register (q) (2) times. You can use this macro now wherever you want. It will be saved over several vim sessions. You wrote your first vim macros. Have fun with it! :-)

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>