8

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/.

Philip Kirkbride
  • 993
  • 2
  • 11
  • 18

2 Answers2

9

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.

StandardEyre
  • 1,118
  • 1
  • 10
  • 22
6

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.

8bittree
  • 1,536
  • 12
  • 20