msgbartop
by Brian Neal
msgbarbottom

18 Nov 09 Vim: Different Settings For Different File Types

Old habits die hard. I have been using 3 space indents for C and C++ code for as long as I have been a programmer. A little over a year ago I dove head-first into Python, and eventually discovered PEP 8. PEP 8 is basically the style guide for the Python community. I read it with great interest and took just about everything to heart, except for the recommended 4-space indents. I just could not shake my old habit.

Eventually as I got more and more excited about Python I decided to wholly embrace the customs of the community. But how could I easily tell my favorite editor Vim to use 4-space indents for just Python code? I still do a lot of C++ at work, and I still like 3-space indents in other file types.

My first attempt was to use a Vim modeline embedded right in my source files. At the bottom of my Python files I placed this line:

# vim: set sw=4 ts=4:

When Vim first opens a file, it scans the first and last few lines in the file, looking for modelines, and will use the settings just for that file.

This obviously worked, but soon I found it ugly and distracting to have that at the bottom of each file. And sometimes I would forget to put it there, and not realize it until a bunch of code had been written.

It turns out there is a far easier way, but it took some digging to discover. Vim has a very elaborate system of determing file types. If you peek into your Vim installation directory, you’ll see a ftplugin directory. This directory is full of little files that get executed once the type of a file has been determined. Some people on the Web suggest that you should modify these files directly. Thus I could modify the ftplugin/python.vim file, and place my tabstop and shiftwidth settings in there. But you would be modifying a Vim file, and your changes would get lost the next time you upgrade Vim.

There is a much better solution. After Vim executes the python.vim file in the ftplugins directory, it looks for a file called ~/.vim/after/ftplugin/python.vim (on Unix; on Windows I’ve had luck with C:\Progam Files\Vim\vimfiles\after\ftplugin\python.vim). If this file exists, it will be executed after the “official” python.vim file.

Inside your personal python.vim file, the documentation says to use the “setlocal” instead of “set” command. Thus, my file looks like:

setlocal tabstop=4
setlocal shiftwidth=4

Although to be honest, I’ve used the regular set for some time (by accident) without seeing any strange effects.

Happy Vimming!

Tags:

Comments are closed.