In Vim, how can I automatically determine whether to use spaces or tabs for indentation

indentationvimwhitespace

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?

Best Answer

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.
        return
    endif

    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
    endif
endfunction

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