I often edit different files in vim, some of which use tabs, and some and different amounts of spaces. With this, I have not found a combination of set expandtab, set shiftwidth, set softtabstop, and filetype plugin indent on that fit all use cases. How does one get vim to automatically apply the correct indentation? Some graphical editors on Windows including Notepad++ would use whatever indentation was present on the prior line, and would work with files that mixed tabs and spaces at different indentation levels, so I am asking if there is a way to implement this functionality in vim without using external plugins.


  • I'm guessing this is a duplicate question but in the meantime see :h 'autoindent', :h 'smartindent', :h 'cindent' for starters. The first one, when enabled, simply uses the indent from the previous line.
    – B Layer
    Jul 2, 2018 at 18:43
  • 4
    The existence of Tim Pope's 'vim-sleuth' plugin implies that a robust native solution may not exist.
    – B Layer
    Jul 2, 2018 at 18:56

1 Answer 1


If you want vim to analyze the file and automatically find out how many and which indent chars (tabs, spaces) are used you will have to write some code or find a plugin. To my knowledge there is no such "automatic detection".

But there are some partial solutions that might fit your needs:

  1. Your files could declare modelines. That's a special line inside the file you are editing that can set some options (like the ones you mention). See :help modeline
  2. If you can find a specific pattern about the indent of you files you could write an autocommand. For example if all your C files use tabs but all python files use 4 spaces and so on. Eg.

    autocmd FileType c,cpp set noet sw=8
    autocmd FileType python set et sw=4
  3. The ftplugin files can do the same but might be cleaner for more complex code. They are files that are sourced whenever the filetype for a buffer is set. See :help ftplugins and :help ftplugin.

If you want to find out where an option was last set use :verbose set OPTION? (with the question mark!).

  • 3
    You can also use the ftplugin mechanism of vim instead of autcommands
    – D. Ben Knoble
    Jul 2, 2018 at 22:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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