6

I'm creating a folder with common code snippets I use.

I want to create a quick command in vim to insert them, for example something like:

:snippet codeblock1

Ideally it would be a single command and codeblock1 could be replaced by the file name of a code snippet.

That way I could have a single command and add new snippets by creating new files in a set folder, likely in ~/.vim/snippets/.

8

The :r command can read a file containing a code snippet and insert it to your active buffer.

Unless I'm missing something, I believe this would address your request.

  • Thanks going to give it a try after lunch and mark correct! – Philip Kirkbride Apr 21 '17 at 16:12
  • wow exactly what I need, can't believe I didn't know that existed. – Philip Kirkbride Apr 21 '17 at 16:46
  • 2
    Glad to help. There's a lot I want to learn about vim, still, after using it for many years. That's one reason I hang out here. :-) – StandardEyre Apr 21 '17 at 17:53
5

StandardEyre's answer is the most direct answer for the body of your question, but you may also be interested in checking out one (or several) of the many snippet plugins for Vim, such as Ultisnips, Neosnippet, or muTemplate.

Rather than a command line mode command, they're usually triggered by a short string in insert mode. For example, typing fn<tab> may expand to

func _() -> void {
    return;
}

with _ being the cursor, in place for the function's name. The snippets can usually be filetype specific and can often take advantage of Vim's auto-completion capabilities. There's a question here that mentions a few more of these and has feature descriptions of some.

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.