Vim:缩进制表符,与空格对齐 [英] Vim: Indent with tabs, align with spaces
问题描述
我已经阅读了几个问题和答案:
I've already read several questions and answers:
但是他们都没有为我提供解决方案.
But none of them offers a solution for me.
我真的很想应用"缩进制表符,与空格对齐"的原则,但是当它出现时自动缩进,我没法教Vim正确的做法.
I really want to apply the "Indent with tabs, align with spaces" principle, but when it comes to auto-indentation, I failed to teach Vim how to do that right.
考虑代码,假设 tabstops == 3
, shiftwidth == 3
(>-
表示制表符,而.
(点)表示空格):
(>--
means tab, and .
(a dot) means space):
{
>--long a = 1,
>-->--..b = 2,
>-->--..c = 3;
}
因此,它尽可能地缩进制表符,然后用空格填充其余部分.但这实际上是一种非常糟糕的方法:当某人将以不同的制表符大小阅读此代码时,该代码将被弄乱.标签大小等于8个字符的情况如下所示:
So, it indents with tabs as much as possible, and then fills the rest with spaces. But it is actually a very bad approach: when someone will read this code with different tab size, the code will be messed up. Here what it will look like with tab size equal to 8 chars:
{
>-------long a = 1,
>------->-------..b = 2,
>------->-------..c = 3;
}
这太可怕了.问题是Vim不能区分缩进和对齐.
It is horrible. The problem is that Vim doesn't distinguish between indentation and alignment.
要使它无论使用哪种制表符大小都能正确显示,应按以下方式缩进代码:
To make it look correctly with whatever the tab size is, the code should be indented this way:
{
>--long a = 1,
>--.....b = 2,
>--.....c = 3;
}
然后,无论该选项卡大小如何,此代码都将看起来不错.例如8个字符:
Then, this code will look nice whatever that tab size is. For example, 8 chars:
{
>-------long a = 1,
>-------.....b = 2,
>-------.....c = 3;
}
如何实现?
推荐答案
影响Vim缩进的最有效方法是通过'indentexpr'
.从其:help
:
The most powerful way to influence indenting in Vim is via 'indentexpr'
. From its :help
:
表达式必须返回缩进的空格数.它可以返回"-1"以保持当前缩进(这意味着"autoindent"为用于缩进).
The expression must return the number of spaces worth of indent. It can return "-1" to keep the current indent (this means 'autoindent' is used for the indent).
因为它返回空格的数量,而不是呈现的缩进本身,并且Vim到目前为止仅支持制表符,空格或制表符最大数量的空格(称为softtabstop),无法完成此操作.
As this returns the number of spaces, not the rendered indent itself, and Vim only so far supports tab-, space-, or maximal-number-of-tab-followed-by-spaces (called softtabstop), this cannot be done.
因此,如果您真的想使用这种缩进方法(我个人也喜欢它的纯净和优雅!(但我不使用它)),则必须关闭自动缩进和自动格式化不幸的是,您自己手动完成了全部工作.
So, if you really want to use this indent method (I personally like it for its purity and elegance, too! (but I don't employ it)), you have to turn off auto-indenting and auto-formatting and do the entire stuff manually by yourself, unfortunately.
这篇关于Vim:缩进制表符,与空格对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!