%% This is file `dtk-extern.sty',
%%
%% LaTeX package for ``Die TeXnische Komoedie''.
%%
%% Copyright (C) 2016-19
%% Rolf Niepraschk, Herbert Voss
%%
%% It may be distributed and/or modified under the
%% conditions of the LaTeX Project Public License, either version 1.3c
%% of this license or (at your option) any later version.
%% The latest version of this license is in
%%    http://www.latex-project.org/lppl.txt
%% and version 1.3c or later is part of all distributions of LaTeX
%% version 2005/12/01 or later.

\ProvidesFile{dtk-extern}%
  [2019/08/09 v0.13: dtk package for running external documents (HV)]

\RequirePackage{shellesc,filecontents,xkeyval,graphicx,marginnote,fancyvrb}

\newcounter{dtk@extern@runs}
\newlength\dtk@extern@mpwidth \setlength\dtk@extern@mpwidth{\z@}

\define@key{dtk}{compiler}[pdflatex]{\def\dtk@extern@compiler{#1}}
\define@key{dtk}{runsequence}[]{\def\dtk@extern@runsequence{#1}}
\define@key{dtk}{runs}[1]{\setcounter{dtk@extern@runs}{#1}}
\define@key{dtk}{grfOptions}[]{\def\dtk@extern@grfOptions{#1}}
\define@key{dtk}{lstOptions}[]{\def\dtk@extern@lstOptions{#1}}
\define@key{dtk}{docType}[latex]{\def\dtk@extern@docType{#1}}
\define@key{dtk}{caption}[]{\def\dtk@extern@caption{#1}}
\define@key{dtk}{label}[]{\def\dtk@extern@label{#1}}
\define@key{dtk}{pages}[1]{\def\dtk@extern@pages{#1}}
\define@key{dtk}{mpwidth}[0pt]{\setlength\dtk@extern@mpwidth{#1}}
\define@boolkey{dtk}[dtk@extern@]{usefancyvrb}[true]{}
\define@boolkey{dtk}[dtk@extern@]{showFilename}[true]{}
\define@boolkey{dtk}[dtk@extern@]{code}[true]{}
\define@boolkey{dtk}[dtk@extern@]{force}[true]{}
\define@boolkey{dtk}[dtk@extern@]{crop}[true]{}
\define@boolkey{dtk}[dtk@extern@]{biber}[true]{}
\define@boolkey{dtk}[dtk@extern@]{xindex}[true]{}
\define@key{dtk}{xindexOptions}[]{\def\dtk@extern@xindexOptions{#1}}
\define@boolkey{dtk}[dtk@extern@]{includegraphic}[true]{}
\define@boolkey{dtk}[dtk@extern@]{inline}[true]{}
\define@boolkey{dtk}[dtk@extern@]{frame}[true]{}
\define@boolkey{dtk}[dtk@extern@]{float}[true]{}
\define@boolkey{dtk}[dtk@extern@]{cleanup}[true]{}
\define@boolkey{dtk}[dtk@extern@]{copyToExampleDir}[true]{}
\define@key{dtk}{align}[\centering]{\def\dtk@extern@align{#1}}
\define@key{dtk}{ExamplesDir}[Examples]{\def\dtk@extern@ExamplesDir{#1}}

\def\ResetKeys{%
 \setkeys{dtk}{
  showFilename=false,%  Dateinamen im Rand angeben
  code=false,%          show Code
  crop=false,%		erzeugte PDF "croppen"
  compiler=pdflatex,%	zu verwendener Compiler
  grfOptions={},%	Optionen der einzubindenden Grafik
  lstOptions={},%	Optionen für das Listing
  includegraphic=true,% Grafik einbinden oder User überlassen
  inline=false,%        Grafik nicht in derselben Zeile
  runs=1,%		Anzahl Compiler-Durchläufe
  runsequence={},%	Im Moment nicht aktiv
  biber=false,%		Biber laufen lassen?
  xindex=false,%	xindex laufen lassen?
  xindexOptions={},%     options for xindex
  force=false,%		Compiler, auch wenn PDF existiert?
  frame=false,%		keinen Rahmen um Abbildung
  float=false,%		nicht als Gleitumgebung
  caption=,%	        keine Caption
  label=,%		kein Label
  pages=1,%		welche Seiten auszugeben sind
  docType=latex,%	LaTeX example Code
  cleanup=false,%	Hilfsdateien nicht löschen
  copyToExampleDir,%    Kopie nach ExamplesDir
  ExamplesDir=Examples,% Unterverzeichnis für Beispiele
  align=\centering,%    Ausgabe zentrieren
  mpwidth=0pt,%         no minipage
  usefancyvrb=false,%   use VerbatimInput instead of listings
  }
}
\ResetKeys

{\catcode`\%=12 
 \gdef\perCent{%}
 \gdef\DoubleperCent{%%}
}

