Search code examples
delphicode-formattingdelphi-xe4code-folding

How do I keep Delphi from automatically expanding folded code regions?


I widely use {$Regions} in my units, but sometimes the VCL editor takes annoying decisions to automatically expand all regions. Is there any way to tell the editor not to expand regions that are collapsed unless I explicity do this by clicking on the + button?


Update from comments:

Unfolding occurs,

  1. with nested procs/funcs. Introducing a new nested "procedure" header. As soon as you type the 'p' character, all other nested procs/funcs are unfolded. This occurss also if, for instance, by mistake, you delete the "end" of any nested proc/func (or anything of the kind).
  2. with regions. If you start a comment with "{", the Region immediately below is unfolded. Starting a comment with "(*" provoques all Regions below to be unfolded and same applies to all procs/funcs under those Regions.

Solution

  • Unfortunately this is one of the problems of Delphi whis is present athleast since Delphi XE if not even from older versions and still hasn't been fixed.

    The reason why code gets automaticaly unfolded is the fact that as soon as Error Insight system detects any syntax error in your unit it treats all the code below that poiunt as non-valid and thus expans all folded code below that point.

    So far the only way that I know to avoid this is to disable the Error Insight. But that means you won't be warned about any potentional syntax errors untill you try to compile your program.

    But I seriously hope Embarcadero will go and fix this soon as it makeswhole code folding system to be useless unles you have Error Insight disabled as you spend more time folding the autoexpanded code again that writing any new code.

    EDIT: Steps to reproduce this (one way of reproducing it)

    Create new application

    Create two new even handlers for OnCreate and OnClose for your form or any two other methods.

    procedure TForm1.FormCreate(Sender: TObject);
    begin
    
    end;
    
    procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
    begin
      //
    end;
    

    In case if you created even handlers make sure there is athleast some code in the lowest handler metrhod or athleast one commented line so that optimizer doesent automatically remove the "empy" event handler.

    Now in top event handler write "Form." and you will se how bottom event handler will be automatically expanded.

    You will see that at this point delphi desent even know when or where current method code block in which syntax error has been detected ends. And this also makes it imposible to properly detect any code blocks below that point.