Posted in Uncategorized

vi: Keyboard Macros

While editing a file I have often the problem to do the same tasks repeatedly on many (or even all) lines, e.g.:

  • appending a semicolon to the end of every line,
  • commenting some lines in a shell script,
  • creating SQL statements from a list of tables,

This can be done with keyboard macros.

Let’s assume, that I have a shell script, where I want to comment some lines, and put the actual date into this comment:

cd $HOME/tmp
ls -l *.txt
rm *.txt
cd -

Shall become:

cd $HOME/tmp
#2017-06-05#ls -l *.txt
#2017-06-05#rm *.txt
cd -

I can use keyboard macros to save some keystrokes. A keyboard macro is startet with the letter q followed by a register. Then the following keystrokes are recorded until a q is pressed again in normal mode.

qc0i#2017-06-05#0jq

q starts the macro, c is the register name – you can use all register az. 0 sets the cursor to the beginning of the line. Then I start the insertion with i, type the text until I press . Finally I set the cursor to the beginning of the line, and go one line down. The last q stop the recording.
For the next line I have only to execute the macro. This is done with @ followed by the register:

@c

And the next line is commented. Observe the 0j at the end of the macro. The cursor is at the beginning of the next line, and everything is ready for next execution.
What to do, if I want to comment the next 17 lines? I use a numeric prefix:

17@c
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s