how to add vim keymap

Tag: vim , keymapping Author: pour Date: 2012-08-25

While programming I am regulary using the following two lines:

sprintf(buff,"%s", __func__);


Is it possible to set any keyboard shortcut to insert these two lines? E.g. when I type \sp in command mode, these functions get added at the cursor position in my file. Is this possible? And if so, how do I map my keys?

Thanks in Advance.

Best Answer

You can use abbreviations, which are designed for this.

:abbr spb sprintf(buff,"%s", __func__);
:abbr uart putrsUART(buff);

Use :help abbr for the gory details. Note that you need to type another character after the abbreviated form for vim to recognize them. This comes naturally for these as you will type ENTER as the next character. It is also possible to enter more than one line with abbreviations. Simply use <CR> where you want a new line.


+1 this is definitely a task more suited to abbreviations.

Other Answer1

Here's an easy mapping for normal mode that lets you hit \sp (unless you've remapped leader, in which case use that instead of \) in order to insert the sprintf statement.

map <Leader>sp isprintf(buff,"%s", __func__);<Esc>

That being said I think abbreviations are the way to go here

Other Answer2

As already mentioned, abbreviations (which I would limit to insert mode (:iabbr), because you probably won't need them in the command-line) are best for simple expansions; you can also define them only for certain filetypes only (via :iabbr <buffer> ...).

Your __func__ looks like a template parameter that you need to adapt each time. You cannot do this via abbreviations, but there are various plugins (many inspired from functionality in the TextMate editor) that offer template insertion with parameter expansion and several advanced features. Check out one of snipMate, xptemplate, or UltiSnips.

Other Answer3

Try snip-Mate for inserting regularly used codesnippets.

Wrong answer, Sorry:

Try this in your vimrc:

map <c-w> :sprintf(buff,"%s",func)<cr> 

This means mapping to Ctrl-W.


Thanks, I added above line in my ~/.vimrc file. and start a new terminal session. I open a file tmp.c and press Ctrl-W key, it shows me following error code. "E492: Not an editor command: sprintf(buff,"%s", func)".
Sorry, I misread your question. I updated my answer.