You can create a template as follow:
First, create a file (for example base.go
) which will be your template with inside the snippet you typed in your question (I store my templates in $HOME/.vim/templates/<language>/
, so in your case, it would be $HOME/.vim/templates/go/base.go
, but the location is up to you really),
Then, in your .vimrc
, add the following mapping:
nnoremap <space>t :-1read $HOME/.vim/templates/go/base.go<CR>/{<CR>o
This mapping does the following when you press space-t
in normal mode:
- the content of the file
$HOME/.vim/templates/go/base.go
is inserted where your cursor is,
- the cursor is moved to the opening
{
,
- you are put in insert mode in the brackets.
So when you open a new go file, press space-t
and it will insert your template and place you where you need to be to start coding.
EDIT:
-1
indicate the position of where to insert the content of the file(:.read file
inserts it just after the current (.
) line. -1
inserts it just after the current line -1. So effectively, it is to insert it where your cursor is and move down the lines including the one you are on. For more about it, you can read :help range
.
The jump is done with the part /{<CR>o
which looks for a {
(/{
), goes to it (<CR>
) and goes in insert mode just after (o
).