shime
shime

Reputation: 9018

Using template files in Vim

I am trying to use a template for Ruby files, by adding this to my .vimrc:

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)
endfunction
autocmd BufNewFile *.rb :call RubyTemplate()

However, this doesn't work and when I open a new Ruby file, it's empty.

Everything works as expected if I issue an :e! afterwards. However, this doesn't work if I add e! to the function, so I have to manually fire it every time.

What am I doing wrong?

Upvotes: 0

Views: 359

Answers (2)

SergioAraujo
SergioAraujo

Reputation: 11830

Noah Frederick has an elegant solution that allows us to insert snippets manually or automatically.

It uses ultisnips plugin and two files

" after/plugin/ultisnips_custom.vim
if !exists('g:did_UltiSnips_plugin')
  finish
endif

augroup ultisnips_custom
  autocmd!
  autocmd BufNewFile * silent! call snippet#InsertSkeleton()
augroup END

and

" autoload/snippet.vim    
function! s:try_insert(skel)
  execute "normal! i_" . a:skel . "\<C-r>=UltiSnips#ExpandSnippet()\<CR>"

  if g:ulti_expand_res == 0
    silent! undo
  endif

  return g:ulti_expand_res
endfunction

function! snippet#InsertSkeleton() abort
  let filename = expand('%')

  " Abort on non-empty buffer or extant file
  if !(line('$') == 1 && getline('$') == '') || filereadable(filename)
    return
  endif

  call s:try_insert('skel')
endfunction

In my case, I have done some changes but now if I create an empty python file, for example, I end up with:

An important note: In my case, if vim or neovim is not detecting the filetype correctly, and it can be done with auto commands, your automatic snippet insertion will not work.

Upvotes: 0

Nitul
Nitul

Reputation: 379

You can use a static template file instead of invoking a function.

For instance, you can create a template file for your ruby scripts in your vim directory as ~/.vim/skeletons/ruby.skel, with the desired contents.

1  # frozen_string_literal: true
2
3

Then in your vimrc you should add the following code:

" Skeleton for .rb files
augroup ruby
    " Remove all existing autocommands in the group
    au!
    au BufNewFile *.rb 0r ~/.vim/skeletons/ruby.skel
augroup end

Upvotes: 1

Related Questions