Viktor Dick
Viktor Dick

Reputation: 111

How do I indent lines with vim when there are commented-out braces?

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.

Upvotes: 2

Views: 233

Answers (1)

Claudio
Claudio

Reputation: 10947

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 

Upvotes: 2

Related Questions