// Compiles Selected Text on "_temp" file.

  Requires(20170103); // Requires this build of WinEdt to work properly
  // Already Compiling Selected Text...
  IfStr("%N",!"_temp","=",!"ShowConsole(1);Exit;");
  // Already Running...
  IfConsoleRunning(!"ShowConsole(1);>
    Prompt('Another application is already running in WinEdt''s Console.');>
    ShowConsole(1);FocusConsole(1);Exit;");

  PushTagsandRegisters;

  Assign('Main_File','%!F');
  Assign('old_src','%0');
  SetExitHandler('Exit_Handler');

  LetReg(7,'%P');
  LetReg(6,'%T');
  // New Document without Main file Set (why not?!)
  IfStr('%!7','','=',!'LetReg(7,"%b\Temp");CreateFolders("%!7")');
  IfStr('%!6','','=',!'LetReg(6,".tex");');

  // Delete the working output files...
  IfFileExists("%b\_Err.log",!"DeleteFile('%b\_Err.log')");
  IfFileExists("%b\_Out.log",!"DeleteFile('%b\_Out.log')");
  IfFileExists("%!7\_temp%!6",!"DeleteFile('%!7\_temp%!6')");
  ListFolderFiles(5,'%P','',0,1);
  LstEnum('%!5','%\');
  LstGetCount(5);
  Repeat(%!5,>
    !`LstGetItem(2,%!c-1);>
      GetFileName('%!2',3);>
      IfStr('%!3',!'_temp',!'=',!'DeleteFile("%P\%!2");');>
      ProcessMessages;>
     `);
  LstRelease;
  ListFolderFiles(5,'%O','',0,1);
  LstEnum('%!5','%\');
  LstGetCount(5);
  Repeat(%!5,>
    !`LstGetItem(2,%!c-1);>
      GetFileName('%!2',3);>
      IfStr('%!3',!'_temp',!'=',!'DeleteFile("%O\%!2");');>
      ProcessMessages;>
     `);
  LstRelease;

  // Change Execution Modes
  LetReg(0,!"LaTeX");Call(!"Exec_Modes");
  LetReg(0,!"TeX");Call(!"Exec_Modes");
  LetReg(0,!"AMSTeX");Call(!"Exec_Modes");
  LetReg(0,!"PDFLaTeX");Call(!"Exec_Modes");
  LetReg(0,!"PDFTeX");Call(!"Exec_Modes");
  LetReg(0,!"XeLaTeX");Call(!"Exec_Modes");
  LetReg(0,!"XeTeX");Call(!"Exec_Modes");
  LetReg(0,!"LuaLaTeX");Call(!"Exec_Modes");
  LetReg(0,!"LuaTeX");Call(!"Exec_Modes");
  LetReg(0,!"TeXify");Call(!"Exec_Modes");
  LetReg(0,!"PDFTeXify");Call(!"Exec_Modes");
  LetReg(0,!"dvi2ps");Call(!"Exec_Modes");
  LetReg(0,!"dvi2pdf");Call(!"Exec_Modes");
  LetReg(0,!"dvi2ps");Call(!"Exec_Modes");
  LetReg(0,!"ConTeXt");Call(!"Exec_Modes");
  JMP(!"Start");

:Exec_Modes:: =======================================================
  Release("%!0-GUI");
  Release("%!0-High_Priority");
  Assign("%!0-Wait", !|1|);
  Release("%!0-Report");
  Release("%!0-Errors");
  Release("%!0-Warnings");
  Release("%!0-ExitCode");
  Release("%!0-Viewer");
  Release("%!0-View_Search");
  Release("%!0-STD_IO");
  Assign("%!0-No_Interaction", !|1|);
  Assign("%!0-Clean_Build", !|1|);
  Assign("%!0-WinEdt_Console", !|1|);
  Assign("%!0-Hidden_Window", !|1|);
  Assign("%!0-Background_Window", !|1|);
  Assign("%!0-Pause", !|1|);
Return;

:Exit_Handler:: =====================================================
// Restore the Main File and Current Execution Modes even if execution
// is canceled or goes badly wrong for some reason ...
  SetMainFile("%$(|Main_File|);");   // Reset the Main File
  LetStr(0,"%$(|old_src|);");
  Exe("%b\Exec\%$(|Exec-Dir|);\ExeMode.edt");
  PopTagsandRegisters;
  StopWorking;
  UpdateStatus;
Return;

:Start:: ============================================================

  StartWorking("Compile selected text...");

  // Create Temporary File using the same (unicode) format as the Main File %F...
  OpenOutput("%!7\_temp%!6",0,0,0,"%F"); // Open temporary TeX file for writing
  GetSel(1,9);                       // Get Selected Text in %!9
  Translate(2,"%!m","%!9",9);        // Translate Output?

  IfStr('%$(!"Compile-UsePragmaComments");',!'1',!'<>',>
    !'JMP(!"Default_Compiler");');
  GetPreamble("\begin{document}",0);
  IfOK(!'Relax;',!'JMP(!"Default_Compiler");');
  FindInString("%!0",!'%@{ }!TEX @{ }program@{ }=@{ }\(*\)@{ }>',-1,-1,1);
  IfOK(!'LetReg(8,"%#0");',!'JMP(!"Default_Compiler");');
  FindInString("%!8",!'\#~{?}{pdflatex|xelatex|lualatex|latex}~{?}',-1,-1,1);
  IfOK(!'JMP(!"LaTeX_File");');

:Default_Compiler:: =================================================
  IfStr('%$(!"Compile-UseSelectedTeXEngine");',!'1',!'=',>
    !'BtnGetMenuItem("TeX Compile",-1);',!'JMP(!"LaTeX_File");');
  // Engines with uncommon preambles:
  IfIStr("%-1",!"TeX",!"=",!"LetReg(8,!'\bye');JMP(!'Preamble_OK');");
  IfIStr("%-1",!"AMSTeX",!"=",!"LetReg(8,!'\bye');JMP(!'Preamble_OK');");
  IfIStr("%-1",!"PDFTeX",!"=",!"LetReg(8,!'\bye');JMP(!'Preamble_OK');");
  IfIStr("%-1",!"XeTeX",!"=",!"LetReg(8,!'\bye');JMP(!'Preamble_OK');");
  IfIStr("%-1",!"LuaTeX",!"=",!"LetReg(8,!'\bye');JMP(!'Preamble_OK');");
  IfIStr("%-1",!"ConTeXt",!"=",!"Call(!'ConTeXt_File');JMP(!'Preamble_OK');");
  JMP(!"LaTeX_File");

:ConTeXt_File:: =====================================================
  LetReg(8,!"\stoptext");
  FindInString("%!9",!"<\\starttext",1,1,11);
  IfOK(!"Return;");                  // Main File already contains \starttext
  GetPreamble("\starttext",0);       // Get Preamble in Register 0
  // Default Preamble (if necessary add more packages):
  IfOK(!'Relax;',!|LetReg(0,'%% No preamble');|);
  Translate(2,"%!M","%!0",0);        // Translate Output?
  WrL("%!0");                        // Write String
  WrL("\starttext");                 // ConTeXt begin...
  WrL;                               // Empty Line (just in case)
Return;

:LaTeX_File:: =======================================================
  LetReg(8,!"\end{document}");
  FindInString("%!9",!"<\\begin\{document\}",1,1,11);
  IfOK(!"JMP(!'Preamble_OK');");     // Main File already contains \begin{document}
  GetPreamble("\begin{document}",0); // Get Preamble in Register 0
  // Default Preamble (if necessary add more packages):
  IfOK(!'Relax;',>
    !|LetReg(0,>
       '\documentclass{article}%\'+>
       '\usepackage{amsmath}%\'+>
       '%% End of default preamble');>
     |);
  Translate(2,"%!M","%!0",0);        // Translate Output?
  WrL("%!0");                        // Write String
  WrL("\begin{document}");           // LaTeX begin...
  WrL;                               // Empty Line (just in case)
:Preamble_OK:: ======================================================
  WrL("%!9");                        // Write String
  WrL;                               // Empty Line (just in case)
  WrL("%!8");                        // Document end...
  CloseOutput;                       // Close temporary file

  SetMainFile("%!7\_temp%!6"); // Reset the Main File
  LetStr(0,''); // No SRC Specials for Compiled Selected
  UpdateStatus;

  // Debugging: see the _temp file:
  //  Open('%F');
  // Prompt('Main File Set to: "%F"');
  //  Exit;

  ListFolderFiles(5,'%P','',0,1);
  LstEnum('%!5','%\');
  LstGetCount(5);
  Repeat(%!5,>
    !`LstGetItem(2,%!c-1);>
      GetFileName('%!2',3);>
      GetFileType('%!2',4);>
      FindInString('%!4','<\.tex~{?}',-1,-1,1);>
      IfOK(!|Relax;|,>
           !|IfStr('%!3',!'_temp',!'=',!'DeleteFile("%P\%!2");');|);>
      ProcessMessages;>
     `);
  LstRelease;
  ListFolderFiles(5,'%O','',0,1);
  LstEnum('%!5','%\');
  LstGetCount(5);
  Repeat(%!5,>
    !`LstGetItem(2,%!c-1);>
      GetFileName('%!2',3);>
      GetFileType('%!2',4);>
      FindInString('%!4','<\.tex~{?}',-1,-1,1);>
      IfOK(!|Relax;|,>
           !|IfStr('%!3',!'_temp',!'=',!'DeleteFile("%O\%!2");');|);>
      ProcessMessages;>
     `);
  LstRelease;

  // different output folder?
  IfStr('%O','%P','=',!|JMP(!'Compile');|);
  SetMainFile("%O\_temp%T");          // Reset the Main File
  Exe('%b\Exec\PDF\PDFCloseDoc.edt'); // Close the _temp.pdf File
  SetMainFile("%!7\_temp%!6");        // Reset the Main File

:Compile:: ==========================================================
  // Run the compiler
  Exe('%b\Exec\TeX\Compile.edt');

:PDF:: ==============================================================

  IfFileExists("%P\_temp.pdf",!"Relax;",!|JMP(!'PS');|);
  IfFileExists("%P\_temp.dvi",!"DeleteFile('%P\_temp.dvi')");
  IfFileExists("%P\_temp.ps",!"DeleteFile('%P\_temp.ps')");
  // move pdf to a different output folder?
  IfStr('%O','%P','=',!|JMP(!'PDF_Preview');|);
  LetReg(0,'%P');
  CopyFile("%!0\_temp%T","%O\_temp%T",1,1);
  SetMainFile("%O\_temp%T");   // Reset the Main File
  DeleteFile("%!0\_temp%T");
  CopyFile("%!0\_temp.pdf","%P\_temp.pdf",1,1);
  DeleteFile("%!0\_temp.pdf");
:PDF_Preview:: ======================================================
  // Only if it exists!
  IfFileExists("%P\%N.pdf",!"Relax;",!"JMP(!'PS');");
  Exe('%b\Exec\PDF\PDF Preview.edt');
  JMP(!'Cleanup');

:PS:: ===============================================================

  IfFileExists("%P\_temp.ps",!"Relax;",!|JMP(!'DVI');|);
  IfFileExists("%P\_temp.dvi",!"DeleteFile('%P\_temp.dvi')");
  // move ps to a different output folder?
  IfStr('%O','%P','=',!|JMP(!'PS_Preview');|);
  LetReg(0,'%P');
  CopyFile("%!0\_temp%T","%O\_temp%T",1,1);
  SetMainFile("%O\_temp%T");   // Reset the Main File
  DeleteFile("%!0\_temp%T");
  CopyFile("%!0\_temp.ps","%P\_temp.ps",1,1);
  DeleteFile("%!0\_temp.ps");
:PS_Preview:: =======================================================
  // Only if it exists!
  IfFileExists("%P\%N.ps",!"Relax;",!"JMP(!'DVI');");
  Exe('%b\Exec\TeX\GSView.edt');
  JMP(!'Cleanup');

:DVI:: ==============================================================

  // DVI should not be moved (it may contain graphics or ps specials)
  // Only if it exists!
  IfFileExists("%P\%N.dvi",!"Relax;",!"JMP(!'Cleanup');");
  Exe('%b\Exec\TeX\DVI Preview.edt');
  JMP(!'Cleanup');

:Cleanup:: ==========================================================

  // Delete the working output files...
  IfFileExists("%b\_Err.log",!"DeleteFile('%b\_Err.log')");
  IfFileExists("%b\_Out.log",!"DeleteFile('%b\_Out.log')");
  IfFileExists("%F",!"DeleteFile('%F')");
  ListFolderFiles(5,'%P','',0,1);
  LstEnum('%!5','%\');
  LstGetCount(5);
  Repeat(%!5,>
    !`LstGetItem(2,%!c-1);>
      GetFileName('%!2',3);>
      GetFileType('%!2',4);>
      FindInString('%!4','<\.{pdf|ps|dvi}~{?}',-1,-1,1);>
      IfOK(!|Relax;|,>
           !|IfStr('%!3',!'_temp',!'=',!'DeleteFile("%P\%!2");');|);>
      ProcessMessages;>
     `);
  LstRelease;
  ListFolderFiles(5,'%O','',0,1);
  LstEnum('%!5','%\');
  LstGetCount(5);
  Repeat(%!5,>
    !`LstGetItem(2,%!c-1);>
      GetFileName('%!2',3);>
      GetFileType('%!2',4);>
      FindInString('%!4','<\.{pdf|ps|dvi}~{?}',-1,-1,1);>
      IfOK(!|Relax;|,>
           !|IfStr('%!3',!'_temp',!'=',!'DeleteFile("%O\%!2");');|);>
      ProcessMessages;>
     `);
  LstRelease;

  SetMainFile("%$(|Main_File|);");   // Reset the Main File
  LetStr(0,"%$(|old_src|);");
  Exe("%b\Exec\%$(|Exec-Dir|);\ExeMode.edt");
  FocusConsole(-1);

  SetExitHandler;

  PopTagsandRegisters;
  StopWorking;
  UpdateStatus;

End;
