DEV Community

Federico Ramirez
Federico Ramirez

Posted on • Edited on

4 2

Vim Tips: Snippets without plugins

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
Enter fullscreen mode Exit fullscreen mode

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|
Enter fullscreen mode Exit fullscreen mode

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%}
Enter fullscreen mode Exit fullscreen mode

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay