Jepessen
Jepessen

Reputation: 12445

vim autoindent constructor of intherither class: avoid double indentantion

I've following code:

MyClass::MyClass() :
  BaseClass() {
  doThis();
  doThat();
}

If I autoindent the code with vim using gg=G I obtain following result:

MyClass::MyClass() :
  BaseClass() {
    doThis();
    doThat();
  }

Constructor code has a one more indentantion, and the closing bracket is not aligned with the constructor, but with the base class definition (probably for the same reason of above rows).

Is there a way to obtain the first code snippet with autoindentation?

At the moment my cino variable is set in the following way inside the .vimrc:

set cino=N-s,l1,b1,g0,i0

Thanks for replies.

Upvotes: 0

Views: 86

Answers (1)

Noah
Noah

Reputation: 261

You can do it with the indentexpr option. In a nutshell you'll have to write your own function that calculates the indent. I wrote a short script that does what you're asking although I didn't make it robust in the interest of time.

function! MyIndent()
  if getline(v:lnum - 2) =~ '^\s*\(\w\)*::\(\w\)*()\s*:\s*$'
        \ && getline(v:lnum - 1) =~ '^\s*\(\w\)*\s*()\s*{\s*$'
    return cindent(v:lnum) - &shiftwidth
  endif
  if getline(v:lnum) =~ '^\s*}\s*\(//.*\|/\*.*\)\=$'
    call cursor(v:lnum, 1)
    silent normal %
    let lnum = line('.')
    if lnum < v:lnum
      if getline(lnum - 1) =~ '^\s*\(\w\)*::\(\w\)*()\s*:\s*$'
            \ && getline(lnum) =~ '^\s*\(\w\)*\s*()\s*{\s*$'
        return cindent(lnum - 1)
      endif
    endif
  endif
  return cindent(v:lnum)
endfunction

If you go to $VIMRUNTIME/indent you'll see a bunch of files that calculate the indent for various programming languages. I found that helpful for writing the script.

Upvotes: 1

Related Questions