← til

Writing custom Vim template

May 8, 2020

Since Rubocop warns me about missing pragma comment for freezing strings and I'm too lazy to write that every time I open a Ruby file, I've decided to write a template.

" Automatically add frozen string literal to the header of Ruby files.
function! RubyTemplate()
    " Add pragma comment
    call setline(1, '# frozen_string_literal: true')
    " Add two empty lines
    call append(1, repeat([''], 2))
    " Place cursor on line number 3
    call cursor(3, 0)
    " Write file to refresh the buffer
    execute "w"
autocmd BufNewFile *.rb :call RubyTemplate()

The only downside of this approach is writing the file to disk automatically, in order to refresh the buffer.

If you know a better way to achieve this, please let me know on Twitter.