vimfile-typevim-pluginftplugin

How do I avoid cumulative filetype commands in vim?


Let's say I load up a python file in vim. A quick check of :scriptnames shows that my ~/.vim/ftplugin/python/python.vim file loads as expected. One of the commands in this file highlights all characters that are past the 80th column. Now lets say I open a C++ file in another buffer (therefore running ~/.vim/ftplugin/cpp/cpp.vim). Although the new commands are executed, the settings in python.vim still apply; therefore characters are highlighted past the 80th column in my C++ file.

Is there anyway to make filetype commands not cumulative like this? I have filetype plugin indent on in my .vimrc.


Solution

  • The problem is that both 'colorcolumn' and :match (you didn't specify whether you use the new setting or the older highlight approach) are local to the window, but ftplugins should only set buffer-local settings.

    Why are these settings window-local? That allows you to have the same buffer displayed in two windows, one with, and one without the highlighting.

    What can you do to prevent this?

    a) Don't set this in the ftplugin, and instead use mappings to toggle the colorcolumn on/off.

    b) Put :setlocal nocolorcolumn into all ftplugin scripts (e.g. in ~/.vim/after/ftplugin/*.vim) for all filetypes that you're using. This will only work unless you switch between different filetypes in the same window.

    c) The correct (but most complex) way to solve this is through a couple of :autocmds on BufWinEnter, BufWinLeave, and WinLeave events.