vimfile-typelanguage-detection

How are programming language specific settings called in Vim and how to detect + overwrite them?


The editor Vim comes with syntax highlighting for many different programming languages.
Questions:

  1. In Emacs, language-specific settings are called "modes". In Vim, however, the term "mode" refers to command or insert mode. So what is the Vim term for programming language specific settings?
  2. Is the programming language of a document determined from its file name extension, or from its contents?
  3. How can I find out which programming language specific mode Vim is in?
  4. How can I overwrite that once and for all for a certain class of documents?

Solution

  • Posting an answer, as requested.

    (1) In Emacs, language-specific settings are called "modes". In vim, however, the term "mode" refers to command vs insert mode. So what is the vim term for programming language specific settings?

    The equivalent Vim term is filetype. Vim uses filetypes to apply language-specific options, indentation, syntax highlighting, key mappings, etc. This is described in detail in the help, see :h filetype.

    To enable automatic filetype detection and handling, you'd normally add something like this to your vimrc:

    filetype plugin indent on
    syntax on
    

    To override the settings Vim gives you this way, you need to add the overrides to a file ~/.vim/after/ftplugin/<filetype>.vim (or equivalent). See :h ftplugin for more details.

    (2) Is the programming language of a document determined from its file name extension, or from its contents?

    Both methods are used. Vim does most filetype detection in a file filetype.vim in it's runtime directory. To find out the exact location of this file:

    :echo $VIMRUNTIME.'/filetype.vim'
    

    Plugins can add more filetypes, and / or override detection and handling of standard ones.

    (3) How can I find out which programming language specific mode vim is in?

    From Vim:

    set ft?
    

    (4) How can I overwrite that once and for all for a certain class of documents?

    To change the filetype of the current file:

    :setf <new_filetype>
    

    or

    :setl ft=<new_filetype>
    

    To make the change permanent: do that from a modeline (cf. :h modeline). For example:

    # vim: filetype=python
    

    You can also use autocmds to achieve the same effect:

    autocmd BufRead,BufNewFile *.py setlocal filetype=python
    

    Do read :h filetype, where all this is described in detail.