Vim 缩进 C/C++ 当类型和名称在不同的行时效果不佳

Vim indents C/C++ functions badly when the type and name are in different lines

以下代码片段很好地解释了我的问题。

我想要的:

template<class T>
ostream& operator<<(ostream& out, const vector<T>& v)
{
    ...
}

int
main()
{
    ...
}

我得到了什么(注意函数名前的过度缩进):

    template<class T>
ostream& operator<<(ostream& out, const vector<T>& v)
{
    ...
}

    int
main()
{
    ...
}

我的 ~/.vimrc 中有 set filetype plugin indent on

我看过 this post,但其中的答案看起来像是在学习一种新的编程语言。我是 vim 粉丝,但不是 vim 专家。没有更简单的解决方案吗?

您可以在 .vimrc 中尝试这些缩进选项:
" 自动缩进
设置ai
" 智能缩进
设置 si
" C 样式缩进
设置 cindent

您看到的是cino-t(cinoptions 设置t)的效果。您需要确保 conniptions 包含 t0 以使参数与左边距齐平

来自:h cino-t

                                            cino-t
    tN    Indent a function return type declaration N characters from the
          margin.  (default 'shiftwidth').

            cino=               cino=t0             cino=t7
                  int             int                        int
              func()              func()              func()

为此,您需要确保为 cpp 文件类型设置了它。 (cindent默认cpp缩进文件开启)

我认为只需将 set cinoptions+=t0 添加到您的 vimrc 中就足够了。

正如我所料,这有一个非常简单的解决方案!在激励自己阅读 :help 'cinoptions-values' 之后,下面的配置就是解决这个特定问题所需要的。

:set cino+=t0

来自帮助文本:

tN    Indent a function return type declaration N characters from the
      margin.  (default 'shiftwidth').

        cino=               cino=t0             cino=t7
              int             int                        int
          func()              func()              func()