Sometimes I edit others source code where the prevailing style is to use tabs. In this case, I want to keep the existing convention of using literal tabs.

For files I create myself, and files that use spaces as the prevailing indent style, I wish to use that instead.

How can I do this in vim?


You can use something like this in your ~/.vimrc to adjust to use spaces/tabs as appropriate:

" By default, use spaced tabs.
set expandtab

" Display tabs as 4 spaces wide. When expandtab is set, use 4 spaces.
set shiftwidth=4
set tabstop=4

function TabsOrSpaces()
    " Determines whether to use spaces or tabs on the current buffer.
    if getfsize(bufname("%")) > 256000
        " File is very large, just use the default.

    let numTabs=len(filter(getbufline(bufname("%"), 1, 250), 'v:val =~ "^\\t"'))
    let numSpaces=len(filter(getbufline(bufname("%"), 1, 250), 'v:val =~ "^ "'))

    if numTabs > numSpaces
        setlocal noexpandtab

" Call the function after opening a buffer
autocmd BufReadPost * call TabsOrSpaces()

There are a variety of plugins for that, for example (starting with my own):

  • My IndentConsistencyCop examines the indent of the buffer and analyzes the used indent widths and methods. If there are conflicting ones or if bad combinations of tabs and spaces are found, it alerts you and offers help in locating the offenders - just like a friendly policeman: >
  • Indent Finder is a Python script and Vim plugin that scans any loaded buffer and configures the appropriate indent settings
  • yaifa.vim is a port to vimscript of the above
  • detectindent.vim by Ciaran McCreesh tries to auto-detect the indentation settings
  • GuessIndent is based on detectindent.vim
  • indentdetect.vim by Eric Van Dewoestine performs a simple detection and can set defaults based on the filespec
  • matchindent.vim detects tabs, 2 and 4-space indents and adapts the indent settings accordingly
  • sleuth.vim by Tim Pope automatically adjusts 'shiftwidth' and 'tabstop' heuristically (via a simplistic sampling that does not check for bad or inconsistent indents) or by looking at other files of the same type
  • filestyle highlights tabs when 'expandtab' is set, trailing spaces, and lines longer than 'textwidth', but doesn't actually check conformance to indent
  • ShowSpaces highlights spaces inside indentation, per buffer / filetype.
  • Indent Detector run when a file is opened or written, has warnings about mixed tab / space indent, and can adapt Vim's corresponding options automatically.

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.