87

我在使用 Eclipse 和 java 时有点被宠坏了。我开始在 linux 环境中使用 vim 进行 C 编码,有没有办法让 vim 自动为块做适当的间距?

因此,在键入 { 后,下一行将缩进 2 个空格,并且该行上的 return 将使其保持相同的缩进,而 } 将移回 2 个空格?

4

7 回答 7

137

这两个命令应该这样做:

:set autoindent
:set cindent

对于奖励积分,请将它们放在一个名为 .vimrc 的文件中,该文件位于您的 linux 主目录中

于 2008-09-18T22:41:16.690 回答
57

在 vim 中写了所有关于标签的内容,它提供了一些你没有问过的有趣的东西。要自动缩进大括号,请使用:

:set cindent

缩进两个空格(而不是八个空格的一个制表符,vim 默认):

:set shiftwidth=2

要防止 vim 将八个空格转换为制表符:

:set expandtab

如果您想更改文本块的缩进,请使用 < 和 >。我通常将此与块选择模式(v,选择文本块,< 或 >)结合使用。

(我会尝试说服您不要使用两个空格缩进,因为我(和大多数其他人)发现它很难阅读,但这是另一个讨论。)

于 2008-09-18T22:47:32.620 回答
8

vim 的许多功能(如autoindentcindent)默认情况下是关闭的。要真正了解 vim 可以为您做什么,您需要一个像样的~/.vimrc.

一个好的入门者是在$VIMRUNTIME/vimrc_example.vim。如果您想尝试一下,请使用

:source $VIMRUNTIME/vimrc_example.vim

在 vim 中时。

I'd actually suggest just copying the contents to your ~/.vimrc as it's well commented, and a good place to start learning how to use vim. You can do this by

:e $VIMRUNTIME/vimrc_example.vim
:w! ~/.vimrc

This will overwrite your current ~/.vimrc, but if all you have in there is the indent settings Davr suggested, I wouldn't sweat it, as the example vimrc will take care of that for you as well. For a complete walkthrough of the example, and what it does for you, see :help vimrc-intro.

于 2008-09-19T00:35:03.937 回答
5

Simply run:

user@host:~ $ echo set autoindent >> .vimrc
于 2010-04-17T07:10:13.900 回答
4

I think the best answer is actually explained on the vim wikia:

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

Note that it advises against using "set autoindent." The best feature of all I find in this explanation is being able to set per-file settings, which is especially useful if you program in python and C++, for example, as you'd want 4 spaces for tabs in the former and 2 for spaces in the latter.

于 2011-06-22T00:33:24.763 回答
0

并永远记住这个关于空格 + 制表符的古老解释:

http://www.jwz.org/doc/tabs-vs-spaces.html

于 2008-09-18T23:09:28.200 回答
-1

尝试:

设置 sw=2

设置 ts=2

设置智能缩进

于 2008-09-18T22:40:44.727 回答