Search code examples
vimftplugin

Use common code for filetype plugin


I have a common set of commands that I want to run in several different Vim filetype plugins. For instance, for html, xml, and xhtml, there are several settings I want to use in common. Where is the best place to put this common code and how do I load it in the individual plugin files?


Solution

  • Shared code in general

    For reuse of (buffer-local) commands or mappings, you can either define them in a (global) function, and invoke that from the ftplugin:

    " Put this in your .vimrc, or make it an autoload function.
    function SetupCommands()
        command! -buffer ...
    endfunction
    
    " in your ftplugin script:
    call SetupCommands()
    

    Or, just put them into a separate script that you :source on demand, e.g. ~/.vim/mysetup.vim:

    " in your ftplugin script:
    runtime mysetup.vim
    

    Filetype inheritance

    Your question however is about a special form of reuse: XML, HTML, and (X)HTML have a lot in common. There's no authoritative way to structure it: HTML is-a form of XML (but with broken validity), XHTML probably both is-a XML and is-a HTML.

    For example, I define abbreviations for HTML in ~/.vim/ftplugin/html_abb.vim:

    inoremap <buffer> <C-CR> <lt>br>
    

    and inherit (and override) this in ~/.vim/ftplugin/xhtml_abb.vim:

    runtime! ftplugin/html_abb.vim
    inoremap <buffer> <C-CR> <lt>br/>
    

    With the :runtime approach, you can even mix and match: Define tools for the generic XML and inherit them for HTML (even though they may complain about the syntax), but define abbreviations for HTML and inherit them for XHTML, but not XML. Vim provides all the flexibility, it's yours to decide on a structure that works well for you.