% \iffalse meta-comment
%
% Copyright (C) 2009 by Martin Scharrer <martin@scharrer-online.de>
% -----------------------------------------------------------------
%
% This work 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 2008/05/04 or later.
%
% This work has the LPPL maintenance status `maintained'.
%
% The Current Maintainer of this work is Martin Scharrer.
%
% This work consists of the files gincltex.dtx, gincltex.ins
% and the derived file gincltex.sty.
%
% $Id: skeleton.dtx 1057 2009-05-04 11:11:37Z martin $
% \fi
%
% \iffalse
\RequirePackage{svn-prov}
%<package>\ProvidesPackage{gincltex}
%<*driver>
\ProvidesFile{gincltex.dtx}
%</driver>
  [2011/01/23 v0.1 Include external LaTeX files like graphics]
%<*driver>
\documentclass{ltxdoc}
\usepackage{gincltex}
\usepackage{hyperref}

\EnableCrossrefs
%\CodelineIndex
\RecordChanges
%\OnlyDescription
\begin{document}
  \DocInput{\jobname.dtx}
  \PrintChanges
  %\newpage\PrintIndex
\end{document}
%</driver>
% \fi
%
% \CheckSum{232}
%
% \CharacterTable
%  {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%   Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%   Digits        \0\1\2\3\4\5\6\7\8\9
%   Exclamation   \!     Double quote  \"     Hash (number) \#
%   Dollar        \$     Percent       \%     Ampersand     \&
%   Acute accent  \'     Left paren    \(     Right paren   \)
%   Asterisk      \*     Plus          \+     Comma         \,
%   Minus         \-     Point         \.     Solidus       \/
%   Colon         \:     Semicolon     \;     Less than     \<
%   Equals        \=     Greater than  \>     Question mark \?
%   Commercial at \@     Left bracket  \[     Backslash     \\
%   Right bracket \]     Circumflex    \^     Underscore    \_
%   Grave accent  \`     Left brace    \{     Vertical bar  \|
%   Right brace   \}     Tilde         \~}
%
%
% \changes{v0.1}{2011/01/23}{First released version}
%
% \GetFileInfo{\jobname.dtx}
%
% \DoNotIndex{\newcommand,\newenvironment,\def,\edef,\xdef,\let}
%
% \ifpdf
% \hypersetup{%
%   pdfauthor   = {Martin Scharrer <martin@scharrer-online.de>},
%   pdftitle    = {The gincltex package},
%   pdfsubject  = {Documentation of LaTeX package gincltex},
%   pdfkeywords = {gincltex, include, graphic, source code, LaTeX, TeX}
% }%
% \fi
% \clearpage
% \null
% \vspace*{-2em}
% \begin{center}
%   {\LARGE\sffamily The \emph{gincltex} Package\\[\medskipamount]}
%   {\large\sffamily Part of the \emph{standalone} bundle\\[\medskipamount]}
%   {\large Martin Scharrer \\[\medskipamount]\normalsize
%   \url{martin@scharrer-online.de}\\[.8ex]
%   \url{http://www.ctan.org/pkg/standalone/}\\[\bigskipamount]}
%   {\large Version \fileversion\ -- \filedate}\\
% \end{center}
% \vspace{1.2em}%
%
% \section{Introduction}
% This small package builds on the standard \LaTeX{} packages |graphic| and |graphicx|
% and its extended form |graphicx| and allows external \LaTeX{} source files
% to be included like image files:
% \begin{quote}
%   |\includegraphics[<options>]{somefile.tex}|
% \end{quote}
%
% Usually such \LaTeX{} files hold a picture environment like
% |picture|, |pspicture|, |pgfpicture| or |tikzpicture|, which may take advantage
% from the |standalone| class.
%
% All options of |\includegraphics| described in the manual of |graphic|/|graphicx| (the |grfguide|)
% should be supported. Therefore it is possible to resize, rotate and clip the content
% of the \LaTeX{} source file in the same way as for images.
%
% \section{Usage}
% After loading the package the |.tex| extension is supported by |\includegraphics|
% and the macro can be used in its normal form for \LaTeX{} files.
% The content of the file is typeset first inside an |\hbox| (the primitive version of |\mbox|)
% and then modified according to the given macro options.
%
% \subsection{Draft support}
% The package supports the |draft| option of |graphics| which only displays an empty box
% with the file name for all included graphics.
% In this mode the source file should not be processed to reduce compile time.
% However the size of the resulting box from the source file must be know in order
% to reserve the required space. Therefore the \emph{bounding box} information is
% cached for future runs with active |draft| option. The location where the information
% is cached can be controlled with the |bb| option.
%
% \subsection{Package options}
% The place where the bounding box information is cached can be adjusted with the 
% |bb| option. By default |bb=aux| is active which stores the bounding box information
% in the |.aux| file. With |bb=file| this information is written in EPS format into
% |.tex.bb| files, e.g. for each source file |name.tex| a file |name.tex.bb| is created.
%
%
% \StopEventually{}
% \iffalse
%<*package>
% \fi
% \section{Implementation}
% \subsection{Package Option}
%    \begin{macrocode}
\newif\if@gincltex@bbfile
\DeclareOption{bb=file}{\@gincltex@bbfiletrue}
\DeclareOption{bb=aux}{\@gincltex@bbfilefalse}
\ProcessOptions*\relax
%    \end{macrocode}
%
% \subsection{Requirements}
% The |graphics| or |graphicx| package is required but not loaded to allow
% the user to decide which one should be used
%    \begin{macrocode}
\RequirePackage{pgf}
%    \end{macrocode}

% \subsection{Graphics Rule Macros}
% The following macro implement a \emph{graphics rule} for \LaTeX{} source code files.
%
% \begin{macro}{\Gin@rule@.tex}
% This macro declares the graphics rule to the |graphics|/|x| package.
% It is equivalent to |\DeclareGraphicsRule{.tex}{tex}{.tex}{}|, which is not
% used here to not rely on the graphics packages at load time.
%    \begin{macrocode}
\@namedef{Gin@rule@.tex}#1{{tex}{.tex}{#1}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\gincltex@box}
% A savebox required to transfer material from the `read' macro to the `include' macro.
% Note that |\@tempboxa| is not used here because it might be used otherwise between the
% two macros.
%    \begin{macrocode}
\newsavebox\gincltex@box
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\gincltex@input}
% Macro to input the \LaTeX{} source file.
% Because |\includegraphics| can be used inside this file certain internal |graphics| macros
% must be reset to there default value.
%    \begin{macrocode}
\def\gincltex@input#1{%
    {\let\Gin@ext\relax\input{#1}}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\Ginclude@tex}
% This driver macro is called from the standard |\includegraphics| macro to include the \LaTeX{} source file.
% Some |\includegraphics| options like |angle| are handled by wrapping this macro in the appropriate
% |graphics| macro like |\rotatebox|, but others must be handled here.
%    \begin{macrocode}
\def\Ginclude@tex#1{%
    \begingroup
%    \end{macrocode}
% The content of the source file might have been already saved into the |\gincltex@box| by the |\Gread@tex| macro.
% If not it is saved here.
%    \begin{macrocode}
    \ifvoid\gincltex@box
        \sbox\gincltex@box{{\gincltex@input{#1}}}%
    \fi
%    \end{macrocode}
% The bounding box points (lower left, upper right) are calculated. It is assumed that the `graphic' baseline starts at the
% lower left point, so |llx=0|. The depth should be |0| as well but to be on the save side it is calculated here.
% The upper right point is given by the box width and height.
%    \begin{macrocode}
    \def\Gin@llx{0}%
    \Gin@defaultbp\Gin@lly{-\dp\gincltex@box}%
    \Gin@defaultbp\Gin@urx{\wd\gincltex@box}%
    \Gin@defaultbp\Gin@ury{\ht\gincltex@box}%
%    \end{macrocode}
% The |height|, |totalheight| and |width| options are already processed and the final requested height and width
% to which the `graphic' should be scaled to are provided. The internal form of the |\resizebox| macro is used for
% this.
%    \begin{macrocode}
    \Gscale@@box\totalheight{\Gin@req@width}{\Gin@req@height}{%
%    \end{macrocode}
% The trimming and clipping operations (|trim|, |viewport| and |clip| options) are handled using a |pgfpicture| from
% the |pgf| package, because it supports both DVI and PDF output.
%    \begin{macrocode}
    \begin{pgfpicture}%
        \pgfkeys{/pgf/.cd,inner sep=0pt,outer sep=0pt}%
        \pgfpathmoveto{\pgfqpoint{\Gin@llx bp}{\Gin@lly bp}}%
        \pgfpathlineto{\pgfqpoint{\Gin@urx bp}{\Gin@lly bp}}%
        \pgfpathlineto{\pgfqpoint{\Gin@urx bp}{\Gin@ury bp}}%
        \pgfpathlineto{\pgfqpoint{\Gin@llx bp}{\Gin@ury bp}}%
        \pgfpathclose
        \expandafter\pgfusepath\ifGin@clip{clip}\else{use as bounding box}\fi
        \pgfnode{rectangle}{base west}{\usebox\gincltex@box}{}{}%
    \end{pgfpicture}%
%    \end{macrocode}
%    \begin{macrocode}
    }%
    \endgroup
}
%    \end{macrocode}
% \end{macro}
%
% The |\Gread@tex| macro is defined in two different ways depending how the bounding box information is preserved.
% This information is required to support the |draft| option of the |graphics| package.
%    \begin{macrocode}
\if@gincltex@bbfile
%    \end{macrocode}
% Use a |.tex.bb| file to store the bounding box information. The standardised EPS format is used here, so that the
% |\Gread@eps| macro can be used.
%
% An output register is required to write the |.tex.bb| files. Advanced users are allowed to predefine it manually
% in order to save a write register. Note that the writing is done inside the |.aux| file, therefore the |\@mainaux|
% handle could be used here, because it is closed while reading the |.aux| file.
%    \begin{macrocode}
\@ifundefined{gincltex@bbout}{\newwrite\gincltex@bbout}{}
%    \end{macrocode}
%
% \begin{macro}{\Gread@tex}
%    \begin{macrocode}
\def\Gread@tex#1{%
  \IfFileExists{#1.bb}%
    {\edef\Gread@BBox{\@percentchar\@percentchar HiResBoundingBox}\Gread@eps{#1.bb}}%
    {%
      \sbox\gincltex@box{{\gincltex@input{#1}}}%
      \def\Gin@llx{0}%
      \Gin@defaultbp\Gin@lly{-\dp\gincltex@box}%
      \Gin@defaultbp\Gin@urx{\wd\gincltex@box}%
      \Gin@defaultbp\Gin@ury{\ht\gincltex@box}%
      \expandafter\xdef\csname gincltex@bb@#1\endcsname{{\Gin@llx}{\Gin@lly}{\Gin@urx}{\Gin@ury}}%
      \if@filesw
        \immediate\write\@auxout{\string\gincltex@bb{#1}\csname gincltex@bb@#1\endcsname}%
      \fi
    }%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\gincltex@bb}
% Write the bounding box information to the |.tex.bb| file. The hi-resolution version is used to be more accurate.
% The code to write the normal version is disabled for now because it is unneeded and requires some non-trivial |pgfmath| calls.
%
% Because this macro is executed inside the |.aux| file, which is read before the begin AND at the end of the document, the macro
% is defined as a no-op first two avoid unnecessary double execution.
%    \begin{macrocode}
\def\gincltex@bb#1#2#3#4#5{}
\AtBeginDocument{\let\gincltex@bb\gincltex@@bb}
\def\gincltex@@bb#1#2#3#4#5{%
    \begingroup
    \immediate\openout\gincltex@bbout=#1.bb\relax
    %\pgfmathtruncatemacro\llx{ceil(#2)}%
    %\pgfmathtruncatemacro\lly{ceil(#3)}%
    %\pgfmathtruncatemacro\urx{ceil(#4)}%
    %\pgfmathtruncatemacro\ury{ceil(#5)}%
    %\immediate\write\gincltex@bbout{\@percentchar\@percentchar BoundingBox: \llx\space\lly\space\urx\space\ury}%
    \immediate\write\gincltex@bbout{\@percentchar\@percentchar HiResBoundingBox: #2 #3 #4 #5}%
    \immediate\closeout\gincltex@bbout
    \endgroup
}
%    \end{macrocode}
% \end{macro}
%
% Storing the bounding box information in the |.aux| file.
%    \begin{macrocode}
\else
%    \end{macrocode}
%
% \begin{macro}{\Gread@tex@setbb}
% Auxiliary  macro to set the bounding box macros.
%    \begin{macrocode}
\def\Gread@tex@setbb#1#2#3#4{%
    \def\Gin@llx{#1}%
    \def\Gin@lly{#2}%
    \def\Gin@urx{#3}%
    \def\Gin@ury{#4}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\Gread@tex}
% Read the bounding box information. The only way to do this is to actually typeset the source file into a box.
% The box is then reused in the |\Ginclude@tex| macro, so there is no overhead.
% The bounding box information is written into the |.aux| file to avoid processing the source file in |draft| mode.
% However if the corresponding macro is not define yet (e.g.\ |draft| run without |.aux| file) the file must be
% read anyway.
%    \begin{macrocode}
\def\Gread@tex#1{%
    \ifcase0\ifGin@draft\@ifundefined{gincltex@bb@#1}{0}{1}\fi\relax
        \sbox\gincltex@box{{\gincltex@input{#1}}}%
        \def\Gin@llx{0}%
        \Gin@defaultbp\Gin@lly{-\dp\gincltex@box}%
        \Gin@defaultbp\Gin@urx{\wd\gincltex@box}%
        \Gin@defaultbp\Gin@ury{\ht\gincltex@box}%
        \expandafter\xdef\csname gincltex@bb@#1\endcsname{{\Gin@llx}{\Gin@lly}{\Gin@urx}{\Gin@ury}}%
    \else
        \expandafter\expandafter\expandafter\Gread@tex@setbb\csname gincltex@bb@#1\endcsname
        \setbox\gincltex@box=\box\voidb@x
    \fi
    \if@filesw
        \immediate\write\@auxout{\string\gincltex@bb{#1}\csname gincltex@bb@#1\endcsname}%
    \fi
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\gincltex@bb}
% Simply define the corresponding bounding box macro.
%    \begin{macrocode}
\def\gincltex@bb#1#2#3#4#5{%
    \global\@namedef{gincltex@bb@#1}{{#2}{#3}{#4}{#5}}%
}
%    \end{macrocode}
% \end{macro}
%
%    \begin{macrocode}
\fi
\endinput
%    \end{macrocode}
%
% \Finale
%</package>

