vimrc: execute multiple lines only for certain filetypes

Viewed 112

There are a few lines in my .vimrc that I only want to use for certain file types (HTML in my case)

Currently it looks like

autocmd! FileType html set matchpairs+=<:>
autocmd! FileType html abb <div> <div><CR><\div><up><CR><TAB>
autocmd! FileType html abb <span> ...etc.

I was wondering, if I really need to retype the first part every time, or something like

autocmd! FileType html[
    set matchpairs+=<:>
    abb <div> <div><CR><\div><up><CR><TAB>
    abb <span> ...etc.
]
2 Answers

Vim's "filetype" mechanism already handles your needs gracefully so you don't have to pollute your vimrc with filetype-specific stuff.

If it doesn't already exist, create $HOME/.vim/after/ftplugin/html.vim (on Unix-like systems) or $HOME/_vimfiles/after/ftplugin/html.vim (on Windows) and put the following content:

setlocal matchpairs+=<:>
abbreviate <buffer> <div> <div><CR><\div><up><CR><TAB>
abbreviate <buffer> <span> ...etc.

Note that…

  • you don't need autocommands anymore,
  • :help :setlocal is preferred over :help :set,
  • <buffer> is added to your mappings and abbreviations to prevent them from leaking to other filetypes, see :help :map-<buffer>.

See :help filetype.

Use \ for line continuation and | to separate commands.

autocmd! FileType html
    \ set matchpairs+=<:>|
    \ abb <div> <div><CR><\div><up><CR><TAB>|
    \ abb <span> ...etc.

See :help :bar and :help line-continuation.

Related