2

I usually use the vim re-indent operator ('=') in order to indent my sourcecode according to its syntax. I also use it on the whole file, especially if I have to read sourcecode that was written by someone else and they have different tab settings or something like that ('gg=G' is really helpful there). This is only problematic when I have something like

(1) int main() {
(2)     for (int i=0; i<3; i++) {
(3)     //for (int i=0; i<4; i++) {
(4)         std::cout << i << std::endl;
(5)     }
(6) }

When I try to indent this code, I get the following indentation levels:

(1) level 0 (which is good)
(2) level 1 (also)
(3) level 2 (could be 1, but I can live with that)
(4) level 2 (good)
(5) level 1 (good)
(6) level 1 (this is the problem)

So the closing brace in line (5) is associated with the opening brace in line (3), which is commented out and therefore not part of the syntax. And the closing brace in line (6) is paired with the opening one in (2), which is wrong. This problem also affects the rest of the code, as functions that come after this one will not be aligned to level 0 but start at level 1.

If the cursor is on the brace in line (5), the correct matching brace in (2) is highlighted, but pressing '%' jumps to line (3). This issue is addressed here, but the supposed solution (a plugin called matchit) only fixes the %, not the =.

Does anyone know of a plugin or hack that solves this issue?

Thanks in advance.

Community
  • 1
  • 1
Viktor Dick
  • 111
  • 1

1 Answers1

2

Use an external program (like indent) instead of vim indentation:

  1. Install indent (e.g., sudo apt-get install indent, on Linux)
  2. On vim, set the equalprg variable:
:set equalprg=indent\ -kr\ -i8\ -ts8\ -sob\ -l80\ -ss\ -bs 
Ingo Karkat
  • 154,018
  • 15
  • 205
  • 275
Claudio
  • 9,427
  • 3
  • 28
  • 67
  • Thanks for the suggestion. This works indeed when indenting the whole file, but if I only want to indent a single line using '==', the program returns with error code 2 and puts the string `indent: Standard input:2: Error:Unexpected end of file` into my source file. I will have to see if this is worth it, i.e. if I only need the 'indent whole file' and 'indent until matching bracket' functions. – Viktor Dick Oct 31 '13 at 13:42
  • @ViktorDick to surpress this warning, `autocmd FileType c,cpp set equalprg=indent\ 2>/dev/null\ -gnu;true` – zhazha Jul 03 '16 at 04:55