【问题标题】:How can I make vim align the ternary ?: operator nicely?如何让 vim 对齐三元 ?: 运算符?
【发布时间】:2011-07-27 08:24:12
【问题描述】:

我喜欢像这样使用三元 ?: 运算符编写代码:

std::string result = input.empty() ? createNewItem()
                                   : processInput( input );

我如何配置 vim 以便在键入 createNewItem() 后按 Return 缩进下一行,以便光标与最后一个 ? 在同一列中,以便我可以继续键入 : processInput( input );

我尝试查看cinoptions-values 设置,但没有看到任何相关内容。

【问题讨论】:

    标签: c++ vim indentation


    【解决方案1】:

    您至少可以通过添加括号来实现这一点:

    std::string result = (input.empty()
                          ? createNewItem()
                          : processInput( input ));
    

    这只有在将表达式分成三行时才有效:I 通常会,但我不得不承认你的格式看起来非常好,而且 可读,在表达式很短的情况下。

    过去,我发现 vim 邮件列表对这种类型非常有用 的问题。它曾经被限制在 Google 群组中,因此您可以咨询 就好像那里是一群人一样;我不确定目前的状态是什么 (因为我无法从工作中访问 Google 群组)。

    【讨论】:

      【解决方案2】:

      受到roughly similiar question 的启发,我锻炼了我的 vimscript-fu 并创建了一个小脚本来完成这项工作:

      if (!exists("*CppIndentDepth"))
          function CppIndentDepth()
              let lineno = v:lnum
              let lastQuestionMark = match(getline(lineno-1), "?[^?]*")
              if lastQuestionMark != -1
                  return lastQuestionMark
              endif
              return cindent(lineno)
          endfunction
      endif
      
      set indentexpr=CppIndentDepth()
      

      我将此文件保存为vimfiles/indent/after/cpp.vim 并将filetype indent on 添加到我的.vimrc 以切换缩进插件的加载。它似乎工作得很好!

      【讨论】:

        猜你喜欢
        • 2011-12-24
        • 2021-12-09
        • 1970-01-01
        • 1970-01-01
        • 2022-01-04
        • 2017-01-01
        • 2018-09-10
        相关资源
        最近更新 更多