Question

While programming I am regulary using the following two lines:

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

putrsUART(buff);

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

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.

Try snip-Mate for inserting regularly used codesnippets. http://www.vim.org/scripts/script.php?script_id=2540


Wrong answer, Sorry:

Try this in your vimrc:

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

This means mapping to Ctrl-W.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top