Thursday, February 11, 2010

Vim macro saves the day!!

So I had to work on a php script at work. Urg, php isn't exactly my language of choice, but I decided to make the best of it and at least try to have some fun, which I did, while learning something in the process. Here's the scoop:

I had to take something like this:
$output.="blah blah blah blah blah";
and turn it into something like this:
$output.="blah blah blah blah blah\n";
Unfortunately for me, there was a TON of lines like this.
After attending a great talk at nycpython by Justin Lilly on editor efficiency, I decided to try out a 'vim macro' for the first time.

Here's how I solved this problem:
  1. type 'qq' to start recording my macro
  2. type '$' to get to the end of the line
  3. hit 'h' twice to move the cursor left twice
  4. hit 'i' to go into insert mode
  5. type '\n' to put in my line break
  6. hit the esc key to get out of insert mode
  7. hit 'j' to move down to the next line
  8. hit 'q' to stop recording the macro
  9. type '20@q' to execute the macro 20 times
So this means that in order to create the macro, the syntax is:
qq commands q
..and then to execute it multiple times:
x@q
...where 'x' is the number of times you want to execute it.

I'm sure that there are many ways to do this, being that vim is such a powerful editing tool.
Anyways, the macro is definitely a tool I see myself using in the future, as it cut down the monotony and time needed to accomplish this annoying task.

Happy coding,
Sean

No comments: