Q: Get tab width from file I have tabstop=4 and expandtab set in my vimrc. Is there a way of making Vim automatically set the tab width value based on what is used in the file that is currently being edited, or do I have to set it manually each time I edit something that doesn't use 4 spaces per tab?

A: You can try vim-sleuth.

This plugin automatically adjusts 'shiftwidth' and 'expandtab' heuristically based on the current file, or, in the case the current file is new, blank, or otherwise insufficient, by looking at other files of the same type in the current and parent directories. In lieu of adjusting 'softtabstop', 'smarttab' is enabled.


A: Another plugin, YAIFA

This plug-in will automatically try to detect the kind of indentation in your file and set Vim's options to keep it that way. It recognizes three types of indentation:
1.- Space: Only spaces are used to indent.
2.- Tab: Only tabs are used.
3.- Mixed: A combination of tabs and space is used. e.g.: a tab stands for 8 spaces, but each indentation level is 4 spaces.
The values of 'expandtab' and 'shiftwidth' set in your vimrc will be used as the default values.

It works like a charm.

A: autotab.c analyzes an up to 5000 line sample of a file to determine the expandtab, tabstop and shiftwidth parameters.
It uses a fairly elaborate algorithm which actually renders the sample using different tab sizes to figure out which one produces the nicest line-over-line alignment based on various heuristics.
Written in C, it's very fast (no noticeable delay when loading a file) and has no dependencies other than a few functions in the standard C library.
