Strange folding in Vim when there's a { and a } on the same line.&*

266 views Asked by At

I am currently editing a C++ file with twp function similar to

int func_name_1(int param) {
   do_stuff();
   and_more();
}

int func_name_2(int param) {
   do_different_stuff();

   STRUCT_TYPE s = {5, 8, 10, 12};
   do_something_with(s);
}

If I do a zc on the word func_name_1, vim folds the function, as expected, so that it now looks like

int func_name_1(int param) {--------------------

On func_name_2 however, the function is folded like so:

int func_name_2(int param) {---------------------
   do_something_with(s);
}

which is not exactly what I want. For some reason the opening and closing {} on one line seem to disturb the folding algortithm.

If someone knows how I can get a "better" folding, I'd appreciate any hinter into the right direction.

Edit the options that I believe are relevant for this problem are set in my buffer like so

set foldmarker={,}
set foldmethod=marker
set foldtext=getline(v:foldstart)

Edit II: If I change the line with the opening and closing {...} to STRUCT_TYPE s = { 5, 8, 10, 12}; (Note the space after the {), then the folding works as expected.

2

There are 2 answers

1
René Nyffenegger On BEST ANSWER

Oh.... I see....

:help fold-marker tells me: Markers can have a level included [..] The following number specifies the fold level

So, the 5 immediatly after the { specified the fold level, which messed things up.

1
sidyll On

The zc command closes the current fold. You may have a folder created to be able to close it, so your problem was on creating the fold and not closing it.

To create the fold use zf or zF. zf Works on visual mode, and also on a motion like zf2j to create a fold on 2 lines down. zF already works in a "line-wise" way.

The most practical way, in your case, would be to position the cursor on the bracket (using f{ for example) and run zf% to create and close a fold that goes to the matching bracket. Anyway, it would be even more practical if that bracket was on another line (so you could use ]] to go to it) but that's a convention out of the scope of this answer :-)