Archive for the 'Productivity Tips' Category

VIM Macros: Old-School text editing using macros massively boosts programmer productivity - How to Do it

Thursday, September 17th, 2009

It always amazes me that some coders never leave the IDE for anything.  It’s especially daft when you’ve got a massive text file to edit and you’re spending an hour walking through it to make the change.

Imagine I’ve got a huge text file full of data and I need to change it into a bunch of SQL insert statements.  I could either write a bit of script (BASH or Python) or just load the file in VIM and use a macro.

Macros are something that most younger coders don’t think of but if i want to easily modify files in a consistent ways then that’s where i’d start every time.

For VIM all you need is “q” to start recording a macro and then a letter for the name of it.  To end recording of the macro hit “q” again.  To run it type “@” followed by the letter you assigned to macro”.  Note: for most of us our default macro is called “q” to make it quicker to type…

So for the uninitiated here’s a step by step walk through on using a VIM macro.
Assume that I’ve got a file of the form

AABBCCDD
EEFFGGHH
IIJJKKLL
MMNNOOPP

with another 96 lines of similar stuff below and i want to insert each row into a table in the form

INSERT INTO VALUES (' ');

First, open the file in VIM.

start a macro “qq” (q starts a macro and we’ll call it “q“)

ensure we’re at the start of a line by hitting “^

type “i” to insert then INSERT INTO VALUES ('

and hit ESC (escape) to stop inserting

move to the end of the line by hitting “$” and hit “a” to append text then ');

and hit ESC (escape) to stop appending text

move down a line and hit “q” to end the recording of the macro

You can now execute the macro by typing @q (”@” meaning - run a macro, “q” as the name of the macro to run)

or you can go to the top line and hit 100@q to run the macro against all the lines.

Hey presto - one fixed up file in less than a minute!