ViM Macro

Once in a while, I need to manipulate a list of items, and it would be much easier to use a Macro. Under Windows, I use to use the Record and Playback features available in Textpad. Unfortunately, Textpad is not available for Linux. But, ViM does the same thing (and more), once you learn it.

In this example, I received a list of fields that my customer wanted to put in an HTML form. So, I needed to take a list like the following:

First
Last
Phone

And then turn that list into an HTML form like the following:

<label>First:</label><input type="text" name="First">
<label>Last:</label><input type="text" name="Last">
<label>Phone:</label><input type="text" name="Phone">

Assuming the list is more than just 3 items, there are two challenges here. First, we need to type text before and after the field, and second, we need to copy the name of the field so that it shows up in the label and as the name of the field. Below are the keystrokes I used to accomplish this.

  • Fire up ViM and paste the list of words into it. Move the cursor to the first of the file with gg.
  • Start recording the macro into the 9th register with q9. You can use any register.
  • Switch to visual mode with v then select the word at the cursor with aw.
  • Yank (copy) the selected text with y.
  • Insert text under the cursor with i.
  • Type <label>.
  • Press the Esc key to exit back to command mode.
  • Move to the end of the current line with $.
  • Start inserting text after the currently selected character with a.
  • Type the new text, in this case we'll type </label><input type=“text” name=“.
  • Now, put (paste) the register after the cursor position with p.
  • Start inserting after the current character with a.
  • Finish typing the rest of the line, we type ”>.
  • Exit to command mode again using the Esc key.
  • Move the cursor to the next line with j then to the beginning of the line with 0.
  • Press q to stop recording the macro.

Now that the macro is recorded, you can just replay the macro from register 9 with @9. You'll notice that the macro will automatically move the the next line. Repeat the process with @9 or even @@.

Usually, I just hit @@ to the end of the file at this point and I'm done. You can also repeat the macro 10 times by typing 10@9. You could even try 999@9 to repeat to the end of the file.

comments powered by Disqus
linux/vim_macro.txt · Last modified: 2020/06/01 22:53 (external edit)