How can I automatically add some skeleton code when creating a new file with vim

后端 未结 8 1367
清歌不尽
清歌不尽 2020-11-29 02:42

When creating a new file with vim, I would like to automatically add some skeleton code.

For example, when creating a new xml file, I would like to add the first lin

相关标签:
8条回答
  • 2020-11-29 02:46

    You can save your skeleton/template to a file, for example ~/vim/skeleton.xml

    Then add the following to your .vimrc

    augroup Xml
        au BufNewFile *.xml 0r ~/vim/skeleton.xml
    augroup end
    
    0 讨论(0)
  • 2020-11-29 02:53

    You can add various hooks when files are read or created. to

    :help event
    

    and read what's there. What you want is

    :help BufNewFile
    
    0 讨论(0)
  • 2020-11-29 02:53

    I wrote a plugin for html:

    On vim scripts: http://www.vim.org/scripts/script.php?script_id=4845

    On Github: https://github.com/linuscl/vim-htmltemplate

    0 讨论(0)
  • 2020-11-29 02:55

    Sorry for the lateness, but I feel the way I do it might be useful to some. It uses the file's filetype, making it shorter and more dynamic than more conventional methods. It was tested only on Vim 7.3.

    if has("win32") || has ('win64')
        let $VIMHOME = $HOME."/vimfiles/"
    else
        let $VIMHOME = $HOME."/.vim/"
    endif
    
    " add templates in templates/ using filetype as file name
    au BufNewFile * :silent! exec ":0r ".$VIMHOME."templates/".&ft
    
    0 讨论(0)
  • 2020-11-29 02:59

    I got something like this in my .vimrc:

    au BufNewFile *.xml 0r ~/.vim/xml.skel | let IndentStyle = "xml"
    au BufNewFile *.html 0r ~/.vim/html.skel | let IndentStyle = "html"
    

    And so on, whatever you'll need.

    0 讨论(0)
  • 2020-11-29 03:04

    It can work with snipmate too:

    augroup documentation
        au!
        au BufNewFile *.py :call ExecuteSnippet('docs')
    augroup END
    
    function! ExecuteSnippet(name)
        execute "normal! i" . a:name . "\<c-r>=TriggerSnippet()\<cr>"
    endfunction
    

    with "docs" the snippet to trigger.

    It works with multi-snippets but then the :messages window appears and it's cumbersome.

    0 讨论(0)
提交回复
热议问题