% \iffalse meta-comment
%
% Copyright (C) 2011 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/09/04 v0.3 Include external LaTeX files like graphics]
%<*driver>
\documentclass{ydoc}[2011/03/17]
\usepackage{gincltex}
\EnableCrossrefs
%\CodelineIndex
\RecordChanges
%\OnlyDescription
\begin{document}
  \DocInput{\jobname.dtx}
  \PrintChanges
  %\newpage\PrintIndex
\end{document}
%</driver>
% \fi
%
% \CheckSum{161}
%
% \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}{Packaged code}
% \changes{v0.1}{2011/03/06}{First release}
% \changes{v0.2}{2011/03/18}{Added explicit 'draft' and 'final' options.}
% \changes{v0.3}{2011/09/04}{Clipping and trimming are now done using the \pkg{adjustbox} package.}
%
% \GetFileInfo{\jobname.dtx}
%
% \DoNotIndex{\newcommand,\newenvironment,\def,\edef,\xdef,\let}
%
% \author{Martin Scharrer}
% \email{martin@scharrer-online.de}
% \maketitle
%
% \begin{abstract}
% This small package builds on the standard \LaTeX{} package \pkg{graphicx}
% and allows external \LaTeX{} source files to be included like graphic files, i.e. adds support for the ".tex"
% extension.
% Some of the lower level operations like clipping and trimming are implemented using the \pkg{pgf} package which supports
% both DVI/PS and PDF output.
% This package uses a very similar technique than the author's other package \pkg{adjustbox}, but provides a different
% interface.
% \\[\medskipamount]
% \textbf{Please note} that this package is new and the implementation might change in future revisions.
% This might cause minor rounding differences in the exact size of the resulting \TeX{} box around the included files.
% \end{abstract}
%
% \section{Introduction}
% This small package builds on the standard \LaTeX{} package \pkg{graphicx}
% and allows external \LaTeX{} source files to be included like graphic files:
%
% \begin{macroquote}
%   \includegraphics[<options>]{<\/file>'.tex'}
% \end{macroquote}
%
% \noindent
% A \LaTeX{} file included this way should result in an identical display as a tightly cropped EPS or PDF image
% of the same file (apart smaller rounding differences).
% Usually such files hold a picture environment like
% \env{picture}, \env{pspicture}, \env{pgfpicture} or \env{tikzpicture}, which may take advantage
% from the \cls{standalone} class.
% In fact \pkg{gincltex} is used in newer versions of \pkg{standalone} to seamlessly switch between source and image files.
%
% All options of \Macro\includegraphics described in the manual of \pkg{graphicx} (the \texttt{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.
%
%
% An alternative is the \pkg{adjustbox} package from the same author which allows the same options
% as for \Macro\includegraphics for arbitrary TeX material:
% \begin{macroquote}
%  \adjustbox{<includegraphics options>}{'\input{'<\/file>'}'}
% \end{macroquote}
%
% \section{Usage}
% After loading the package the ".tex" extension is supported by \Macro\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.
% The \pkg{graphicx} package is automatically loaded.
%
% \subsection{Draft support}
% The package supports the \opt{draft} option of \pkg{graphicx} 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 \opt{draft} option. The location where the information
% is cached can be controlled with the \opt{bb} option.
%
% \subsection{Package options}
% The \opt*{draft} and \opt*{final} options are directly passed to the loaded \pkg{graphicx} package.
% Having a different draft setting is not supported and the one used by the \pkg{graphicx} package will always take affect for \pkg{gincltex}.
%
% The place where the bounding box information is cached can be adjusted with the 
% \opt*{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}
% At the moment the key=value format is simply hard coded.
%    \begin{macrocode}
\newif\if@gincltex@bbfile
\DeclareOption{bb=file}{\@gincltex@bbfiletrue}
\DeclareOption{bb=aux}{\@gincltex@bbfilefalse}
\DeclareOption{draft}{\PassOptionsToPackage{draft}{graphicx}}
\DeclareOption{draft=true}{\PassOptionsToPackage{draft}{graphix}}
\DeclareOption{draft=false}{\PassOptionsToPackage{final}{graphicx}}
\DeclareOption{final}{\PassOptionsToPackage{final}{graphicx}}
\DeclareOption{final=true}{\PassOptionsToPackage{final}{graphicx}}
\DeclareOption{final=false}{\PassOptionsToPackage{draft}{graphicx}}
\DeclareOption*{\PassOptionsToPackage\CurrentOption{adjustbox}}
\ProcessOptions*\relax
%    \end{macrocode}
%
% \subsection{Requirements}
% The \pkg{graphicx} package is required.
% The \pkg{pgf} package is required for the graphic manipulations.
%    \begin{macrocode}
\RequirePackage{adjustbox}
%    \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 \pkg{graphicx} package.
%    \begin{macrocode}
\DeclareGraphicsRule{.tex}{tex}{.tex}{}
%    \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@boxfile}
% Macro to box the \LaTeX{} source file.
% Because \Macro\includegraphics can be used inside this file certain internal \pkg{graphicx} macros
% must be reset to there default value.
% The argument is expanded first because it could include |\Gin@ext|.
% The content is stored with zero depth to achieve the same result as with included graphics.
%    \begin{macrocode}
\def\gincltex@boxfile#1{%
    \sbox\gincltex@box{{%
        \hbox{\vbox{%
            \hbox{%
                \edef\@tempa{{#1}}%
                \let\Gin@ext\relax
                \expandafter\input\@tempa
            }%
            \vskip\z@
        }}%
    }}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\Ginclude@tex}
% This driver macro is called from the standard \Macro\includegraphics macro to include the \LaTeX{} source file.
% Some \Macro\includegraphics options like |angle| are handled by wrapping this macro in the appropriate
% \pkg{graphicx} macro like \Macro\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
        \gincltex@boxfile{#1}%
    \fi
%    \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 \Macro\resizebox macro is used for
% this.
%    \begin{macrocode}
    \resizebox*{\Gin@req@width}{\Gin@req@height}{%
        \ifGin@clip\expandafter\clipbox\else\expandafter\clipbox\fi*{{\Gin@llx} {\Gin@lly} {\Gin@urx} {\Gin@ury}}{\usebox\gincltex@box}%
    }%
    \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 \opt{draft} option of the \pkg{graphicx} 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}{\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
    \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 \opt{draft} mode.
% However if the corresponding macro is not define yet (e.g.\ \opt{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
        \gincltex@boxfile{#1}%
        \def\Gin@llx{0}%
        \let\Gin@llx\Gin@lly
        \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
% \iffalse
%</package>
% \fi

