在 Vim 中,如何自动确定是使用空格还是制表符进行缩进?

Chr*_*own 7 vim indentation whitespace

有时我会编辑其他的源代码,其中流行的风格是使用制表符。在这种情况下,我想保留使用文字选项卡的现有约定。

对于我自己创建的文件,以及使用空格作为主要缩进样式的文件,我希望改用它。

我怎样才能在 vim 中做到这一点?

Chr*_*own 9

您可以在您的中使用类似的东西~/.vimrc来调整以适当使用空格/制表符:

" 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()
Run Code Online (Sandbox Code Playgroud)


Ing*_*kat 6

有各种各样的插件,例如(从我自己的插件开始):