按文件类型设置 Vim 空白首选项
在我的工作中,我需要遵循缩进的内部风格,如下所示:
- 编码 html 时使用 2 个空格,
- 编码 javascript 时使用 ruby 制表符,建议使用 tabwidth=4 为
每个文件类型指定不同的空白首选项的最佳方法是什么?
At my work, I am required to follow the house style for indentation, which goes as follows:
- 2 spaces when coding html and ruby
- tabs when coding javascript, with tabwidth=4 recommended
What is the best way to specify different whitespace preferences per filetype?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
方法有很多,但这里介绍一种简单易懂的方法。将这些行添加到您的
~/.vimrc
中:there are many ways, but here's a simple, easy to understand way. add these lines to your
~/.vimrc
:彼得的答案很简单,但不幸的是选项并不正确。您需要使用以下选项:
另请注意:
:set list
使 vim 显示制表符。:retab!
命令让 vim 修复文件(用制表符替换空格,反之亦然)。Peter's answer is straightforward enough, but unfortunately the options aren't right. You need to use the following options instead:
Also note:
:set list
.:retab!
command.对 Peter 的回答+1,但 Vim 还提供了另一种解决方案。如果您想做一些比单个
setlocal
更复杂的事情,比如一次设置一大堆选项、命令和映射,那么 vim 的文件类型插件功能就可以帮上忙。您需要在
.vimrc
中添加filetype 插件
或filetype 插件缩进
,然后为例如 ruby 创建一个插件,您可以创建~/.vim/ftplugin/ruby.vim
。从技术上讲,您可以在此处使用任何您喜欢的命令,在加载 Ruby 文件时运行,但推荐的命令包括setlocal
、map
、command -buffer
,并定义函数。用户指南中有更多信息;如果您非常熟悉 vim 脚本,请跳转到:help 41.11
,否则请阅读:help usr_40
和:help usr_41
。+1 to Peter's answer, but Vim provides another solution as well. If you want to do something more complicated than a single
setlocal
, like setting up a whole bunch of options, commands, and mappings at once, then vim's filetype plugin feature comes to the rescue.You need to have
filetype plugin on
orfiletype plugin indent on
in your.vimrc
, and then to create a plugin for e.g. ruby you can create~/.vim/ftplugin/ruby.vim
. Technically you can use any commands you like in here, to be run when a Ruby file is loaded, but the recommended ones includesetlocal
,map <buffer>
,command -buffer
, and defining functions. Lots more information is in the User Guide; if you're pretty familiar with scripting vim then jump to:help 41.11
, otherwise read:help usr_40
and:help usr_41
.还有一个很好的 vim 脚本: DetectIndent 它尝试检测您打开的文件。
如果您处理许多具有不同编码风格的文件,这将非常方便。
我在 .vimrc 中使用自动命令:
There's also a nice vim script: DetectIndent which tries to detect the indentation of a file that you open.
It's very handy if you work with many files with different coding style.
I use an autocommand in my .vimrc:
要在按下 Tab 键时插入空格字符,请设置 'expandtab' 选项:
下一步是控制按下 Tab 键时将插入的空格字符数,设置 'tabstop' 选项。例如,要为制表符插入 2 个空格,请使用:
ref: http://vim.wikia.com/维基/Converting_tabs_to_spaces
To insert space characters whenever the tab key is pressed, set the 'expandtab' option:
Next step is to control the number of space characters that will be inserted when the tab key is pressed, set the 'tabstop' option. For example, to insert 2 space for a tab, use:
ref: http://vim.wikia.com/wiki/Converting_tabs_to_spaces