0

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:

\begin{equation}

\end{equation}

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?

1 Answer 1

1

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.

2
  • 1
    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, 2020 at 1:14
  • 1
    @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, 2020 at 4:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.