Search code examples
pythonvimindentationvim-plugin

Where is `filetype plugin` defined and how to override it?


I am trying set python indentation to use 2 spaces instead of 4 (or 8) spaces. I put the following in my ~/.vimrc:

set expandtab
set shiftwidth=2
set softtabstop=2
set tabstop=2

This works well, as long as I do not put filetype plugin on in the config as well. When I do have filetype plugin on, when I open a python file, set tabstop? will return 8 and the indentation got messed up.

So my questions are: (1) how does the filetype plugin on work and where is the filetype-specific config files located? (2) how can I override the filetype-specific config in my ~/.vimrc (or somewhere else)?


Solution

    1. How does the filetype plugin on work and where is the filetype-specific config files located?

      filetype on enables filetype detection, which does exactly what the name implies.

      filetype plugin on enables both filetype detection and filetype plugins, which are vimscript files that contain filetype-specific commands for setting various options, defining mappings, etc. Those ftplugins are located under $VIMRUNTIME/ftplugin/ and you can make your own under ~/.vim/ftplugin/ or ~/.vim/after/ftplugin/ as well as various places under &runtimepath and/or &packpath.

      Judging by the "python" tag, the ftplugin you are having problems with is $VIMRUNTIME/ftplugin/python.vim, which has this snippet:

      if !exists("g:python_recommended_style") || g:python_recommended_style != 0
          " As suggested by PEP8.
          setlocal expandtab tabstop=4 softtabstop=4 shiftwidth=4
      endif
      
    2. How can I override the filetype-specific config in my ~/.vimrc (or somewhere else)?

      In general, you can choose between two methods:

      • Add FileType autocommands in your .vimrc:

        augroup myFiletypes
            autocmd!
            autocmd FileType foo setlocal this=that
            […]
        augroup END
        
      • Put your settings in their own ftplugins:

        " in after/ftplugin/foo.vim
        setlocal this=that
        

      The latter is cleaner.

      In this specific case, the feature is behind a global variable so you simply keep your settings in your .vimrc "as-is" and add the following line (which will drive your coworkers mad):

      let g:python_recommended_style = 0
      

      as per :help ft-python-plugin.