At my work, I am required to follow the house style for indentation, which goes as follows:
- 2 spaces when coding html and ruby
What is the best way to specify different whitespace preferences per filetype?
there are many ways, but here's a simple, easy to understand way. add these lines to your
+1 to Peter's answer, but Vim provides another solution as well. If you want to do something more complicated than a single
setlocal, like setting up a whole bunch of options, commands, and mappings at once, then vim's filetype plugin feature comes to the rescue.
You need to have
filetype plugin on or
filetype plugin indent on in your
.vimrc, and then to create a plugin for e.g. ruby you can create
~/.vim/ftplugin/ruby.vim. Technically you can use any commands you like in here, to be run when a Ruby file is loaded, but the recommended ones include
command -buffer, and defining functions. Lots more information is in the User Guide; if you're pretty familiar with scripting vim then jump to
:help 41.11, otherwise read
:help usr_40 and
Peter's answer is straightforward enough, but unfortunately the options aren't right. You need to use the following options instead:
- You can make vim show tab characters by using
- Once you have the tab/space options set correctly, you can make vim repair the file (replace spaces with tabs or vice versa) using the
There's also a nice vim script: DetectIndent which tries to detect the indentation of a file that you open. It's very handy if you work with many files with different coding style.
I use an autocommand in my .vimrc:
:autocmd BufReadPost * :DetectIndent
To insert space characters whenever the tab key is pressed, set the 'expandtab' option:
Next step is to control the number of space characters that will be inserted when the tab key is pressed, set the 'tabstop' option. For example, to insert 2 space for a tab, use: