Tuesday, September 13, 2011

Creating a Marco in Vim

I'm a fan of the vim text editor, and try to use it as much as possible. I have hard time though making the effort to learn more than I already know. While I think I can use it pretty effectively, I know I've truly only scratched the surface.

Often I find myself retyping the same commands over and over to repeatedly accomplish the same task. I then make a mental note to learn about creating macros, which would of helped me out. I then proceed to forget about immediately.

Not today though. Today I'm going to create my first macro.

A macro is a series of commands that can be replaced. Marcos can be assigned to buffers so they can be saved and recalled. Buffers have single- character names in the ranges:

  • 0-9
  • a-z
  • A-Z

To start the definition of a macro in command mode, type 'q' followed by a single character in one of the ranges above.

I'm going to start with the text below and think of some reason to create a macro:

hello my name is george
hello my name is george
hello my name is george

How about we try and replace every occurence with "name" with "first name". We could do a global substitution by typing a colon followed by 's/name/first name/g' and hitting enter, but I want to try out a macro.

A marco could simply:

  1. Search for the next occurrence of name.
  2. Replace "name" with "first name" (or insert the text "first ")

Let's try it out. With my cursor on the first character in the file, if I:

  1. Type 'q' to declare I want to define a macro
  2. Type 'a' to assign the macro to buffer 'a'
  3. Type '/' followed by "name" then Enter to find the first occurence of "name"
  4. Type 'cw' followed by "first name" then Esc to change the word
  5. Type 'q' to complete the macro definition

The text should now have one occurrence of "first name" in place of "name":

hello my first name is george
hello my name is george
hello my name is george

Now we can run the macro typing '@a'. Running it twice will complete the remaning two substitutions, giving us:

hello my first name is george
hello my first name is george
hello my first name is george

We could also run the marco a number of times with one command. Say, given the text above where the first substitution was done, if we wanted to run the marco twice in one shot, instead of invoking it two separate times, we can type '2@a'.

No comments:

Post a Comment