I work on a range of JavaScript projects. In most of these projects, the indentation of JavaScript files is 2 spaces, so I've set my default indentation width to that. However it becomes 1 or 4 in some other projects.

Is there a way to ask Vim to change the indentation style based on the style already used in the current file?

  • Why dont you add such settings in .vimrc for particular filetype? :au BufEnter *.js :set shiftwidth=2. This works for all projects,
    – SibiCoder
    May 28, 2016 at 8:38
  • 5
    @SibiCoder: Because even the same filetype can have different indenting styles across different projects. (eg: projects not belonging to the same company)
    – thameera
    May 29, 2016 at 8:51
  • *.* is just a pattern. You can use filename or path as well. Or, you can use similar auto command like what I gave, for each file. You can instruct the auto command to take the tabwidth of current file and put it for path of this file. Its pretty easy.
    – SibiCoder
    May 29, 2016 at 9:10

2 Answers 2


To add to @Undo 's answer above. Tim Pope too has a plugin that tries to do the same at tpope/vim-sleuth

  • 5
    Sleuth seems to work a bit better than detectindent, in my experience, and also will try to determine the proper indent settings for new files by looking at other files nearby in the filesystem.
    – jamessan
    Feb 3, 2015 at 17:45
  • @jamessan didn't know that, good to know. Feb 3, 2015 at 17:47
  • 2
    Please read our policy on plugin-recommendation answers and add some detail about how exactly to use your recommended plugin to solve the problem. Feb 6, 2015 at 22:17

I haven't used it, but ciaranm/detectindent might be what you're looking for. It seems to be active (last updated 25 days ago), and looks like it does what you want:

A Vim plugin, for automatically detecting indent settings. This plugin adds a :DetectIndent command, which tries to intelligently set the 'shiftwidth', 'expandtab' and 'tabstop' options based upon the existing settings in use in the active file.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.