// -*- ASCII:EDT -*-
// completeEnv.edt
// completes the current
// environment
// (schlicht 20010703)
// -----------------------------
// Modified by alex: 20011107
// Active String: \begin{?}}
// Active String: \end{{
// Complete the environment
///////////////////////

SetTracking(0);
BeginGroup;

Mark(0);
// Anything preselected? Then give the macro
// a chance to find the environment again:
IfSel(0,">","CharRight;");

// Called by an Active String?
SelCharLeft;
LetReg(0,'');
IfStr("%S","}","=","LetReg(0,'0');");
IfStr("%S","{","=","LetReg(0,'1');");

// Check for Active String \end{} (the same as \end{{)
IfStr('%!0','0','=',>
  !`FindInString("%L","\end{}", 1,2, 1110, %c-2);>
    IfNum(%!2,%c-1,!"=",!"LetReg(0,'1');");`);

// Filter out things like \begin{tabular}{l  p@{6cm}}
IfStr('%!0','0','=',>
  !`FindInString("%L","{", 1,2, 1110, %c-2);>
    FindInString("%L","\begin{", 1,3, 1110, %c-2);>
    IfNum(%!2,%!3,"<>","Goto(0);SetTracking(1);EndGroup;Exit;");`);

Delete;

IfisMode("DTX","%!m",>
 !"IfStr('%?','macrocode','=',>
    !'LetReg(6,!|%    |);>
      LetReg(7,||);',>
    !'LetReg(6,!|% |);>
      LetReg(7,!|%   |);');>
   ",>
 !"LetReg(6,'');>
   LetReg(7,'  ');");

IfStr("%!0","0","=",>
  !`>
    NewLine;>
    InsertBullet;>
    NewLine;>
    Ins('%!6\end{%?}');>
    LineUp(2);>
    TrackCaret;>
    NextBullet;>
    CharLeft;>
    Ins('%!7');//Indent it<>
    NextBullet;>
   `);

IfStr("%!0","1","=",>
  !`>
    Mark(0);>
    Ins("}");>
    SetSel(0);>
    MatchDelimiter(0,0,1,1);>
    IfOK(>
      !``SaveFind;>
         SetFindTextSelect(0);>
         SetNotFoundNotify(0);>
         SetSearchSelected;>
         SetSearchCurrentDoc;>
         SetSearchCyclic(0);>
         SetSearchEntire(0);>
         SetSearchForward(1);>
         SetRegEx(1);>
         SetSearchCaseSensitive(1);>
         SetFindStr("\\begin\{\(*\)\}");>
         IfFound(>
           !"GetTag(0, 9); // Get the Current Environment Name in the local Register 9<>
             Goto(0);>
             Ins('%!9');>
             CharRight;>
             SetSel(0);>
            ",>
           !"Goto(0);>
             SetSel(0);>
             LetReg(0,'');>
            ");>
         RestoreFind;>
       ``,>
       ``>
         Goto(0);>
         CharRight;>
         CharLeft;>
         LetReg(0,'');>
       ``);>
   `);


EndGroup;
SetTracking(1);
Refresh(1);

IfStr("%!0","1","=",>
  !`MatchDelimiter(0,0,0,1);`);

End;
