Monday, March 8, 2010

vim: mapping the F2 key to a sequence of commands

Macros are a great way to automate tasks in vim. You can record a sequence of keystrokes, assign them to a register, and then playback the macro saved in that register any number of times.

However, sometimes you come across a macro that is so useful that you use it frequently. Perhaps you use it across several vim sessions. You wish you could create a keyboard shortcut for this macro, and then save it in your ~/.vimrc file for anytime usage.

This is how you can do that, using vim’s map command:
map <F2> 0i\<Esc>A\n\<Esc>j

This mapping will bind the F2 key to perform this sequence of operations:

number operation vim command
1 go to the hard BOL (beginning of line) 0
2 insert the '\' character i\
3 go back to command mode <Esc>
4 append \n\ to the end of the line A\n\
5 go back to command mode <Esc>
6 go down one line (so that you can just press F2 again on the next line, to continue) j

No comments: