How can I make vim align the ternary ?: operator nicely?

半城伤御伤魂 提交于 2019-12-08 16:14:24

问题


I like to write code using the ternary ?: operator like this:

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

How can I configure vim so that when pressing Return after having typed createNewItem() indents the next line so that the cursor is in the same column as the last ? so that I can just continue typing : processInput( input );?

I tried looking at the cinoptions-values setting but I didn't see anything relevant.


回答1:


You can achieve this at least partially be adding parentheses:

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

This only works if you break the expression up into three lines: I usually do, but I'll have to admit that your format looks very nice and readable, in cases where the expressions are short.

In the past, I've found the vim mailing list very helpful for this sort of question. It used to be gated to Google groups, so you could consult it as if it were a group there; I'm not sure what the current status is (since I can't access Google groups from work).




回答2:


Inspired by a roughly similiar question I exercised my vimscript-fu and created a little script to do this job:

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()

I saved this file as vimfiles/indent/after/cpp.vim and added filetype indent on to my .vimrc to toggle loading of indentation plugins. It seems to work good enough!



来源:https://stackoverflow.com/questions/6841410/how-can-i-make-vim-align-the-ternary-operator-nicely

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!