Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 226
Frerich Raabe Avatar asked Jul 27 '11 08:07

Frerich Raabe


2 Answers

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

like image 142
James Kanze Avatar answered Sep 20 '22 12:09

James Kanze


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!

like image 42
Frerich Raabe Avatar answered Sep 21 '22 12:09

Frerich Raabe