← til

Writing custom Vim template

May 8, 2020
vim

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"
endfunction
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.


Did you like this article? You can follow me on Twitter or subscribe to the RSS feed if you'd like to follow along.