Federico Ramirez
Posted on March 21, 2022
There are many Vim plugins to create code snippets. But did you know Vim already supports this functionality?
I like relying on vanilla Vim as much as possible, and keep plugins to a minimum. For that reason, I ended up using :help abbreviations
to make a simple snippet engine.
It works so well, I'd like to share it! Below is an example of my current setup:
augroup haml
autocmd!
autocmd FileType haml inorea <buffer>
\ table %table<CR>%thead<CR>%tr<CR>%th {%header row%}<CR><BS><BS>%tbody<CR>%tr<CR>%td {%body row%}
augroup END
nnoremap <Plug>GoToNextPlaceholder :call search('{%[^%]*%}')<CR>va{
imap <silent> <C-q><C-e> <C-v><C-a><C-]><Esc><Plug>GoToNextPlaceholder
nmap <silent> <C-q><C-q> <Plug>GoToNextPlaceholder
imap <silent> <C-q><C-q> <Esc><Plug>GoToNextPlaceholder
vmap <silent> <C-q><C-q> <Esc><Plug>GoToNextPlaceholder
The mappings I use are <C-q><C-e>
to expand, and <C-q><C-q>
to go to next placeholder, but feel free to change this to whatever you like.
I define snippets inside an augroup
, in this case, all HAML snippets are there. Each snippet ends with ctrl-a
, that's just so snippets don't get automatically triggered all the time, we want to manually trigger them.
You can input the <ctrl-a>
character while typing by pressing <ctrl-v><ctrl-a>
in insert mode.
The snippet itself looks like this:
autocmd FileType |my-filetype| inorea <buffer> |my-sippet<c-a>| |my-expansion|
You can use {%placeholders%}
in the expansion, to be navigated with <C-q><C-q>
. A HAML table snippet looks like this:
autocmd FileType haml inorea <buffer>
\ table %table<CR>%thead<CR>%tr<CR>%th {%header row%}<CR><BS><BS>%tbody<CR>%tr<CR>%td {%body row%}
Hope you find it useful!
EDIT: If you like this approach, I created an actual plugin here :) It's less than 100 lines of Vimscript, so if you are into minimal, no-dependency plugins, you'll feel right at home.
Posted on March 21, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.