您的位置:首页 > 其它

Fix Indentation and Tabs in VIM (Vim格式化操作)

2011-03-27 17:53 417 查看
2011-03-27 wcdj



先看一段简单的tutorial。



Fix Indentation and Tabs in VIM

Thanks to the folks in #vim on freenode, here's a quick tutorial on how to fix the indentation and tabs
in an xml file from within VIM…

First find out what your current settings are by typing:

:filetype

Should return something like “filetype detection:ON plugin:OFF indent:OFF”

1) :set filetype=xml

2) :filetype indent on

3) :e

4) gg=G

Basically what this is doing is setting the filetype to xml (so it can pickup the XML indenting rules (see :e $VIMRUNTIME/indent
for a list of available languages
)

Then turn on indent, then reload it (:e).

The last step is ‘gg=G
' which will acutally retab the entire file
(gg is line 1, and G is last line

).

You can find more info by reading vim help files:

:he gg

:he =

:he G

:he :filetype

Note: Most commands in vim are run with by typing “:command
, you can find help by typing “:help command
” or simply “:he cmd
”. HOWEVER, the main command to retab “gg=G” is NOT preceeded by a “:”
.



看完这段tutorial,我们遇到的问题基本就解决了。









Vim格式化代码功能——gg=G



常用的几个功能:

(1) gg=G 是一个自动缩进的命令 (在命令状态下直接输入,不需要输入冒号),gg是文件首,G是文件尾,所以 gg=G 是整理全部代码。

(2) == 整理当行,加行数整理多行。

(3) ={ 或者 =i{ 整理一个代码块。

(4) mG=nG 当 m 不等于 n 的时候能完成从 m 行到 n 行的局部的缩进。例如,从80行缩进直到100行,你可以用 80G=100G,在命令状态下使用 :set nu 查看行号,一般更习惯将 se nu 直接写入Vim的配置文件,这样每次打开都会显示行号。

(5) 在写代码前,设置自己的代码风格。在配置文件里添加命令:

" 设置缩进和行号

set nu ru ai si ts=4 sw=4

(6) :set equalprg=indent

意思是用indent程序处理等号命令,indent默认是gnu风格。

建议不要改,代码风格应该自己主动养成,=适用于修改代码或者粘贴别处代码后整理缩进。

这里又体现出不用indent的好处了,如果用indent,单纯格式化代码块会丢统一的行首缩进,而且选中的如果不是内部完整的代码块,会出错,把出错的输出贴到了代码里....弊端很多。

参考:

http://forum.ubuntu.org.cn/viewtopic.php?f=35&t=296929&p=2145053

http://blog.zol.com.cn/808/article_807892.html

http://www.chovy.com/web-development/fix-indentation-and-tabs-in-vim/#comments
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: