适应性标签在vim中的应用

8

我碰巧在编写代码时发现有些模块使用制表符进行缩进,而其他模块使用空格。许多文本编辑器(如Np ++)都具有某种自适应的制表功能,如果前一行(或代码块)使用空格,则使用空格进行缩进,否则使用制表符。

我没有在vim中看到这样的功能。是否有任何插件或设置可以实现此功能?

4个回答

3

我倾向于像下面的示例一样设置我的环境。 我通常的做法是用空格替换制表符,并在需要覆盖该规则时使用augroup。 Makefile是一个需要使用TAB的好例子,而cpp文件则需要使用空格。

" A tab produces a 4-space indentation
:set softtabstop=4
:set shiftwidth=4
:set expandtab
" replace tabs with spaces unless noted otherwise

" <snip>

augroup CPPprog
   au!
   "-----------------------------------
   " GENERAL SETTINGS
   "-----------------------------------
   au BufRead,BufNewFile,BufEnter             *.cpp,*.c,*.h,*.hpp   set nolisp
   au BufRead,BufNewFile,BufEnter             *.cpp,*.c,*.h,*.hpp   set filetype=cpp
   au FileType                                *                     set nocindent smartindent
   au FileType                                *.c,*.cpp             set cindent
   au BufRead,BufNewFile,BufEnter             *.cpp                 let g:qt_syntax=1
   " turn on qt syntax highlighting (a plugin)
   au BufNewFile,BufRead,BufEnter             *.c,*.h,*.cpp,*.hpp   let c_space_errors=1
   " trailing white space and spaces before a <Tab>

   " <snip>

augroup END

" <snip>

augroup filetype
  au! BufRead,BufNewFile,BufEnter *Makefile*,*makefile*,*.mk set filetype=make
augroup END
" In Makefiles, don't expand tabs to spaces, since we need the actual tabs
autocmd FileType make set noexpandtab

1

0

正如@zkhr所说,你可以使用smartindentautoindent。你也可以使用cindent,这是vim在编辑C/C++文件时使用的默认缩进。

'smartindent'会在某些情况下自动插入一个额外的缩进级别,并适用于类似C的文件。

'cindent'更加可定制,但在语法方面也更加严格。

'smartindent'和'cindent'可能会干扰基于文件类型的缩进,并且不应与之同时使用。

如果你正在编辑特定的文件,并且希望阻止自动缩进,请输入:

:setlocal noautoindent
:setlocal nocindent
:setlocal nosmartindent
:setlocal indentexpr=

0

我认为Vim中没有完全符合您要求的功能。但是您可能想查看copyindent。请参阅:h copyindent。它提供了“自适应制表符”,但不完全符合您的要求。新行上的前导制表符/空格将复制上一行的制表符/空格。但是,如果您增加缩进,则添加制表符或空格的决定将取决于expandtab设置。(您还可以查看preserveindent选项的帮助,这也应该在您的情况下进行设置。)

您还需要通过autoindentsmartindent设置自动缩进。不确定的是,在设置copyindent后,您可能需要重置smartindentautoindent才能使其正常工作(例如,执行:set nosmartindent然后再执行:set smartindent)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接