24

I'm working on a large codebase, where each file has different indentation conventions: tabs, 4 spaces, 3 spaces, etc.

I currently default on tabs and do set shiftwidth=N expandtab smarttab when I come across a spaces-indented file, but that's annoying.

Is there any functionality in Vim, or a plugin, which can recognize that, for instance, the current buffer uses an indentation with three spaces per shift?

Stefan Majewsky
  • 5,427
  • 2
  • 28
  • 51
  • Crosslink: same question on different sites [indentation - How do I make Vim adapt to the current indenting style of the file I'm editing? - Vi and Vim Stack Exchange](https://vi.stackexchange.com/questions/52/) ■ [whitespace - In Vim, how can I automatically determine whether to use spaces or tabs for indentation? - Unix & Linux Stack Exchange](https://unix.stackexchange.com/questions/63196/in-vim-how-c) ■ [editor - Can vim recognize indentation styles (tabs vs. spaces) automatically? - Stack Overflow](https://stackoverflow.com/questions/9609233) – user202729 Jun 03 '22 at 03:04

2 Answers2

23

Various plugins exist that attempt to handle that situation. Here are a few I found by search for detect indent at vim.org

jamessan
  • 41,569
  • 8
  • 85
  • 85
  • 6
    sleuth seems to work better than DetectIndent, in my five minutes of testing. For whatever reason, DetectIndent makes incorrect guesses on even a simple, consistently formatted C file (it has size 2 tabs and DetectIndent thinks it's size 4). – Kat Oct 23 '14 at 10:04
  • Although sleuth will set hard tab to `tabstop=8` by default. There's the option of (short of modifying sleuth source code on the line `let tabstop = get(a:detected.options, 'tabstop', get(a:detected.defaults, 'tabstop', [4]))[0]`) setting e.g. `let g:sleuth_vim_defaults = {"tabstop": 4}` (where `&ft='vim'`) but as far as I can see that configuration option is undocumented (I figured out looking at `s:UserOptions()` function in the script) && it's local by filetype. – user202729 Dec 30 '22 at 03:53
2

Good question,I'm facing the same problem too, and recently I wrote such a vim plugin for myself:https://github.com/luochen1990/indent-detector.vim

it has the following features:

  • detect mixed indent and echo warnning on bufEnter and bufWrite automatically.
  • switch setting about indenting to fit the current indenting style automatically.
  • detecting time is limited, so you don't need to worry about opening huge files.

I think it is well designed, and need to be known, post an issue on github if you have any suggestion :)

luochen1990
  • 3,689
  • 1
  • 22
  • 37