0

I am currently thrown into a new project where the indentation style is a bit special. The basic rule is to use 'keyword+blank' spaces to indent the next line.

For example:

if () {
   // indent 3 spaces here
}

while () {
      // indent 6 spaces here
}

There are some (or a lot) of exeptions:

  • else if: use same number of spaces as if (3)
  • case in switch/case (2 spaces)
  • ...

1) Is there already a plugin available that can do it for me? According to one of the developers this is called 'smart identation'. Unfortunately VIM's smartindent does something different.

2) If the answer to 1 is no. Is there an easy way to configure vim to respect these rules?

Pieter-Jan
  • 450
  • 5
  • 9
  • one of the answers posted in response to [Changing Vim indentation behavior by file type](http://stackoverflow.com/questions/158968/changing-vim-indentation-behavior-by-file-type?rq=1) suggests the use of a plugin called [autotab](http://www.kylheku.com/cgit/c-snippets/tree/autotab.c). It can be handy if you have existing files conforming with the desired indentation rules – Imran Ali Jan 31 '17 at 12:45
  • Thanks, but I don't think this will work. The information in the tabstop, etc. parameters vim provides can not hold the indentation style I described. – Pieter-Jan Jan 31 '17 at 13:25

1 Answers1

1

I'm not aware of any such plugin, and IMHO this scheme is anything but smart.

However, it is entirely possible to write a custom indent plugin that implements the exact requirements that you have. See :help 'indentexpr'; also, Vim ships with several indent plugins in $VIMRUNTIME/indent/*.vim that can serve as inspiration.

Basically, the algorithm would be like this:

  • Check the previous line for one of the keywords (if, while, and so on).
  • If there's a match, calculate the offset and add that to the previous line's indent (indent(v:lnum - 1)); else, use the previous line's indent as is.
  • If the line contains a }, find the line with the matching {, and use the indent from that line.
Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324