return 0
return 0

Reputation: 4396

How to configure vim such that it automatically configures itself to fit a particular file type?

As a simple example, when I write my c/c++/java etc on vim, I expect the tab indent to be 4 spaces. However, if I work on a html file, I expect the intent to be 2 spaces. How do I set .vimrc such that it detects what file I am working on and with that information sets itself?

Thanks.

Upvotes: 0

Views: 62

Answers (1)

Gordonium
Gordonium

Reputation: 3497

The command filetype indent plugin on will indent automatically based on filetypes using what's in your indent folder. There are lots of options that you can manually change (such as cindent and the like) but the above command will take care of most of that for you and actually changing cindent or smartindent yourself can mess things up a bit in my experience.

So, you want your own custom settings for certain files? If you want 2 indents for html files then do this:

  1. Put filetype indent plugin on in your .vimrc file.
  2. Create a html.vim file.
  3. Put the following code in the file:

setlocal shiftwidth=2

setlocal tabstop=2

  1. Save the file to ~/.vim/after/ftplugin. (If you're on Windows then probably try $HOME/vimfiles/after/ftplugin). If that doesn't work then put them in ~/.vim/ftplugin instead but this last option won't necessarily override other plugins.

Here's some more info if people are interested.

There are a number of options for plugins but you specifically asked for edits to the .vimrc so you basically need to understand the different types of indents that vim uses. These are the very basic ones. The autoindent options are below.

Basic

  • tabstop, which changes the width of tab. This is the main value to set.
  • shiftwidth is all about indentation (e.g. the >>, << and == commands).
  • If you set expandtab you will indent softtabstop amound of spaces. I.e. expandtab converts tabs into a certain number of spaces. I think if you want to insert a block tab instead of a number of spaces when :set expandtab is used, you can just enter block visual mode and press tab. For example CTRL+v,TAB, but I could be wrong.

Automatic indentation

  • autoindent just picks the indentation from previous lines. So if you're working on a line, switch to normal mode and type o to insert in the line below then you will ident automatically as per the line you were just on.

Upvotes: 2

Related Questions