\newcounter{dtk@example@counter}

\newcommand\extern@ExampleType[5]{%
   \ifdtk@extern@usefancyvrb
     \@namedef{#1@initText}{\gdef\FancyVerbStartString{#2}\gdef\FancyVerbStopString{#3}}% text
     \@namedef{#1@initPreamble}{\gdef\FancyVerbStartString{#4}\gdef\FancyVerbStopString{#5}}% code
   \else
     \@namedef{#1@initText}{linerange=#2-#3,includerangemarker=false}% text
     \@namedef{#1@initPreamble}{linerange=#4-#5,includerangemarker=false}% code
   \fi
}

\extern@ExampleType{latex}%               #1
  {\string\begin\string{document\string}}%       #2
  {\string\end\string{document\string}}%         #3
  {\perCent StartVisiblePreamble}% #4
  {\perCent StopVisiblePreamble}%  #5

\extern@ExampleType{context}
  {\string\starttext}
  {\string\stoptext}
  {\perCent StartVisiblePreamble}
  {\perCent StopVisiblePreamble}

%%
%% [#1]: Optionen  #2: Dateiname
%%
\newenvironment{ErstelleGrafik}[2][]{%
   \xdef\dtkExternDateiname{#2-\arabic{dtk@example@counter}}%
   \typeout{Externer Dateiname: \dtkExternDateiname}%
   \global\setkeys{dtk}{#1}%                   \begin
   \expandafter\IfFileExists\expandafter{\dtkExternDateiname.pdf}{}{\setkeys{dtk}{force}}%
   \begingroup
   \@nameuse{filecontents*}{\dtkExternDateiname.tex}
  }
  {\@nameuse{endfilecontents*}%         \end
   \ifdtk@extern@copyToExampleDir
     \ShellEscape{cp\space\dtkExternDateiname.tex \dtk@extern@ExamplesDir/}%
   \fi
   \global\stepcounter{dtk@example@counter}%
   \endgroup
   \ifdtk@extern@force
     \loop\ifnum\thedtk@extern@runs>0
       \typeout{Run: \thedtk@extern@runs\space \dtk@extern@compiler\space\dtkExternDateiname}%
       \ShellEscape{\dtk@extern@compiler\space\dtkExternDateiname}%
       \addtocounter{dtk@extern@runs}{-1}%
     \repeat
   \fi
   \ifdtk@extern@code
      \ifdim\dtk@extern@mpwidth>\z@ \minipage[t]{\dtk@extern@mpwidth}\vspace{0pt}\fi
        \expandafter\edef\expandafter\dtk@lst@options@preamble\expandafter{%
          \@nameuse{\dtk@extern@docType @initPreamble},
          \dtk@extern@lstOptions,
          backgroundcolor=\noexpand\color{black!12}}%
          \ifdtk@extern@usefancyvrb
            \expandafter\VerbatimInput\expandafter[\dtk@lst@options@preamble]{\dtkExternDateiname}%
          \else
           \expandafter\lstinputlisting\expandafter[\dtk@lst@options@preamble]{\dtkExternDateiname}%
          \fi
        \ifdtk@extern@showFilename
          \marginnote{\rotatebox{90}{\dtkExternDateiname}}%[-15mm]%
        \fi
%     
      \expandafter\edef\expandafter\dtk@lst@options@text\expandafter{%
        \@nameuse{\dtk@extern@docType @initText},
        \dtk@extern@lstOptions,
        backgroundcolor=\noexpand\color{black!8}}%
%      \typeout{\dtk@lst@options@text}
       \ifdtk@extern@usefancyvrb
         \expandafter\VerbatimInput\expandafter[\dtk@lst@options@text]{\dtkExternDateiname}%
       \else
         \expandafter\lstinputlisting\expandafter[\dtk@lst@options@text]{\dtkExternDateiname}%
       \fi
     \ifdim\dtk@extern@mpwidth > \z@\relax \endminipage\fi
   \fi
   \expandafter\IfFileExists\expandafter{\dtkExternDateiname.pdf}%
     {\ifdtk@extern@force
        \ifdtk@extern@biber
          \ShellEscape{biber  \dtkExternDateiname}%  NAch biber nochmal latex
          \ShellEscape{\dtk@extern@compiler\space\dtkExternDateiname}%
        \fi
        \ifdtk@extern@xindex 
          \ShellEscape{xindex \dtk@extern@xindexOptions\space \dtkExternDateiname.idx}%  NAch xindex nochmal latex
          \ShellEscape{\dtk@extern@compiler\space\dtkExternDateiname}%
        \fi
        \ifdtk@extern@crop
          \ShellEscape{pdfcrop \dtkExternDateiname}%
          \ShellEscape{mv \dtkExternDateiname-crop.pdf \dtkExternDateiname.pdf}%
        \fi
      \fi
     }{}
   \ifdtk@extern@code\else
      \ifdtk@extern@showFilename
        \marginnote{\rotatebox{90}{\dtkExternDateiname}}%
      \fi
   \fi
%
   \ifdtk@extern@includegraphic
     \ifdtk@extern@float
       \begin{figure}[!htb]
     \else
       \ifdim\dtk@extern@mpwidth>\z@ 
         \hfill\minipage[t]{\dimexpr\linewidth-\dtk@extern@mpwidth-1em\relax}\vspace{0pt}
       \else
         \ifdtk@extern@inline\else\par\fi\begingroup
       \fi
     \fi
     \dtk@extern@align
     \ifdtk@extern@frame
       \expandafter\@for\expandafter\next\expandafter:\expandafter=\dtk@extern@pages\do{%
          \fbox{\expandafter\includegraphics\expandafter[\dtk@extern@grfOptions,page=\next]{\dtkExternDateiname}}%
              \hspace{5pt}}\hspace*{-5pt}
%   \fbox{\expandafter\includegraphics\expandafter[\dtk@extern@grfOptions]{\dtkExternDateiname}}%
     \else
       \expandafter\@for\expandafter\next\expandafter:\expandafter=\dtk@extern@pages\do{%
          \expandafter\includegraphics\expandafter[\dtk@extern@grfOptions,page=\next]{\dtkExternDateiname}%
              \hspace{5pt}}\hspace*{-5pt}
%       \expandafter\includegraphics\expandafter[\dtk@extern@grfOptions]{\dtkExternDateiname}%
     \fi
     \ifx\dtk@extern@caption\@empty\else\caption{\dtk@extern@caption}\fi
     \ifx\dtk@extern@label\@empty\else\label{\dtk@extern@label}\fi
     \ifdtk@extern@float
       \end{figure}
     \else
       \ifdim\dtk@extern@mpwidth>\z@ 
         \endminipage
       \else
         \par\endgroup
       \fi
     \fi
   \fi
   \ifdtk@extern@cleanup
      \ShellEscape{rm \dtkExternDateiname.log}%
      \ShellEscape{rm \dtkExternDateiname.aux}%
      \ShellEscape{rm \dtkExternDateiname.toc}%
%      \ShellEscape{rm \dtkExternDateiname.log}%
   \fi
   \global\ResetKeys}
\stepcounter{dtk@example@counter}%
%
\let\externalDocument\ErstelleGrafik
\let\endexternalDocument\endErstelleGrafik
%%
\endinput
