Vim snippets with arguments

I'm trying to create snippets without using any plugins. For instance,

nnoremap ,eq :-1read $HOME/.vim/snips/.eq.tex<CR>o<TAB>  inserts the contents of .eq.tex:   I would like to do the same thing except be able to pass a simple character argument so that ,for i produces for (int i = 0; i < n; ++i) { }  while ,for j gives for (int j = 0; j < n; ++j) { }  Is something like this possible? One possibility could be to use functions, function! For(idx) r$HOME/.vim/snips/.for.c
endfunction


But this takes us back to the same problem. Or should I be defining mappings to :command functions, as in the 5th answer of this post?

To get a single character to use as an "argument" in a mapping, you can use the getchar() function, which waits for one.

You should then use nr2char() to convert it to a string.

If you want to use the character more than once (as it's your case here), you should store it in a variable. It's easier if you use a function to do so. Then use an <expr> mapping to insert the return value of the function into the buffer.

Putting it all together:

function! SnippetFor()
let v = nr2char(getchar())
return printf("for (int %s = 0; %s < n; %s++) {}\<Left>", v, v, v)
endfunction

inoremap <expr> ,for SnippetFor()


Activate it with ,fori or ,forj in Insert mode. You might want to tweak how the braces work or something like that.

But, really, use a snippet manager. It's way more flexible and you get to define your snippets at a much higher level! Not to mention you can find libraries of already defined snippets to get you quickly started.

• Thanks @filbranden. Regarding your last comment, I understand. The problem is that there is always a mountain of documentation and fine details that goes into making a solution to an otherwise trivial problem. Perhaps in the long term it pays off. In the short term you learn nothing about Vim or how to solve the problem you began with. The reality is I could probably hard code all the snippets I use with little effort. This says something specific about my use cases, but unless you're switching between 10 different language environments all day a whole separate software seems unnecessary. – algae Jun 7 '20 at 1:14
• @algae UltiSnips has videos if that helps! github.com/SirVer/ultisnips/blob/master/README.md#screencasts :-) Yes I see your point about learning more about Vim and having simple needs, but I still think a snippet manager is a great tool to add to the toolbox, especially because once you learn to use one well you start seeing more cases where you could.use its help that you hadn't bothered before... – filbranden Jun 7 '20 at 4:55