munikarmanish
munikarmanish

Reputation: 372

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

The following code snippets explain my problem well.

What I want:

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

int
main()
{
    ...
}

What I get (notice the over-indentation before the function name):

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

    int
main()
{
    ...
}

I have set filetype plugin indent on in my ~/.vimrc.

I have looked at this post but the answer in that looks like learning a new programming language. I am a vim fan, but not a vim expert. Isn't there a simpler solution?

Upvotes: 8

Views: 1918

Answers (3)

munikarmanish
munikarmanish

Reputation: 372

Just as I guessed, this had a pretty simple solution! After motivating myself to read the :help 'cinoptions-values', the following configuration was all that's needed to solve this particular problem.

:set cino+=t0

From the help text:

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

Upvotes: 1

FDinoff
FDinoff

Reputation: 31429

What you are seeing is the effect of cino-t (cinoptions setting t). You need to make sure conniptions contains t0 to make the parameter flush with the left margin

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

To do this you need to make sure that it is set for the cpp filetype. (cindent is turned on by the default cpp indent file)

I think just adding set cinoptions+=t0 to your vimrc should be sufficient.

Upvotes: 12

Void
Void

Reputation: 21

You could try these indent options in .vimrc:
" Auto indent
set ai
" Smart indent
set si
" C-Style indent
set cindent

Upvotes: 0

Related Questions