ManagedMyC: Code folding for functions
This is part 2 of [many?] posts about creating an ANTLR-based language service for Visual Studio.
Since this is a near-trivial feature to add based on the code in my previous post, I’ll go ahead and get it in tonight. We want to fold from the opening { to the closing } of a function, so the first thing to do is find that in the grammar.
declaration_ : class1? type? IDENTIFIER paren_params block | simple_declaration ;
The first alternative in the declaration_ rule is a function: clearly you have return type, name, parameters, and then the definition block. Since the block rule starts with { and ends with }, it’s exactly what we want to fold. We’ll make this work just like the braces; change the rule to add an action to mark the folding region:
declaration_ : class1? type? IDENTIFIER paren_params block { Region( $block.start, $block.stop ); } | simple_declaration ;
Then open up your MyCParserHelper.cs file and add these two Region helper functions immediately above the DefineRegion function already there:
1 2 3 4 5 6 7 8 | public void Region( IToken lh, IToken rh ) { DefineRegion( TextSpanHelper.Merge( ToTextSpan( lh ), ToTextSpan( rh ) ) ); } public void Region( IToken token ) { DefineRegion( ToTextSpan( token ) ); } |
Finally, you need to make sure the AuthoringSink knows that you are making changes to the document’s hidden region markers by adding a line to DefineRegion:
1 2 3 4 5 | public void DefineRegion( TextSpan span ) { Sink.ProcessHiddenRegions = true; Sink.AddHiddenRegion( span ); } |