如何在 vim 中只使用 tab (而不是空格)

我更喜欢使用 tab而不是 white space(可能与其他大多数略有不同)

但是我发现,当我在行的末尾按下 Enter时,它会增加一些 留白,但是不会增加 标签。所以,我必须删除它们,然后按 标签键。

我想知道如何将 vim 设置为:

  1. 只使用 标签缩进线条
  2. 制表符看起来像4个空格,但实际上是一个制表符
  3. 当在一行的末尾点击 enter时,新行只用制表符开始

我在谷歌上搜索了一段时间,但没有找到一个好的答案。提前谢谢你


更新

@ Alok 提供的答案在大多数情况下都很有效。但我刚刚发现,有时,这取决于文件类型。例如,如果您正在编辑一个 haml文件,并且在您的 vimfiles/indent/中有一个 haml.vim,那么所有的制表符将被转换为 space。因此,如果您希望它只是 tab,您应该修改(或删除)相应的缩进文件。

80412 次浏览

The settings you are looking for are:

set autoindent
set noexpandtab
set tabstop=4
set shiftwidth=4

As single line:

set autoindent noexpandtab tabstop=4 shiftwidth=4

autoindent can be replaced with smartindent or cindent, depending upon your tastes. Also look at filetype plugin indent on.

http://vim.wikia.com/wiki/Indenting_source_code

Late to the discussion, just for anyone who struggled to force the use of tabs. With the current version of vim (>8) it was required to set:

:set noet ci pi sts=0 sw=4 ts=4

which expands to:

:set noexpandtab
:set copyindent
:set preserveindent
:set softtabstop=0
:set shiftwidth=4
:set tabstop=4

We can also use this setup with only specific file types, taking advantage of setlocal:

autocmd FileType c,cpp,java,python setlocal noet ci pi sts=0 sw=4 ts=4

For further reference, see: https://vim.fandom.com/wiki/Indent_with_tabs,_align_with_spaces

In my case set indentexpr= did the trick.

I have found the config files which set the annoying behavior with fd python.vim /. In /usr/share/vim/vim90/indent/python.vim there is the line setlocal indentexpr=python#GetIndent(v:lnum). The function python#GetIndent is defined in /usr/share/vim/vim90/autoload/python.vim. This function returned a weird value which was not a multiple of shiftwidth and tabstop. Therefore vim inserted a tab followed by some spaces.

Now, that I have set indentexpr to an empty value, I think vim falls back to autoindent. smartindent and cindent are turned off. (https://vimhelp.org/indent.txt.html)

Of course set noexpandtab is required, too. I am not sure if any other settings are relevant here.


EDIT: autoindent is not perfect, it does nothing more than indent the new line as much as the previous line.

set smartindent
set cinwords=if,elif,else,try,except,finally,with,for,while,class,def

does not work as expected and cindent does not seem suitable for python, so using indentexpr is the way to go after all.

Luckily the indentation function can be configured, see help ft-python-indent or look at the code – that was more informative regarding the disable_parentheses_indenting feature. It seems this is the solution for me:

if !exists('g:python_indent')
let g:python_indent = {}
endif
let g:python_indent.disable_parentheses_indenting = 1

(https://vi.stackexchange.com/a/38824/43863)