% \iffalse meta-comment
%<=*COPYRIGHT>
%% Copyright (C) 2010-2022 by Martin Scharrer <martin.scharrer@web.de>
%% ---------------------------------------------------------------------------
%% This work may be distributed and/or modified under the
%% conditions of the LaTeX Project Public License, either version 1.3
%% 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.3 or later is part of all distributions of LaTeX
%% version 2005/12/01 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 standalone.dtx and standalone.ins
%% and the derived filebase standalone.sty, standalone.cls and
%% standalone.cfg.
%%
%<=/COPYRIGHT>
% \fi
%
% \iffalse
%<*driver>
\NeedsTeXFormat{LaTeX2e}
\ProvidesFile{standalone.dtx}[%
%<=*DATE>
    2022/10/10
%<=/DATE>
%<=*VERSION>
    v1.3b
%<=/VERSION>
    DTX file of the standalone bundle]
\documentclass[a4paper,11pt]{ydoc}
\usepackage{flafter}
\usepackage{standalone}
%\addtolength{\oddsidemargin}{1cm}
%\addtolength{\textwidth}{-1cm}
\def\subsectionautorefname{section}
\def\subsubsectionautorefname{section}
\EnableCrossrefs
\CodelineIndex
\RecordChanges
\colorlet{keydesc}{opt}
\OnlyDescription
\lstset{numbers=none,columns=fullflexible}
\def\Eurl#1{\edef\temp{{#1}}\expandafter\url\temp}
\IfFileExists{metalogo.sty}{%
\usepackage{metalogo}%
}%
{%
\providecommand{\XeLaTeX}{Xe\TeX}
\providecommand{\XeLaTeX}{Xe\LaTeX}
}
\begin{document}
  \DocInput{\jobname.dtx}
  \PrintChanges
  \newpage\PrintIndex
\end{document}
%</driver>
% \fi
%
% \CheckSum{3934}
%
% \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}{2010/03/21}{First released version}
% \changes{v0.2}{2010/03/22}{Added support for beamer style settings in the config file using \cs{ifstandalonebeamer}. Updated documentation.}
% \changes{v0.3}{2010/03/26}{Added package options to automatically copy sub-preamble code to the main preamble.}
% \changes{v0.3a}{2010/03/27}{Fixed bug related to line endings in \texttt{.sta} file. Listed sub-files now have \texttt{.tex} as default extension.}
% \changes{v0.4}{2011/02/28}{Added option 'border' for easy adjustments of the preview border.}
% \changes{v1.1}{2012/05/05}{Fixed conversion issue with MiKTeX.}
% \changes{v1.1a}{2012/05/20}{Failed conversion now always creates a normal output file. Some requested changes in the
% manual.}
% \changes{v1.1b}{2012/09/15}{Fixed issue with 'subpreambles' for Beamer documents.}
% \changes{v1.2}{2012/12/31}{Fixed build issue with MiKTeX due to incorrect quoting character.}
% \changes{v1.3}{2018/03/24}{Several fixes for new driver and LuaTeX versions. Other minor fixes in bundle and manual.}
% \changes{v1.3a}{2018/03/26}{Improved shellescape code to ensure compatibility with all current LaTeX formats.
% Added loading of LuaTeX compatibility packages.
% Changed filemodedate code to support LuaTeX.
% Fixes for option combination multi,convert.}
% \changes{v1.3b}{2022/10/10}{Fixed incorrect/unwanted messages for conversion feature. Updated project URLs in documentation. Added dependency list file.}
%
% \GetFileInfo{\jobname.dtx}
%
% \DoNotIndex{\newcommand,\newenvironment,\def,\edef,\xdef,\gdef,\DeclareRobustCommand}
% \DoNotIndex{\expandafter,\if,\else,\fi,\ifnum,\ifx,\let,\global,\long}
% \DoNotIndex{\newcounter,\newcount,\message,\meaning,\noexpand,\relax,\value}
% \DoNotIndex{\setcounter,\addtocounter,\advance,\afterassignment,\AtEndOfPackage}
% \DoNotIndex{\ProvidesPackage,\providecommand,\RequirePackage,\empty,\begin,\end}
% \DoNotIndex{\begingroup,\bgroup,\egroup,\endgroup,\csname,\endcsname,\@tempa,\@tempb}
% \DoNotIndex{\ignorespaces,\lccode,\sffamily,\@gobble,\@ifundefined,\@for,\or}
% \DoNotIndex{\@firstoftwo,\@ifnextchar,\@namedef,\@nameuse,\@secondoftwo}
% \DoNotIndex{\@temptokena,\toks@,\BODY,\do,\g@addto@macro,\lowercase,\uppercase,\the}
% \DoNotIndex{\aftergroup,\CurrentOption,\DeclareBoolOption,\DeclareDefaultOption,\DeclareStringOption,\DeclareVoidOption}
% \DoNotIndex{\endinput,\endpreview,\input,\LoadClass,\newif,\PassOptionsToPackage,\preview,\ProcessKeyvalOptions}
% \DoNotIndex{\renewcommand,\renewenvironment,\setbeamertemplate,\SetupKeyvalOptions,\space,\unskip,\usepackage}
% \DoNotIndex{\unexpanded,\write,\next,\jobname,\hbox}
%
% \ifpdf
% \hypersetup{%
%   pdfauthor   = {Martin Scharrer <martin.scharrer@web.de>},
%   pdftitle    = {The standalone class and package},
%   pdfsubject  = {Documentation of LaTeX class and package 'standalone'},
%   pdfkeywords = {standalone, LaTeX, TeX}
% }%
% \fi
% \author{Martin Scharrer}
% \email{martin.scharrer@web.de}
% \repository{https://github.com/MartinScharrer/standalone}
% \maketitle
%
%
% \begin{abstract}
% The \pkg{standalone} bundle allows users to easily place picture environments or other material in own source files
% and compile these on their own or as part of a main document.
% A special \cls{standalone} class is provided for use with such files, which by default crops the resulting output file to the content.
% The \pkg{standalone} package enables the user to simply load the standalone files using \Macro\input\relax inside a main document.
% \end{abstract}
%
% \smallskip
% \begin{multicols}{2}
% \setcounter{tocdepth}{2}
% \tableofcontents
% \end{multicols}
%
% \section{Online Resources and Help}
% This bundle is released on the comprehensive \TeX\ archive network (CTAN) under \url{https://ctan.org/pkg/standalone}.
% Any modern \LaTeX\ distribution should pick it from there automatically, though. CTAN now allows votes and comments on packages and such feedback is very welcome.
%
% The source code of this bundle is hosted on Github under \url{https://github.com/MartinScharrer/standalone}.
% The ticket system there should be used to report bugs or request new features: \url{https://github.com/MartinScharrer/standalone/issues}.
%
% User which need help with should search for an existing solution on the site TeX.Stackexchange.com: \url{https://tex.stackexchange.com/questions/tagged/standalone}
% or post a new question: \url{https://tex.stackexchange.com/questions/ask?tags=standalone}.
% The bundle author is an active user on TeX.SE but other users might help as well.
%
% \section{Installation}
% This bundle is part of the two main \LaTeX\ distributions \emph{TeX Live} and \emph{MikTeX} and can be easily installed
% with their package managers. It is also provided as TDS ZIP file on CTAN which can be used for a manual install.
% Other packages are also required as described in \autoref{sec:dep}.
%
% \subsection{Installation with TeX Live}
% Using a normal TeX Live the bundle is easily installed using the package manager \texttt{tlmgr}.
% The command \texttt{tlmgr install standalone} will install it and \texttt{tlmgr update standalone} can be used to update it.
%
% Because the Ubuntu/Debian version of TeX Live may not include \texttt{tlmgr} a manual install of the package is
% required. The author recommends to manually install the vanilla version of TeX Live instead which will include
% regular package updates.
%
% \subsection{Installation with MikTeX}
% The bundle can be easily installed using the MikTeX package manager as described by
% \url{http://docs.miktex.org/manual/pkgmgt.html}. The MikTeX package name is identical to the normal package name.
%
% \subsection{Manual Installation from CTAN}
% The bundle is also available on the Comprehensive TeX Archive Network (CTAN), both as the DTX/INS files and as TDS
% ZIP file, which can be used for a manual install. A manual install is only required if the used distribution does not
% include the (required version of the) package.
%
%
% \subsubsection{Installation from TDS ZIP file}
% The TDS (\TeX\ Directory Structur) ZIP file includes all package files in the final form and relative location.
% It can be downloaded from CTAN: \url{http://mirrors.ctan.org/install/macros/latex/contrib/standalone.tds.zip} and
% from the Github project site \url{https://github.com/MartinScharrer/standalone/releases/}.
% It needs only to be unzipped in a TEXMF directory. Under Linux/Unix this is usually the user TEXMF directory
% \path{~/texmf}.
% Under Windows it is usually \path{C:\Users\<user name>\texmf} (Windows Vista/7) or \path{C:\Documents and
% Settings\<user name>\texmf} (Windows XP).
% Under Mac OS X it is usually \path{/Users/<user name>/Library/texmf}.
% Alternatively a system local directory can be used which is usually given by the environment variable
% \texttt{TEXMFLOCAL}.
% After the files are copied to this location the file name database of \TeX\ might need to be updated.
% This can be done with TeX Live by running \texttt{texhash <path>} or \texttt{mktexlsr <path>}.
% MikTeX provides a graphical interface to refresh its file name database as described by
% \url{http://docs.miktex.org/manual/configuring.html#fndbupdate}.
%
%
% \subsubsection{Installation from DTX File}
% The package is also provided as DTX (Documented TeX file) which is accompanied by an INS (Install) file
% under \url{http://www.ctan.org/tex-archive/macros/latex/contrib/standalone}.
% To unpack all package files from the DTX file compile the INS file with |tex| once.
% The manual can be compiled from the DTX file with |pdflatex|. This requires the \pkg{ydoc} bundle to be installed.
%
%
% \subsection{Dependencies}\label{sec:dep}
% The \cls{standalone} class and package require the \pkg{xkeyval} package.
% The packages \pkg{ifpdf}, \pkg{ifluatex}, \pkg{ifxetex}, and \pkg{shellesc} are loaded if available, otherwise some fall-back code is used.
% If enabled the class options \opt{varwidth}, \opt{preview} and \opt{beamer} require the package or class of the same name.
%
% The \pkg{standalone} package requires the \pkg{currfile} package (which in turn uses \pkg{filehook}) to track the correct file names of
% sub-files included using |\input|.
% For the compilation support for included standalone files the \pkg{gincltex} and \pkg{filemod} packages are also required.
%
% To compile the documentation of \cls{standalone} the \cls{ydoc} bundle is required.
%
% All of these packages are included in recent versions of the TeXLive or MikTeX distributions and are freely available on \href{http://www.ctan.org/}{CTAN}.
%
% \section{Bug reports, feature requests and other feedback}
% Bug reports, feature requests and other feedback about the \cls{standalone} bundle can be sent to the author
% either by email to \href{mailto:martin.scharrer@web.de?subject=standalone:%20}{martin.scharrer@web.de}
% or using the issue tracker for the bundle under \url{https://github.com/MartinScharrer/standalone/issues}.
% Bug reports should include the used version of \cls{standalone} as well as the used \LaTeX\ format (|pdflatex|, |latex|, |xelatex|, etc.) and distribution including its version.
% Usually a minimal example which recreate the issue is immensely helpful in analysing and solving any bug.
% Please look for existing related issue tickets first and check the FAQ/troubleshooting in \autoref{sec:classfaq} first.
% Issues related to the \opt{preview} class option should be compared with a direct use of the underlying \pkg{preview} package.
%
%
% \clearpage
%
% \section{Introduction}
% Larger \LaTeX{} documents can be split into multiple \TeX\ files which are then included in a main document with \cs{include}
% for e.g.\ chapter files or \cs{input} for e.g.\ \TeX-coded pictures. Keeping pictures in their own sub-files improves readability
% of the main file and simplifies the sharing of them between different documents. However, during the, sometimes lengthly,
% drawing/coding process it has benefits to be able to compile the pictures on their own. The compile process is much quicker and
% the resulting document only holds the picture which avoids constant page turning and zooming.
%
% While it is possible to write a small `main' file for each picture file, this method is a little cumbersome and clutters
% the directories with a lot of extra files. A second method is to place the `main' components, i.e. a preamble, directly into the
% picture files and make the main document ignore this code sections.
%
% The package \cls{standalone} can be used in the main document to skip all extra preambles in included files. The main file must load all packages
% and settings required by the sub-files. Several package options are provided to collect the preambles of the sub-files automatically and execute them from the main file.
%
% A \cls{standalone} class is also provided to minimise the extra preamble code needed in this files.
% It's usage is optional, but simplifies and standardises how picture files are compiled standalone.
% The class uses by default the \opt{crop} option to create an output file which only contains the picture with no extra
% margins, page numbers or anything else.
% A configuration file \file{standalone.cfg} read by the class allows the user to adjust settings and macros easily
% on a per directory base.
%
% \subsection{Quick instructions}
% Load the \cls{standalone} \emph{package} very early in the main document. Also all packages needed by all the sub-files must be loaded by the main document.
% Include your picture or other sub-files using |\input| or a similar macro as normal.
% In the sub-files use the \cls{standalone} \emph{class} with a normal \cs{documentclass} and load all packages needed for the particular
% file. Finally wrap the actual content of the sub-file in a \env{document} environment. Avoid empty lines at the begin or end of the document body.
%
% When the sub-file is compiled on its own the |\documentclass| and \env{document} environment will be active as normal. The main file, however,
% will skip everything from the |\documentclass| till the |\begin{document}|. The (now fake) \env{document} environment is redefined to be a simple
% TeX-group. Any code lines after the |\end{document}| will be ignored. The real \env{document} environment of the main file will be unaffected and will work as normal.
%
% The packages required by each sub-file can be transfered automatically to the main document preamble using the options
% listed in \autoref{sec:pkgoptions}.
%
% \subsection{Version update and backwards compatibility}
% The default behaviour of v1.x of the \cls{standalone} class is slightly different as the one of v0.x, but should result in the same output for the majority of standalone files.
% In previous versions the \opt{preview} option was enabled by default, but since v1.0 the new, similar \opt{crop} option is now used.
% This change should improve several use-cases, like avoiding the creation of a paragraph due to a trailing empty line and issues with TikZ patterns under \XeLaTeX.
% However, paragraph breaks are now ignored by default, which should be no issue at all for picture and similar environments which are the main target of the \cls{standalone} class.
% Additionally, the default border has been changed from the \pkg{preview} default of 0.50001bp to no border (0pt).
% Both of these settings can be changed back to the old default by adding \Macro\standaloneconfig{preview,border=0.50001bp} in the configuration file
% or explicitly stating these options as class options.
%
% One true incompatibility between v0.x and v1.x is the load point of the class configuration file.
% In v0.x the configuration file was loaded after all options where processed in order to have all if-switches their final value.
% In v1.x the configuration file is now loaded directly before the given class options are processed. This allows to easily set default options for all standalone files.
% Code which relies on if-switches (like \Macro{ifstandalone} and \Macro{ifstandalonebeamer}) should be placed inside a \Macro\AtEndOfClass{<code>} macro.
% This change might require an update of personal configuration files.
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsection{Similar packages and classes}
% The following packages, libraries and/or classes target the same or similar applications as the \bundle{standalone} bundle and are mentioned here for easy comparison, so that the user can decide
% which suits them best.
%
% The \pkg{docmute} package is written for the same basic task as the \cls{standalone} package. However, no sub-preamble processing other than the removal is support. It also
% doesn't provide a special class or configuration file.
%
% The \pkg{subfile} package and class are written for the same application to allow subfiles to be compiled standalone. However, the \cls{class} class will import the preamble from a given main file,
% while \pkg{standalone} is designed more for the opposite direction where the preamble of subfiles can be imported to the main document. Therefore a \cls{standalone} file can be more easily included
% into several documents, like a paper (scientific publication), a corresponding presentation and then a thesis, while \cls{subfile} is designed for a one-to-one relationship.
% At the time of the writing \pkg{subfile} is not part of TeXLive due to a missing license statement.
%
% The \lib{external} library of \pkg{tikz} allows to externalize \env{tikzpictures} from an main document. Its build feature is similar to the one provided by \cls{standalone}.
% However, both work form different directions: \cls{standalone} allows to include external \env{tikzpictures} to be included in a main file while ignoring the preamble while
% \lib{external} writes them from the main file to temporary external files. The user must decide which workflow is better suited for him/her.
% Also \cls{standalone} is working independently of \pkg{tikz} and supports other picture environments like \pkg{pstricks} or any other \TeX\ material.
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \clearpage
% \section{Usage of the \cls{standalone} class}
% \subsection{Basic usage}
% Creating a basic standalone is straight-forward: Create a normal \LaTeX\ document which uses the \cls{standalone} as document class.
% The preamble should load all required packages and libraries for the content. The content, usually a single picture environment like \env{tikzpicture},
% is placed in the \env{document} body. Empty lines before and after the picture should be avoided.
% Also the |\begin{document}| and |\end{document}| should each stand on a source line of their own.
%
% \par\noindent
% \begin{minipage}{\textwidth}
% \begin{lstlisting}[language={[latex]tex},gobble=4,frame=lines,caption={Basic use of the \cls{standalone} class.},numbers=none]
%   \documentclass{standalone}
%   \usepackage{somepackage}
%   \begin{document}
%   \begin{somepicture}
%       \somedrawingcommands
%   \end{somepicture}
%   \end{document}
% \end{lstlisting}
% \end{minipage}
%
% Such a file can be compiled as normal. The \cls{standalone} class will crop the resulting output file (PDF or DVI/PS) to the content size plus a certain border.
% Page number and other header or footer material will be suppressed.
%
% For pictures drawn with TikZ a dedicated \opt{tikz} option is provided which loads the \pkg{tikz} package and also configures the \env{tikzpicture} environment to create a single cropped page.
% For PSTricks pictures an corresponding \opt{pstricks} option is provided.
%
% \par\noindent
% \begin{minipage}{\textwidth}
% \begin{lstlisting}[language={[latex]tex},gobble=4,frame=lines,caption={Basic use of the \cls{standalone} class.},numbers=none]
%   \documentclass[tikz]{standalone}
%   %\usetikzlibrary{calc}
%   \begin{document}
%   \begin{tikzpicture}
%     \draw (0,0) rectangle (2,1) node [midway] {Example};
%   \end{tikzpicture}
%   % Further 'tikzpicture' environments are possible which will create further pages.
%   \end{document}
% \end{lstlisting}
% \end{minipage}
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsection{Class options}\label{sec:classoptions}
% The \cls{standalone} class provides the following options to adjust the processing and size of the content.
% These options are removed from the normal list of class options and not passed to any loaded packages or classes like it would usually occur.
% This is also done to avoid option conflicts with identical named options of the underlying class.
%
% All boolean options take either `|true|' or `|false|' as optional values. Otherwise, if the option is used without a value, `|true|' is used.
% If not mentioned otherwise all options set to `|false|' initially.
% Options might switch other options on or off. For example, mutual exclusive options will disable each other. The order of the option is obeyed
% and later options will prevail over earlier ones.
%
% By default the \opt{crop} option with \opt{border}|=0| is enabled. In versions prior to v1.0 the option \opt{preview} was the default. This chance
% was deemed required and should not affect most documents. However, in some cases resetting the \opt{preview} option
% might be required.
%
% Certain class options can also be set inside the preamble or document body using \Macro\standaloneconfig{<options>}.
%
% \DescribeKey{class}'='<class name>
% Specifies the underlying class which is loaded by the \cls{standalone} class.
% By default \cls{article} is used, which should be suitable for standalone pictures.
% In certain cases it may be from benefit to use the same class than in the targeted main document.
% For the \cls{beamer} class the special \opt{beamer} option should be used instead.
%
% \DescribeKey{crop}'=true|false'
% If enabled this option crops the content to its natural size plus a specified border. This is done by saving the content in a box register and resizing
% the page size relative to the box dimensions. This option is enabled by default (since v1.0).
% This option is mutually exclusive with the similar \opt{preview} option and will therefore disable it.
% If both options are used the last one will be enabled and the other will be disabled.
% Also \Key{float}'=false' will be set by \Key{crop}'=true' in order to avoid issues with floating environments.
%
% \DescribeKey{preview}'=true|false'
% If enabled this option loads the \pkg{preview} package with the \opt{tightpage} option
% and wraps the content into a \env{preview} environment. This crops the content to its natural size plus a specified border.
% Issues with the \pkg{preview} options and TikZ shadings under \XeLaTeX have been reported. In this cases the \opt{crop} option should be used instead.
% Note that this option was enabled by default for versions before v1.0, but since then \opt{crop} is enabled by
% default.
%
% This option is mutually exclusive with the similar \opt{crop} option and will therefore disable it.
% If both options are used the last one will be enabled and the other will be disabled.
% Also \Key{float}'=false' will be set by \Key{preview}'=true' in order to avoid issues with floating environments.
%
% \DescribeKey{border}'='<length (all sides)>
% \DescribeKey{border}'='{<length (left/right)>~<length (bottom/top)>}
% \DescribeKey{border}'='{<length (left)>~<length (bottom)>~<length (right)>~<length (top)>}
% This option allows to specify the border used by the \opt{preview} and \opt{crop} options.
% An alternative name of this option is \opt{margin}.
% The border can either be given using a single value for all sides, separately for the horizontal and vertical borders or for all sides separately.
% Multiple values are separated by spaces, which require the whole value to be wrapped in braces.
% By default a border of |0pt| is set.
%
% This option can be changed during the document using \Macro\standaloneconfig and will affect all following pages.
%
% \DescribeKey{multi}'=true|false'
% \DescribeKey{multi}'='{<environment name>, \ldots>}
% By default the \cls{standalone} class assume that the whole content is one block which should be shown on one single page.
% If this option is activated multiple pages are supported. Each page will be cropped to its content plus the selected border (as long either \opt{preview} or \opt{crop} are enabled).
% A set of environments which hold a single page must either be given as option value or declared using \Macro\standaloneenv{<environment name>, \ldots}.
% No typeset material should be used outside such environments.
% Note that this option is enabled automatically by \Macro\standaloneenv if either \opt{crop} or \opt{preview} is enabled.
% However, it needs to be set explicitly as class option if the \opt{ignorerest} option is also set.
% If environment names are provided as option values the option is set to `|true|' and the environments are passed to \Macro\standaloneenv which is executed at the begin of the
% document environment, where all mentioned environments should be already defined.
%
% \DescribeKey{ignorerest}'=true|false'
% This option is only meaningful when both \opt{multi} and \opt{crop} are enabled.
% Then it determines if all material which does not appear inside environments declared with \Macro\standalone should be ignored or not.
% This is done by boxing and discarding all outside material. Any code will be placed inside a group and therefore local settings made between environments
% will not affect later code. Code in the preamble is not affected.
% It is recommended to keep this option disabled and only use it if really required.
% It should be noted that which \opt{preview} such material is always ignored while not affecting local settings.
% Therefore the \opt{ignorrest} option can be seen as a compatibility setting to make \opt{crop} act more like \opt{preview}, if this is required by the user.
%
%
% \DescribeKey{multido}'=true|false'
% Often the \pkg{multido} package with its \Macro\multido macro is used to produce several iterations of a diagram.
% Usually every iteration should be placed on a seperate page. This option simplifies this task be changing
% \Macro\multido to automatically wrap the content (3rd argument) in a \opt{multi} environment.
% This option will only work if the \Macro\multido macro is on the top level and not part of an environment like \env{pspicture}.
%
% The \opt{ignorerest} option is supported by \opt{multido} because special care is taken to not ignore the
% \Macro\multido macros.
%
% The nesting of \Macro\multido macros is supported and only the outer one will produce pages while the inner ones are
% acting normally. The same is true for \Macro\multido inside any \opt{multi} environment.
%
% This option sets the option \opt{multi}|=samultido|, loads the \pkg{multido} package and redefines its internal macro
% \Macro\multido@.  This is done to also support the other macros \Macro\mmultido, \Macro\Multido and \Macro\MMultido.
%
%
% \DescribeKey{varwidth}'=true|false'
% \DescribeKey{varwidth}'='<width>
% A trailing empty line between the content and \Macro\end{document}\relax will normally create a paragraph which is \Macro\linewidth wide.
% This paragraph (or any other one) will enlarge the size of smaller pictures and display itself as a large right border.
% This option uses the \pkg{varwidth} package to wrap the content into a \env{varwidth} environment, which is based on \env{minipage},
% but will always use the natural width of the content if it is smaller than the given maximum width.
% The resulting effect is that the created paragraph will not cause any additional width and that multiple paragraphs can be included as part of the content.
% The used maximal width (which is provided to the underlying \env{minipage} environment) is \Macro\linewidth by default, but can be set
% by provided a width as value to the option. Doing so will also switch the option on.
%
% If the \opt{crop} option is used the content is placed in restricted horizontal mode which ignores paragraph breaks.
% Using the \opt{varwidth} option paragraph breaks are enabled again.
%
% A drawback of this option is that the content will be limited to the given width, i.e.\ wider picture environment will be cropped to the width at the right
% side. In such cases either a larger width should be selected, the option be switch off, any paragraph breaks should be avoided (no trailing empty lines) or one of the
% specific picture options like \opt{tikz} or \opt{pstricks} should be used instead.
%
% This option can be changed during the document using \Macro\standaloneconfig and will affect all content of the following pages.
%
% \DescribeKey{tikz}'=true|false'
% This option declares that the content contains of one or more \env{tikzpicture} environments. This sets |multi=tikzpicture,varwidth=false| and loads the \pkg{tikz} package.
%
% \DescribeKey{pstricks}'=true|false'
% This option declares that the content contains of one or more \env{pspicture} or \env{pspicture*} environments. This sets |multi=pspicture,varwidth=false| and loads the \pkg{pstricks} package.
% Because \env{pspicture*} uses \env{pspicture} internally it is also supported. Other environments which use it as well should also be supported,
% but might also declared explicitly using \Macro\standaloneenv{<environment name>, \ldots}.
%
% \DescribeKey{beamer}'=true|false'
% If set to `|true|' this option enables a special \cls{beamer} mode, where the normal cropping is disabled.
% Instead the content is shown on a blank beamer frame.
%
% \DescribeKey{float}'=true|false'
% If this option is that to `|false|' (which is the default) any floats like \env{figure} and \env{table} environments are turned into non-floating environment.
% This is required for the options \opt{crop} and \opt{preview} to work, so these will set \Key{float}'=false' when set to `|true|' itself.
% In general it is recommended to keep floating environments inside the main document and only place the content of them into standalone files.
% This also makes it simple to include the same content in different floats of different main documents.
%
% If custom floats are defined using a package like \pkg{float} are not supported yet. Dependent on the way they define floats they might still work.
% For these \Key{float}'=true' should be set as class options so that the normal definition of floats is preserved.
% Afterwards \Macro\standaloneconfig{float=false} can be used to disable floats while taking the changed float definition into account.
%
%
% \DescribeKey{convert}'='{<conversion options>}
% \DescribeKey{png}'='{<conversion options>}
% These options allow to enable and configure the conversion feature. See \autoref{sec:convert} for the full description.
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsection{Macros and environments}\label{sec:classmacros}
% The following macros and environments can be used inside the preamble of \cls{standalone} files. Further macros are listed in \autoref{sec:common} which are
% defined by both the class and package and can be used in standalone files but also in the main document.
%
% \DescribeMacro\standaloneconfig{<options>}
% This configuration macro accepts the class options described in \autoref{sec:classoptions}.
% It can be used inside the class configuration file to set default settings used by all standalone files, as mention in \autoref{sec:configfile}.
% These settings are set just before the class options of the standalone file are processed.
%
% Certain class options (e.g.\ \opt{border}, \opt{varwidth}) which do not have a global effect can also be changed using this macro later in the preamble or even inside the document body
% between different content if the \opt{multi} option is enabled.
%
% \DescribeMacro\standaloneenv{<environment>', '<environment>', '\ldots}
% If the \opt{multi} option is in effect this macro should be used to declare all environments which produce content.
% Common examples of such environments are \env{tikzpicture}, \env{pspicture} and other picture environments.
% This macro must only be used inside the preamble.
% Every use of such an environment in the document body will produce a new page.
% An exception are nested appearances of such environments, e.g.\ a \env{tikzpicture} inside a node of another \env{tikzpicture}.
% The environments must be previously defined and must not be redefined afterwards. Multiple appearances of the same environment name
% inside one or multiple \Macro\standalonenv should be avoided.
%
% This macro uses \Macro\PreviewEnvironment internally if the \opt{preview} option is active. Own code is used with the alternative \opt{crop} option.
% If none of these options are enabled this macro will have not effect and will be silently ignored.
%
% \DescribeMacro{\standaloneignore}
% In rare cases some code must be placed before the |\documentclass| of a sub-file (e.g.\ |\PassOptionsToPackage|).
% Because the main document will only skip code between |\documentclass| and |\begin{document}| this code will be executed by it.
% In order to avoid this the macro \cs{standaloneignore} can be used at the very beginning of a sub-file to skip over this code.
% However it must be written as |\csname standaloneignore\endcsname| to avoid a `Undefined control sequence' error when compiled standalone.
% After all the class is not loaded at this point, therefore no \cls{standalone} macros are yet defined.
% The |\csname|\,\ldots|\endcsname| construct will simple make it equal to |\relax| in this case.
%
% Please note that all code before |\documentclass| is not processed by any of the \opt{subpreamble} options but always simply removed.
% This macro was inspired by the similar macro |\docmute| of the |docmute| package.
%
% \DescribeEnv[<sub-file content>]{standalone}
% The \env{standalone} environment is automatically wrapped around the content of standalone files.
% If the \opt{multi} option is enabled it is wrapped around every page, i.e.\ every environment declared with \Macro\standaloneenv.
% The definition of this environment depends on options like \opt{crop} and \opt{preview}.
% It is possible to redefine this environment in the configuration file or the document preamble to adjust the processing of the content, but this is not recommended.
% If done most content related options will stop work and/or cause errors.
%
% The beamer specific macros and environments are described in \autoref{sec:beamer}.
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsection{Support for Beamer Presentations}\label{sec:beamer}
% Presentation can be written in \LaTeX\ using the \cls{beamer} class. Each presentation frame is wrapped in a \env{frame} environment. Overlay effects
% can be added using special macros. This effects result in multiple pages per frame. Pictures with such overlay effects can not be
% compiled standalone using the normal settings. Instead the \cls{standalone} class must load the |beamer| class and wrap the content also in
% a \env{frame} environment while skipping the \env{preview} environment. To activate this settings load the \cls{standalone} class with the |beamer| option.
% Because the \env{frame} environment is quite special (it normally collects all it's content and calls the \cs{frame}) and must also support
% verbatim content it is not easily possible to redefined the |document| environment to include \env{frame}. Also \env{frame} accepts options which |document| doesn't.
% Therefore a second environment called \env{standaloneframe} is used in the beamer picture files. It will be equal to \env{frame} in standalone mode, but
% without effect otherwise.
%
% \DescribeMacro{\ifstandalonebeamer}
% Both the class and the package provide the if-switch \cs{ifstandalonebeamer}, which can be used to only include code if the file is
% compiled standalone with the |beamer| class option set.
% The switch is set to \cs{iftrue} by the class when loaded with the \opt{beamer} option and always to \cs{iffalse} by the package.
% It can be used to place beamer specific options in the configuration files, which should be skipped for non-beamer standalone files.
% If used inside the configuration file this switch must be placed inside \Macro\AtEndOfClass{\ldots}, because the \opt{beamer} option is not yet processed
%
% \begin{DescribeEnv}{standaloneframe}
%   !\begingroup\oargstyle!<< <overlay specification> >>!\endgroup!
%   ['<'<default overlay spec>'>']!\\\hspace*{7em}!
%   [<options>]{<optional frame title>}{<optional frame subtitle>}
%   \relax\MacroArgs<code with beamer overlays>
% \end{DescribeEnv}
% The \env{standaloneframe} environment must be used in sub-file holding beamer overlay code.
% It is only defined when the class is called with the |beamer| option and acts as a replacement
% of the \env{frame} environment of beamer when compiled standalone.
% All optional arguments of \env{frame} are supported but most might not be useful for normal sub-files.
% When compiled as part of a main document it does nothing except of gobbling its arguments.
%
% The listings~\ref{lst:beamer}--\ref{lst:beamerrepl} shows a beamer standalone example and its effective code in standalone and main document mode.
%
% \par\bigskip\noindent
% \begin{minipage}{\textwidth}\noindent
% \begin{lstlisting}[language={[latex]tex},gobble=4,frame=lines,numbers=none,caption={Use of \texttt{standalone} class with \texttt{beamer} option.},label=lst:beamer]
%   % Use of 'standalone' class with a beamer overlay:
%   \documentclass[beamer]{standalone}
%   % Load packages needed for this TeX file:
%   \usepackage{tikz}
%   % Surround TeX code with 'document' environment:
%   \begin{document}
%   \begin{standaloneframe}[<options>] % e.g. 'fragile'
%    % Add your TeX code:
%     \only<1>{ One }%
%     \only<2>{ Two }%
%   \end{standaloneframe}
%   \end{document}
% \end{lstlisting}
% \end{minipage}
%
% \par\bigskip\noindent
% \begin{minipage}{\textwidth}\noindent
% \begin{lstlisting}[language={[latex]tex},gobble=4,frame=lines,numbers=none,caption={Effective beamer code if compiled standalone.}]
%   \documentclass{beamer}
%   <beamer code from standalone.cfg file>
%   \usepackage{tikz}
%   \begin{document}
%   \begin{frame}[your options]
%     \only<1>{ One }%
%     \only<2>{ Two }%
%   \end{frame}
%   \end{document}
% \end{lstlisting}
% \end{minipage}
%
% \par\bigskip\noindent
% \begin{minipage}{\textwidth}\noindent
% \begin{lstlisting}[language={[latex]tex},gobble=4,frame=lines,numbers=none,caption={Effective code if included in a beamer presentation.},label=lst:beamerrepl]
%   \begingroup
%     \only<1>{ One }%
%     \only<2>{ Two }%
%   \endgroup
%   \endinput
% \end{lstlisting}
% \end{minipage}
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsection{Class configuration file}\label{sec:configfile}
% The \cls{standalone} class loads a configuration file called \file{standalone.cfg} just before the options are processed, but after all options and if-switches are declared.
% Any class options can then also be given using \Macro\standaloneconfig{<options>}.
% Settings which depends on the finally used options should be placed inside \Macro\AtEndOfClass{\ldots}, so that they are processed after all options.
% This is particular required for \cls{beamer} specific settings, because at load time of the configuration file a given \opt{beamer} option is not yet processed.
% Please note that this was handled differently before v1.0, so in old configuration files edited by the user the \Macro\AtEndOfClass must now be added.
%
% A default configuration file is provided together with the bundle and holds some default settings. Because this file will be overwritten every time the bundle is updated, users
% should create an own configuration file in the local TEXMF tree or the document directory. In order to keep the default behaviour this file should either contain the content of the bundle configuration file
% or load it.
% Because it can be assumed that the bundle configuration file resides inside a \file{standalone} directory, therefore it can be loaded from a user configuration file using
% \Macro\input{standalone/standalone.cfg}.
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsection{Conversion to images}\label{sec:convert}
% Using the \opt{convert} class option the standalone file can be easily converted to an raster image. This is done by executing an external program to convert the output file (PDF or PS) to
% an image (recommended is the lossless PNG format, but also others are supported).
%
% \subsubsection{Conversion settings}
% Conversion settings can be given as the value of the \Key{convert}'='{<settings>} option.
% By default conversion is disabled (\Key{convert}'=false'). If enabled without providing own settings (\Key{convert}, \Key{convert}'=true')
% the following default settings are used: PNG format, a density of 300dpi, no explicit size and the output file name is given by \Macro\jobname, i.e.\ the name of the \LaTeX\ document.
% Using the \opt{convert} option with any value other than |false| will enabled it.
% All normal conversion settings are listed in \autoref{tab:convopt}, while \autoref{tab:advconvopt} lists the more advanced options which e.g.\ can be used to modify the conversion command directly.
% Note that macros used inside documentclass options must be protected from expansion. This can either be done wrapping the whole argument in an \Macro\unexpanded{..} (requires e-\TeX)
% or by using \Macro\noexpand in front of any macro.
%
% \begin{table}
% \vspace*{-10ex}%
% \belowcaptionskip=\abovecaptionskip
% \caption[Conversion Options]{Conversion Options (to be used in the value of \opt{convert} class option)}\label{tab:convopt}
% \hbox to \textwidth{\hss%
% \begin{tabular}{>{\ttfamily}lp{\dimexpr.7\textwidth\relax}l}
%  \toprule
%  \multicolumn{1}{l}{Sub-Option}  &  Description & Default value \\
%  \midrule
%   (no value) &  Conversion enabled with default settings   & ./. \\
%     true     &  Conversion enabled (with default settings if no other options are given)  & (no value) \\
%     false    &  Conversion disabled   & (no value) \\
%  \midrule
%     density  &  Sets the density in dots-per-inch (dpi). Can be a single numerical value or `\meta{X}|x|\meta{Y}'.  & |300| \\
%     size     &  Sets the size of the image. Can be a single numerical value or `\meta{X}|x|\meta{Y}'. If empty the size is determined by the density setting and the size of the PDF. & (empty) \\
%  subjobname  &  The jobname used for the internal \LaTeX\ run  & |\jobname| \\
%     inext    &  Input file extension including the leading dot  & |.pdf| or |.ps| \\
%     inname   &  Name base of input file (i.e.\ file name without extension)  & |\subjobname| \\
%     infile   &  Input file name  & |\inname\inext| \\
%     outext   &  Output file extension including the leading dot  & |.png| \\
%     outname  &  Name base of output file  & |\inname| \\
%     outfile  &  Output file name  & |\outname\outext| \\
%  \bottomrule\noalign{\smallskip}
%  \multicolumn{3}{l}{%
%   \strut Note: the settings (except 'true' and 'false') can also be used as macros in other settings.
%   }%
% \end{tabular}
% \hss}
% \medskip
% \caption{Advanced Conversion Options}\label{tab:advconvopt}
% \hbox to \textwidth{\hss%
% \begin{tabular}{>{\ttfamily}lp{\dimexpr.6\textwidth\relax}l}
%  \toprule
%  \multicolumn{1}{l}{Sub-Option}  &  Description & Default value \\
%  \midrule
%     command  &  Command line used for conversion. & (see |imagemagick|) \\
%     imagemagick & Sets the convert command to use Image Magick: \newline\bigskip
%                   \hspace*{-5em}\hbox{\vtop{\hbox{\strut|command=\unexpanded{{\convertexe\space -density \density\space |\vrule height 2\ht\strutbox width 0pt{}}%
%                                      \hbox{\strut|         \infile\space \ifx\size\empty\else |}%
%                                      \hbox{\strut|         -resize \size\fi\space -quality 90 \outfile}}|}}\hss} \\
%     convertexe  & Name of the executable of Image Magick. & (see \autoref{sec:convprogs})  \\
%     ghostscript & Sets the convert command to use Ghostscript: \newline\bigskip
%                   \hspace*{-5em}\hbox{\vtop{\hbox{\strut|command=\unexpanded{{\gsexe\space -dSAFER -dBATCH -dNOPAUSE|\vrule height 2\ht\strutbox width 0pt{}}%
%                                      \hbox{\strut|         -sDEVICE=\gsdevice\space -r\density\space|}%
%                                      \hbox{\strut|         -sOutputFile=\outfile\space \infile}}|}}\hss} \\
%     gsexe       & Name of the executable of Ghostscript. & (see \autoref{sec:convprogs})  \\
%     precommand  & Command to be executed before the actual conversion command.  & {\tabular[t]{@{}l@{}}|dvips \subjobname| (DVI/PS),\\empty (PDF)\endtabular} \\
%     gsdevice    & The output device to be used for ghostscript. Already set up for PNG and JPG output. & \parbox[t]{15em}{Uses known device if defined for output format, otherwise the output format itself.}\\
%     onfailure   & Sets if an type of `message' which should be triggered on conversion failure:  |error|, |warning|, |info| or |ignore|. & |warning| \\
%  \bottomrule
% \end{tabular}
% \hss}
% \end{table}
%
% \subsubsection{Conversion software}\label{sec:convprogs}
% The conversion requires an external image converter program to be installed. By default the two following tools are supported and either of them must be installed in order to use the conversion feature.
% In order for an external program to be executed the \texttt{-shell-escape} option\footnote{Maybe named differently depending on the used \LaTeX\ distribution} must be used for the
% compiler executable, e.g.\ \texttt{pdflatex -shell-escape filename}. Without this option no conversion is possible.
%
% By default the conversion program of \href{http://www.imagemagick.org/}{Image Magick} is used for PDF \LaTeX\ files, which is freely available for Unix/Linux, Mac and MS Windows.
% Under Ubuntu Linux it can be installed using the shell command `\texttt{sudo apt-get install imagemagick}'.
% The conversion executable is simply called `|convert|'. However, there is another program with the same name provided by MS Windows itself which
% converts old FAT filesystems to NTFS! It has been suggested to rename the Image Magick executable to `|imgconvert|' instead.
% By default \cls{standalone} uses `|imgconvert|' as executable if MS Windows is detected and `|convert|' otherwise.
% The executable name can be change manually using the `|convertexe|' conversion option or by using
% \codeline{\AlsoMacro\standaloneconfig{'convert='{'convertexe='{convert}}}}
% in the configuration file `|standalone.cfg|'.
%
% Another conversion program is \href{http://pages.cs.wisc.edu/~ghost/}{Ghostscript} which is a very common PostScript interpreter which also supports PDF.
% It is used by default for DVI/PS files.
% Under Ubuntu Linux it is most likely already installed but otherwise can be installed using `|sudo apt-get install ghostscript|' or
% `|sudo apt-get install gs|'.
% It can convert both to various output formats and is freely available for Unix/Linux, Max OS X and MS Windows.
% It requires to set the correct output device which is not always fully identical to the output format (e.g.\ `|png16m|' for a PNG (with 16 million colors)).
% The devices for PNG and JPG are already configured.
% Other devices can be configured using the \Key{defgsdevice}'='{<.extension>}{<device>} conversion setting.
% The Ghostscript executable is usually named `|gs|' under Linux/Unix and `|gswin32c|' under MS Windows and configured this way by default,
% but this may be changed using the |gsexe| setting.
%
%
% \subsubsection{Conversion process}
% The conversion process is currently implemented in the following way to allow the normal compilation and subsequent conversion using only one (manual) compiler run.
% Because the document must be fully compiled before the conversion can occur the \cls{standalone} executes the same \LaTeX\ compiler (e.g.\ texttt{pdflatex}) again as
% a sub-process which compiles the current document fully. This is done when the \cls{standalone} class is loaded, so that the main compiler instance is still at \Macro\documentclass
% and has not yet itself opened the output file for writing. After the document got compiled using the sub-process the external conversion tool will be executed.
% If required intermediate conversions like \texttt{dvips} are also executed beforehand.
% Finally the main compiler run is terminated without producing any output, keeping the output file generated by the sub-process intact.
% A drawback of this implementation is that the log file created by the sub-process is overwritten by the main process and does not hold meaningful information.
% This can be compensated by setting a different jobname for the sub-process using the \Key{subjobname} conversion setting.
%
% \subsubsection{Conversion examples}
%
% PDF/PS is rastered with 600x100dpi and then converted to JPG:\\*[\smallskipamount]
% |  \documentclass[convert={density=600x100,outext=.jpg}]{standalone}|
%
% \par\medskip\noindent
% Produces BMP with 400x400px (one side might be meder if content is not quadratic in shape):\\*[\smallskipamount]
% |  \documentclass[convert={outext=.bmp,size=400}]{standalone}|
%
% \par\medskip\noindent
% Produces TIFF G4 output file using Ghostscript with a density of 72dpi:\\*[\smallskipamount]
% |  \documentclass[convert={ghostscript,gsdevice=tiffg4,|\\*
% |                 outext=.tiff,density=72}]{standalone}|
%
% \par\medskip\noindent
% Produces PNG (default) with a size of 640px (suitable to be uploaded on StackExchange sites without the image getting downscaled):\\*[\smallskipamount]
% |  \documentclass[convert={size=640}]{standalone}|
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% \subsection{Simple TeX File}
% A simple \file{standalone.tex} file is provided together with the bundle, which may be useful in special occasions.
% It will set the \cs{ifstandalone} switch to \emph{true} when compiled standalone but to \emph{false}
% when loaded after any |\documentclass| macro, as long the switch isn't defined yet.
% It must be used if this switch is required before the |\documentclass| of a standalone file.
%
% \noindent
% \begin{minipage}{\textwidth}\noindent
% \begin{lstlisting}[language={[latex]tex},gobble=4,frame=lines,numbers=none,caption={Usage of 'standalone.tex'.}]
%   \input{standalone} % use before any '\documentclass'
%   \ifstandalone
%     % Used only if compiled standalone
%   \fi
% \end{lstlisting}
% \end{minipage}
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsection{FAQ / Troubleshooting}\label{sec:classfaq}
% This section expands some issues and their solution which can arise with the \cls{standalone} class.
%
% \subsubsection*{Large white space / border at the right side}
% A large white space / border on the right side occurs when the content is placed inside a paragraph.
% This causes the content to be \Macro\linewidth wide and so smaller pictures will contain now a white space at the right.
% A common cause for this is that there was is a empty line between the content and \Macro\end{document} which causes a paragraph break.
%
% This issue can be solved by either removing any trailing lines or other paragraph breaks, or by using the \opt{varwidth} option which suppresses the extra added width.
% It is also possible to use the \opt{multi} option and \Macro\standaloneenv{<environment name>} to declare certain environments as page content.
% The \opt{tikz} option does this for \env{tikzpictures} and the \opt{pstricks} option for \env{pspicture}. See the descriptions of these options for more details.
%
% \subsubsection*{Some amount of the content on the right side is missing}
% If the content is cropped to much on the right side, check if the \opt{varwidth} option is used. In this case the used maximum width (\Macro\linewidth by default) is too small.
% A larger width can be set using \hbox{\opt{varwidth}\MacroArgs'='<length>} or the option can be disabled altogether using \hbox{\opt{varwidth}|=false|}.
% The largest width possible is given by \Macro\maxdimen, which however might cause internal overflows.
%
% This can also be caused with \cls{beamer} content (i.e.\ when the \opt{beamer} option is used). In this case no cropping or \env{varwidth} environment is used at all,
% but the content is simply to large to fit on a \cls{beamer} \env{frame}. To avoid this rescale the content to do fit. This can be realised by either using
% scaling facilities of the used picture environment (like |scale| with \env{environment}, but this only scales coordinates) or using \Macro\scalebox or \Macro\resizebox from \pkg{graphicx}.
% For complicated code which contains verbatim or other catcode changing code either the \Macro\Resizebox from the \pkg{realboxes} package
% or the \MacroArgs{adjustbox}{scale=<factor>} environment from the \pkg{adjustbox} package should be used.
%
% \subsubsection*{A multi-page document contains some pages with unwanted content}
% This is caused while \opt{multi}|=true| and \opt{crop}|=true| are set but \opt{ignorerest}|=false| \emph{and} the document contains
% typeset material outside of environments declared with \Macro\standaloneenv. To avoid that this extra material should be removed or \opt{ignorerest} should be set to |true|.
% This will also ignore all settings inside the document body which are not inside a declared environment. These can be moved to the preamble instead.
% See the description of the \opt{ignorerest} option for more details.
%
% \subsubsection*{In a multi-page document using DVI/PS mode all pages except the first have a vertical offset}
% The vertical reference points in PostScript could does not change when the pages are resized to fit the individual content of every page.
% Therefore an offset is added to compensate for this, which shifts the content to the appropriate vertical position.
% Should this not work as expected please inform the package author and provide a small example which causes this issue, together with the version number of the used |latex| compiler and tools (like |dvips|, |ps2pdf|)
% as well as the used \cls{standalone} bundle.
%
% \subsubsection*{Issues with cropped files in DVI mode}
% The \opt{crop} option uses PostScript commans in DVI mode, i.e.\ when |latex| not |pdflatex| (or others) is used as a compiler.
% This PostScript commands will only work once the DVI is converted to PS or EPS.
% Currently this cropping code is experimental and might not produce a full (E)PS standard compatible file.
% This can lead to wrong bounding boxes and wrong orientations or, dependent on the used PostScript tool, even to PostScript compiler errors.
% Some issues can be overcome by converting the the (E)PS file to a (more) standard compatible version using tools like |eps2eps| or Ghostscript.
%
% \subsubsection*{Errors ``Float(s) lost'' or ``not in outer par mode''}
% Floating environments like \env{figure} or \env{table} can not be used while \Key{float}'=true' and either \Key{crop}'=true' or \Key{preview}'=true' is set.
% The last two options will try to store the float into a box which is not allowed (because it can't the float any longer).
% Usually \Key{float}'=false' will solve this error, because it turns these environments into non-floating alternatives.
% Because both the \Key{crop} and \Key{preview} option will set \Key{float}'=false' themselves, this issue can only arise when the \Key{float} option is manually set afterwards.
%
% \subsubsection*{Image conversion does not work}
% In order for the image conversion to work an external conversion software must be installed. By default either Image Magkick or GhostScript is used. Please insure that either or both of these softwares are installed.
% Installation guide for your operating system should be easily available on the Internet. The \LaTeX\ compiler option |-shell-escape| must be used to allow this external software to be executed from within the \LaTeX\ code.
% If this two points are fulfilled but the conversion does still not work, please check the log file. The lines in question start with `|runsystem|' (at least with \TeX\ Live 2011).
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \clearpage
% \section{Usage of the \pkg{standalone} package}
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsection{Basic usage}
% The \pkg{standalone} package needs simply be loaded using \Macro\usepackage in a main document. It redefines the \Macro\documentclass macro, which can occur in sub-files,
% so that it ignores anything till the next \Macro\begin{document} and then takes the \env{document} environment as a simple group. The real \env{document} environment in the main file is not
% affected. Sub-files can then be included in the main document body using \Macro\input{<filename>}.
%
% The \pkg{standalone} package must not be loaded before the document class using \Macro\RequirePackage, because this will cause issues.
% Also it is not possible to \Macro\input\relax standalone files inside the preamble, e.g.\ as part of a \Macro\savebox assignment.
%
% It is possible to cascade \cls{standalone} files, i.e. \Macro\input\relax a \cls{standalone} file from within a \cls{standalone} file. Then both the \cls{standalone} class and the \pkg{standalone}
% package must be loaded by the any parent \cls{standalone} file. These parent files can still be used inside other \LaTeX\ documents if these load the \pkg{standalone} package themselves.
%
% See \autoref{sec:pkgoptions} for a list of package options which enable further features.
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsection{Package options}\label{sec:pkgoptions}
% The following options are supported by the \pkg{standalone} package.
% Most of them are boolean options which take either `|true|' or `|false|' as optional values. If such an option is used without a value, `|true|' is used.
% If not mentioned otherwise all options set to `|false|' initially.
% Options might switch other options on or off. The order of the option is obeyed and later options will prevail over earlier ones.
% Note that some older versions of the \pkg{standalone} package only take the option without any value.
%
% \DescribeKey{subpreambles}'=true|false'
% The \cls{standalone} package removes all sub-file preambles (``sub-preambles'') by default when loaded.
% However, if the package is loaded with the \opt{subpreambles} options, all sub-preambles are stored in an auxiliary file with the name `\meta{main tex file name}|.sta|' (for \emph{sta}ndalone).
% This file is then loaded or processed at the beginning of the next \LaTeX\ run (i.e.\ at the place in the preamble where the \cls{standalone} package is loaded).
% The way how the \opt{subpreambles} option works can be controlled by the options \opt{sort}, \opt{print} and \opt{comments}/\opt{nocomments}.
% Please note that the \opt{sort} and \opt{print} options require of course the \opt{subpreambles} option and will enable it if not already done so.
%
% \DescribeKey{sort}'=true|false'
% With only the \opt{subpreambles} option set, the sub-preambles are simple read and executed unchanged. This includes the risk of option clashes if one package is loaded with different
% options inside the sub-preambles and/or the main preamble. This is avoided by the \opt{sort} option, which accumulates all packages loaded by all sub-files together with their options.
% The options are then marked to be loaded by the package using \LaTeX{}s \cs{PassOptionsToPackage} macro. The packages are loaded at the end of the preamble using the \cs{AtBeginDocument} hook.
% This allows the user to load the same packages with own options in the main file, after the |standalone| package is loaded, without any option clashes.
%
% \DescribeKey{print}'=true|false'
% While the \opt{sort} option is giving already good results, problems with the order of packages can still occur. Some packages provide, redefine or patch the same macros, so that they must be loaded in
% the correct order to give the desired result. Potential additional code in the sub-preambles, required for some sub-figures but maybe incompatible with others, complicates the situation further.
% If such issues occur they can hardly be handled in an automatic way. Instead the sub-preambles must be carefully merged into the main preamble.
% The option \opt{print} was created to simplify this otherwise cumbersome task.
% It concatenated all sub-preambles into a single file named `\meta{main tex file name}|.stp|' (for \emph{st}andalone, \emph{p}rint). Each preamble is commented with its original file name.
% Please note that |.sta| file mentioned above, while quite similar, holds additional macros and might not be easily user readable or editable.
% After the file was generated it can be easily pasted into the main file preamble using a text editor.
%
% When the \opt{print} option is enabled the normal |.sta| file is not generated or loaded. Because this will cause most likely some errors related to packages not loaded, all sub-file bodies will be skipped.
% A warning is printed for each sub-file to remind the user about this fact. The \opt{print} option is only indented to by used when required to get a list of sub-preambles. After including this list in the main file the option
% must be removed to compile the main file normally.
%
% \DescribeKeys
% \hbox{\Key{print},\Key{sort}}
% \endDescribeKeys
% Finally if both the \opt{print} and \opt{sort} options are enabled, a `sorted' list of sub-preambles is printed into the |.stp| file. In this `sorted print' mode all |\usepackage| macros and other
% similar macros like |\usepgflibrary|, |\usetikzlibrary| as well as |\usetikztiminglibrary| from the |pgf|, |tikz| and |tikz-timing| packages, respectively) are removed from the rest of the sub-preamble code.
% A list of packages (and libraries) without duplicates is printed at the begin of the |.stp| file (using |\usepackage|, of course). Every option provided by any sub-file for a package is added, again without duplicates.
% If specific package date was requested in a sub-file it is also added. If multiple dates are requested for one package, the most recent (i.e.\ the ``highest one'', not the last processed) is used.
% After this list(s) the rest of the sub-preamble code is printed with the above macros removed. This mode frees the user from the need to remove duplicates and collect package options manually.
%
% Please note that all |\usepackage| and similar macros inside braces |{}| will not be seen by \cls{standalone}s sort macro and therefore are not extracted or handled in any special form mentioned above.
% This can be exploited to load certain packages only in \cls{standalone} mode but not in the main document.
% Unfortunately, macros inside \Macro{ifstandalone}!\ldots!\AlsoMacro\fi are seen and extracted while not wanted inside the main file.
% The macro \Macro\onlyifstandalone{<code>} (see below) was created because of this two reasons. Its argument braces hide the content from the scanner.
% It is then also completely removed from the printed sub-preamble code.
%
% \DescribeKey{comments}'=true|false'
% \DescribeKey{nocomments}
% The \opt{comment} option selects if the |.stp| file should also include the comments of the sub-preambles.
% For backwards compatibility \opt{nocomments} exists which is identical to \Key{comments}'=false'.
% Comments are included by default in the non-sorting print mode (\opt{print} without \opt{sort} option), but can cause `wrong' results during the `sorting' process and are therefore removed by default in this mode.
% The reason for this can be explained as follows.
% In order to transfer the comments from the sub-files to the |.stp| file \TeX\ must be instructed to handle them as normal input and not discard them.
% However, in this case the scanning algorithm which removes |\usepackage| and friends can not distinguish
% between `active' macros and macros which are commented out. All above mentioned macro inside comments will then be processed as when there where `active'.
% The user might favour the information provided by the comments over this small risk and enable them using the \opt{comments} option.
%
% \DescribeKey{group}'=true|false'
% This option is set the `|true|' by default and controlled whether or not a group is added around the content of standalone files. Normally (`|true|') the \env{document} environment of the sub-files
% is turned into an environment which does nothing, besides adding the usual group. If set to `|false|' this environment made transparent, so that no group is added.
% Any definition inside the document body of sub-files will still be accessible after the \Macro\input\relax macro. Note that this does not effects the \Macro\includestandalone macro which always
% will add a group.
%
% \DescribeKey{mode}'='<mode>
% Sets the mode for \Macro\includestandalone. Valid values are `|tex|' (use source file, default),
% `|image|' (use existing image file produced by the source file), `\verb+image|tex+' (use image if available, source otherwise),
% `|build|' (build image from source, then use it), `|buildmissing|' (only build image if it does not exist)
% and `|buildnew|' (only build image if source file is newer; doesn't work with \XeLaTeX). See \autoref{sec:pkgmacros} for more details.
% See also \autoref{sec:build} for further details.
%
% \DescribeKey{obeyclassoptions}'=true|false'
% If this option is enabled the \Macro\includestandalone will try to obey the class options used in the standalone files while in `|tex|' mode.
% This only works if the standalone file uses the \cls{standalone} class and only with certain options. The class configuration file will also be loaded (in
% a local scope, for every standalone file) in order to load the default settings.
%
% This feature is intended to ensure (nearly) identical results independent if the standalone files are included as source code or as image,
% in order to permit an easy switch between this two modes.
% In particular, the standard size options |10pt|, |11pt| and |12pt| are applied to the standalone file (supported for the standard and KOMA Script classes)
% as well as the \opt{border} class option. The \opt{multi}'='{<environment>, \ldots} option is supported and will make the |page=|\meta{number} option of \Macro\includegraphics
% work with \Macro\includestandalone. This means, that one particular page can be selected, while all other environments are skipped.
% By default the first page is taken (if \opt{multi} was used). The special value of |-1| will include all pages from the source file (but not from the image).
% Because \opt{multi} option will assume that either \opt{crop} or \opt{preview} is enabled and will always ignore other content like with \Key{ignorerest}'=true'.
% These three class option will be ignored by the package, which might lead to different behaviour between standalone and main-document mode, but only for uncommon cases
% where \opt{multi} is used without declaring environments and with disabled cropping (\opt{crop}/\opt{preview}).
% In order to support a potential \opt{varwidth} option the \pkg{varwidth} is loaded if it is available.
%
% This is an extended feature, which requires substantial amount of extra code and some advanced techniques to switch the font size.
% It might not work correctly under all circumstances. Because of this it is disabled by default.
% At the moment it does not take the class configuration file into account and does not work for \cls{beamer} standalone files.
%
% \DescribeKey{extension}'='<.extension>
% The image file extension (with leading dot) used for \Key{mode}'=image' can be selected using this option.
% By default the target output file extension of the used \LaTeX\ compiler is used, i.e.\ `|.pdf|' for |pdflatex|,
% |lualatex| and |xelatex| and `|.eps|' (converted from DVI) for |latex|.
%
% \DescribeKey{build}'='{<build options>}
% This option allows to set the options used for building images from standalone files.
% See \autoref{sec:build}, especially \autoref{tab:buildsettings} for further details.
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsection{Macros}\label{sec:pkgmacros}
% The following user macros are provided by the \cls{standalone} package. Further macros are listed in \autoref{sec:common} which are
% defined by both the class and package and can be used in standalone files but also in the main document.
%
% \DescribeMacro\standaloneconfig{<options>}
% This configuration macro accepts some of the package options described in \autoref{sec:pkgoptions}. These options are \opt{group}, \opt{mode}, \opt{extension} and \opt{build},
% which can be changed for different included standalone files.
%
% If both the \pkg{standalone} class and package is used together this macro can also be used to set the class options as described in \autoref{sec:classmacros}.
%
% \DescribeMacro\includestandalone[<options>]{<file>}
% This sophisticated macro can be used instead of \Macro\input\relax to include standalone files. Its behaviour is controlled by the \opt{mode} package option.
% This macro can either include the source code in the same way as \Macro\input\relax (\Key{mode}'=tex'), include the output file (PDF, EPS) using \Macro\includegraphics\relax
% (\Key{mode}'=image'), try first the output file and use the source file if it is available (\Key{mode}'=image|tex'),
% build the output file from the source file either always (\Key{mode}'=build'), only if the image files does not exist (\Key{mode}'=buildmissing')
% or only if the source file is newer (\Key{mode}'=buildnew', which doesn't work on \XeLaTeX\ because some pdf\TeX\ macros are required for this).
% See also the \autoref{sec:build} for further details.
%
% The \meta{file} argument must be the file name of the standalone source file \emph{without} the extension. The macro accepts the same \meta{options} as \Macro\includegraphics as well
% as any options suitable for \Macro\standaloneconfig. This means that the source file can also be resized and rotated in `|tex|' mode like an image.
% TODO: In this mode the package also tries to extract and apply the class options from the standalone file and apply these to the included source.
% Unfortunately, it can not be fully guaranteed that the standalone content will be displayed identical in source code and image mode. Some settings might not be applied
% in the same way and rounding differences may occur.
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsection{Building images from standalone files}\label{sec:build}
% Using the \Macro\includestandalone macro standalone files can be either included directly as source files or as vector graphic images which are build from these.
% The \pkg{standalone} package provides the feature to automatically build image files from given standalone source files.
% This is controlled by the \opt{mode} options. This was already described in \autoref{sec:pkgoptions} and~\ref{sec:pkgmacros}.
%
% This enables the user to switch easily between including source code or images, either globally or only for selected standalone files.
% Using images has the benefit that the included material, often complicated pictures, does not have to be recompiled every time with the main document.
% This leads to significant speed improvements. The drawback is a slight increase in file size, because the material will have its own file headers.
% Also any settings done in the main document which would affects the source code will not have an effect on the image. This can be positive or negative dependent on the case.
%
% An extended feature is the automatic building of images from the standalone files, either always or only if the source files are newer than the existing image files.
% In this cases the \Macro\includestandlone macro will call the \LaTeX\ compiler on the standalone files in question to produce the images, then include these using \Macro\includegraphics.
% This requires the `|-shell-escape|' compiler option to be set, otherwise the execution of shell commands is disabled for security reasons.
%
% The image files will normally be created in the current directory of the main document, which is not necessarily the same directory where the source files are located.
% Dependent on the used compiler settings, files in the current directory will be found first before other directories are searched.
% Using \Key{mode}'=buildnew' newly build image files placed in the current directory will therefore taken before older images files potentially located in the directory of
% the standalone files. Because the exact directory of source files is not accessible within \LaTeX\ documents, it is not possible to create the images files always in the same directories
% as the source files. Compiler options like `|-output-directory|' can be useful to influence the output directory of the build images. However, these options must be used with the
% internal compiler run, i.e.\ by setting \Key{build}'='{'latexoptions='<...>} appropriately, not (only) on the main \LaTeX\ compiler run.
%
% If the build process fails a warning is issued and the source code will be included instead. It should be noted that failure detection is not perfect and might lead to false positives or negatives.
%
% \begin{table}
% \makeatletter
% \def\showbuildvar#1{{%
%   \expandafter\let\expandafter\@tempa\csname sa@build@#1\endcsname
%   \@onelevel@sanitize\@tempa
%   \texttt{\@tempa}
% }}%
% \makeatother
% \belowcaptionskip=\abovecaptionskip
% \caption{Build settings}\label{tab:buildsettings}
% \hbox to \textwidth{\hss%
% \begin{tabular}{>{\ttfamily}lp{\dimexpr.45\textwidth\relax}l}
%  \toprule
%  \multicolumn{1}{l}{Build setting} &  Description & Default value \\
%  \midrule
%   latex & \LaTeX\ compiler to be used & Same as main compiler \\
%   latexoptions & Command line options for compiler & \tiny\showbuildvar{latexoptions} \\
%   jobname & Jobname for build compiler run & \scriptsize\showbuildvar{jobname} \\
%   quote & Character to be used to quote file names & \verb|'| for Linux\,\&\,Mac OS X, \verb|"| for Windows \\
%   command & Full build shell command & \scriptsize\showbuildvar{command} \\
%   postcommand & Command executed after main command, to produce final output file & \scriptsize\texttt{dvips -o '\textbackslash file.eps' '\textbackslash file.dvi'} \normalsize (DVI mode only)\\
%  \bottomrule\noalign{\smallskip}
%  \multicolumn{3}{l}{%
%   \strut Note: the settings (except `\texttt{command}' and `\texttt{postcommand}') can also be used as macros in other settings.
%   }\\%
%  \multicolumn{3}{l}{%
%   \strut The given file name is available (without extension) as \texttt{\textbackslash file}.
%   }%
% \end{tabular}
% \hss}
% \end{table}
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \section{Common macros}\label{sec:common}
% The following conditional macros are defined by both the \cls{standalone} class and package, but react differently when the code is compiled standalone or as part of a main document.
%
% \DescribeMacro{\ifstandalone}
% Both the class and the package provide the if-switch \cs{ifstandalone}, which can be used to only include code if the file is
% compiled standalone. The switch is set to \cs{iftrue} by the class and to \cs{iffalse} by the package.
%
% The additional file \file{standalone.tex} also defines this switch by checking if \cs{documentclass} was already used. It can be included
% with |\input{standalone}| and is intended for specialised files which do not use the \cls{standalone} class.
%
% \DescribeMacro{\IfStandalone}{<code for standalone mode>}{<code for main document>}
% This is the macro version of the \Macro\ifstandalone if-switch. It executes the first argument only in \cls{standalone} mode, i.e.\ when the file is compiled on its own.
% When included in the main document the second argument is executed instead.
% As mentioned in \autoref{sec:pkgoptions}
% it can also be used to hide |\usepackage| and similar macros from the extraction scanner of the |sort| option. The macro and its arguments is not printed into the |.stp| file.
%
% \DescribeMacro{\onlyifstandalone}{<code>}
% This macro is similar to \Macro\IfStandalone but only has takes one argument which is executed only in standalone mode, but ignored when compiled as part of a main document.
% As mentioned in \autoref{sec:pkgoptions}
% it can also be used to hide |\usepackage| and similar macros from the extraction scanner of the |sort| option. The macro and its argument is not printed into the |.stp| file.
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \section{Usage Examples}
%
% \def\lstlistingname{Example}
% \setcounter{lstlisting}{0}
%
% \par\noindent
% \begin{minipage}{\textwidth}
% \begin{lstlisting}[language={[latex]tex},gobble=4,frame=lines,caption={Use of \emph{standalone} package.}]
%   % Main file
%   % Real document class:
%   \documentclass{article}
%
%   % Use the 'standalone' package:
%   \usepackage{standalone}
%
%   % Load all packages needed for all sub-files:
%   \usepackage{tikz}
%
%   % Inside the real 'document' environment
%   % read the sub-file with '\input'
%   \begin{document}
%   % ...
%   \begin{figure}
%     \input{subfile}
%     \caption{A subfile}
%   \end{figure}
%   % ...
%   \end{document}
% \end{lstlisting}
% \end{minipage}
%
% \par\noindent
% \begin{minipage}{\textwidth}
% \begin{lstlisting}[language={[latex]tex},gobble=4,frame=lines,caption={Use of \emph{standalone} class.}]
%   % A sub-file (e.g. picture) using the 'standalone' class:
%   % Use 'standalone' as document class:
%   \documentclass{standalone}
%
%   % Load packages needed for this TeX file:
%   \usepackage{tikz}
%
%   % Surround TeX code with 'document' environment as usually:
%   \begin{document}
%   % Add your TeX code, e.g. a picture:
%   \begin{tikzpicture}
%     \draw (0,0) rectangle (2,1) node [midway] {Example};
%   \end{tikzpicture}
%   \end{document}
% \end{lstlisting}
% \end{minipage}
%
% \par\noindent
% \begin{minipage}{\textwidth}
% \begin{lstlisting}[language={[latex]tex},gobble=4,frame=lines,caption={Effective code if compiled standalone.}]
%   \documentclass{article}
%
%   \newenvironment{standalone}{\begin{preview}}{\end{preview}}
%   \input{standalone.cfg}
%   % which by defaults loads:
%   % \PassOptionsToPackage{active,tightpage}{preview}
%   \usepackage{preview}
%
%   \usepackage{tikz}
%
%   \begin{document}
%   \begin{standalone}
%   \begin{tikzpicture}
%     \draw (0,0) rectangle (2,1) node [midway] {Example};
%   \end{tikzpicture}
%   \end{standalone}
%   \end{document}
% \end{lstlisting}
% \end{minipage}
%
% \par\noindent
% \begin{minipage}{\textwidth}
% \begin{lstlisting}[language={[latex]tex},gobble=4,frame=lines,caption={Effective code if included in a main document.}]
%   \begingroup
%   \begin{tikzpicture}
%     \draw (0,0) rectangle (2,1) node [midway] {Example};
%   \end{tikzpicture}
%   \endgroup
%   \endinput
% \end{lstlisting}
% \end{minipage}
%
%
%
% \StopEventually{}
% \clearpage
% \section{Implementation}
% \lstset{numbers=left}
%
% \iffalse
%<*standalone.cls>
% \fi
%
% \subsection{The Class File}
%    \begin{macrocode}
%<!COPYRIGHT>
\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{standalone}[%
%<!DATE>
%<!VERSION>
%<*DRIVER>
    2099/01/01 develop
%</DRIVER>
    Class to compile TeX sub-files standalone]
%    \end{macrocode}
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{If-Switches}
%
% \begin{macro}{\ifstandalone}
% This if-switch is defined by both the class and package. This class sets
% it to true while the package (loaded by the main document) sets it to false.
%    \begin{macrocode}
\newif\ifstandalone
\standalonetrue
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifstandalonebeamer}
% This if-switch is defined by both the class and package. This class sets
% it to true only if the |beamer| option was given. The package (loaded by the main document) sets it always to false.
%    \begin{macrocode}
\newif\ifstandalonebeamer
\standalonebeamerfalse
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\onlyifstandalone}
% Macro version of |\ifstandalone|. The |{ }| around the argument protects the content from the package etc. scanners.
%    \begin{macrocode}
\let\onlyifstandalone\@firstofone
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\IfStandalone}[2]{true clause}{false clause}
% Macro version of |\ifstandalone .. \else .. \fi|. The |{ }| around the argument protects the content from the package etc. scanners.
%    \begin{macrocode}
\let\IfStandalone\@firstoftwo
%    \end{macrocode}
% \end{macro}
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{Code for border values}
% The following macros are used to parse the \opt{border} option.
%
% \begin{macro}{\sa@border@left}
% \begin{macro}{\sa@border@right}
% \begin{macro}{\sa@border@top}
% \begin{macro}{\sa@border@margin}
%    \begin{macrocode}
\def\sa@border@left{0.50001bp}
\let\sa@border@right\sa@border@left
\let\sa@border@top\sa@border@left
\let\sa@border@bottom\sa@border@left
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\rem@bp}
%    \begin{macrocode}
\def\rem@bp#1bp\relax#2\@nnil{#1}%
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\default@bp}
%    \begin{macrocode}
\def\default@bp#1#2{%
    \begingroup
    \afterassignment\remove@to@nnil
    \dimen@ #2bp\relax\@nnil
    \expandafter
    \endgroup
    \expandafter
    \def\expandafter#1\expandafter{\the\dimen@}%
}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sa@readborder}
%    \begin{macrocode}
\def\sa@readborder#1 #2 #3 #4 #5\@nnil{%
    \ifx\\#2#3#4\\%
        \default@bp\sa@border@left{#1}%
        \let\sa@border@right\sa@border@left
        \let\sa@border@top\sa@border@left
        \let\sa@border@bottom\sa@border@left
    \else
    \ifx\\#4\\%
        \default@bp\sa@border@left{#1}%
        \let\sa@border@right\sa@border@left
        \default@bp\sa@border@top{#2}%
        \let\sa@border@bottom\sa@border@top
    \else
        \default@bp\sa@border@left{#1}%
        \default@bp\sa@border@bottom{#2}%
        \default@bp\sa@border@right{#3}%
        \default@bp\sa@border@top{#4}%
    \fi\fi
}%
%    \end{macrocode}
% \end{macro}
%
% Define if-switches for TeX formats.
% This loads the corresponding packages if available, but falls back to some own code if they are not installed.
%    \begin{macrocode}
\expandafter\ifx\csname ShellEscape\endcsname\relax
    \IfFileExists{shellesc.sty}{
        \RequirePackage{shellesc}
        \@ifpackagelater{shellesc}{2016/04/29}{
        }{
            \protected\def\ShellEscape{\immediate\write18 }
        }
    }{
        \protected\def\ShellEscape{\immediate\write18 }
    }
\fi
\expandafter\ifx\csname ifluatex\endcsname\relax
    \IfFileExists{ifluatex.sty}{\@firstoftwo}{\@secondoftwo}{%
        \RequirePackage{ifluatex}
    }{
        \begingroup
        \expandafter\ifx\csname directlua\endcsname\relax
            \endgroup
            \expandafter\let\csname ifluatex\expandafter\endcsname\csname iffalse\endcsname
        \else
            \endgroup
            \expandafter\let\csname ifluatex\expandafter\endcsname\csname iftrue\endcsname
        \fi
    }
\fi
\expandafter\ifx\csname ifpdf\endcsname\relax
    \IfFileExists{ifpdf.sty}{\@firstoftwo}{\@secondoftwo}{%
        \RequirePackage{ifpdf}
    }{
        \begingroup
        \expandafter\ifx\csname pdfoutput\endcsname\relax
            \endgroup
            \expandafter\let\csname ifpdf\expandafter\endcsname\csname iffalse\endcsname
        \else
            \endgroup
            \ifnum\pdfoutput<1
                \expandafter\let\csname ifpdf\expandafter\endcsname\csname iffalse\endcsname
            \else
                \expandafter\let\csname ifpdf\expandafter\endcsname\csname iftrue\endcsname
            \fi
        \fi
    }
\fi
\expandafter\ifx\csname ifxetex\endcsname\relax
    \IfFileExists{ifxetex.sty}{\@firstoftwo}{\@secondoftwo}{%
        \RequirePackage{ifxetex}
    }{
        \begingroup
        \expandafter\ifx\csname XeTeXrevision\endcsname\relax
            \endgroup
            \expandafter\let\csname ifxetex\expandafter\endcsname\csname iffalse\endcsname
        \else
            \endgroup
            \expandafter\let\csname ifxetex\expandafter\endcsname\csname iftrue\endcsname
        \fi
    }
\fi
%    \end{macrocode}
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{Options}
%
%    \begin{macrocode}
\let\sa@classoptionslist\@classoptionslist
\RequirePackage{xkeyval}
\newif\ifsa@preview
\newif\ifsa@crop
\newif\ifsa@multi
\newif\ifsa@multido
\newif\ifsa@varwidth
\newif\ifsa@ignorerest
\newif\ifsa@ignoreempty
\newif\ifsa@tikz
\newif\ifsa@pstricks
\newif\ifsa@convert
\newif\ifsa@float
\newif\ifsa@math
%    \end{macrocode}
%
% The \cs{ifstandalonebeamer} switch is in the user-level.
% Wire the setter macros to the internal naming scheme, so that \Macro\sa@boolean can be used with it.
%    \begin{macrocode}
\let\sa@beamertrue\standalonebeamertrue
\let\sa@beamerfalse\standalonebeamerfalse
%    \end{macrocode}
%
% \begin{macro}{\sa@clsoption}
% Wrapper macro to define options.
%    \begin{macrocode}
\def\sa@clsoption{%
    \define@key{standalone.cls}%
}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{key}{standalone.cls}{border}
% Sets the border around the content.
%    \begin{macrocode}
\sa@clsoption{border}{%
    \sa@readborder#1 {} {} {} {} \@nnil
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.cls}{margin}
% Alias for \opt{border}.
%    \begin{macrocode}
\sa@clsoption{margin}{%
    \sa@readborder#1 {} {} {} {} \@nnil
}
%    \end{macrocode}
% \end{key}
%
% \begin{macro}{\sa@boolean}[2]{name of if-switch}{`true' or `false'}
% Sets if-switches.
%    \begin{macrocode}
\def\sa@boolean#1#2{%
    \sa@boolorvalue{#1}{#2}%
        {\ClassError{standalone}{Invalid value '#2' for boolean key '#1'}{}}%
}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sa@boolorvalue}[2]{name of if-switch}{`true', `false' or a value}{code to be executed if it is a value.}
% Sets if-switches.
%    \begin{macrocode}
\def\sa@boolorvalue#1#2{%
    \begingroup
    \edef\@tempa{#2}%
    \def\@tempb{true}%
    \ifx\@tempa\@tempb
        \endgroup
        \csname sa@#1true\endcsname
        \expandafter\@gobble
    \else
    \def\@tempb{false}%
    \ifx\@tempa\@tempb
        \endgroup
        \csname sa@#1false\endcsname
        \expandafter\expandafter
        \expandafter\@gobble
    \else
        \endgroup
        \expandafter\expandafter
        \expandafter\@firstofone
    \fi\fi
}
%    \end{macrocode}
% \end{macro}
%
%
%
%
% \begin{key}{standalone.cls}{preview}
% Boolean to control if \pkg{preview} package should be used.
%    \begin{macrocode}
\sa@clsoption{preview}[true]{%
    \sa@boolean{preview}{#1}%
    \ifsa@preview
        \setkeys{standalone.cls}{crop=false,float=false}%
    \fi
}
\sa@previewtrue
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.cls}{crop}
% Boolean to control if own code should be used.
% That code boxes the content and resizes the page to match the box dimensions.
%    \begin{macrocode}
\sa@clsoption{crop}[true]{%
    \sa@boolean{crop}{#1}%
    \ifsa@crop
        \setkeys{standalone.cls}{preview=false,float=false}%
    \fi
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.cls}{ignorerest}
% Boolean to control if all other code outside of specified environments should be explicit ignored.
% That code boxes the outside content and then than discards it.
%    \begin{macrocode}
\sa@clsoption{ignorerest}[true]{%
    \sa@boolean{ignorerest}{#1}%
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.cls}{ignoreempty}
% Boolean to control if empty boxes/pages should be ignored.
% This is intended mostly for the \opt{multi} option and currently only works with \opt{crop} but not with \opt{preview}.
%    \begin{macrocode}
\sa@clsoption{ignoreempty}[true]{%
    \sa@boolean{ignoreempty}{#1}%
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.cls}{multi}
% Boolean to control if multiple pages are used.
%    \begin{macrocode}
\sa@clsoption{multi}[true]{%
    \sa@boolorvalue{multi}{#1}{\sa@multitrue\AtBeginDocument{\standaloneenv{#1}}}%
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.cls}{multido}
% Boolean to control if the \Macro\multido macro from the \pkg{multido} package should be
% loaded and redefined to create a separate page per iteration automatically.
%    \begin{macrocode}
\sa@clsoption{multido}[true]{%
    \sa@boolean{multido}{#1}%
    \ifsa@multido
        \setkeys{standalone.cls}{multi=samultido}%
    \fi
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.cls}{math}
%    \begin{macrocode}
\sa@clsoption{math}[true]{%
    \sa@boolean{math}{#1}%
    \ifsa@math
        \setkeys{standalone.cls}{multi=true,ignoreempty=true,border=0.50001bp}%
    \fi
}
\AtBeginDocument{\ifsa@math\sa@math\fi}
%    \end{macrocode}
% \end{key}
%
% \begin{macro}{\sa@math}
% Enables a simple support for multiple math equations.
% Displaymath is typeset as in-text math but with \cs{displaystyle} in effect.
% This allows \Macro\(, \Macro\), \Macro\[ and \Macro\] as well as \env{math} and \env{displaymath}.
% To simply typeset multiple equations two environments \env{multimath} and \env{multidisplaymath}
% are defined which use \Macro\\ as a delimiter. Every equation will be placed on a tight page on its own.
% To allow a trailing \Macro\\ the \opt{ignoreempty} is automatically enabled.
%    \begin{macrocode}
\def\sa@math{%
    \standaloneenv{math}%
    \def\({\begingroup\math}%
    \def\){\endmath\endgroup}%
    \def\[{\(\displaystyle}%
    \def\]{\)}%
    \def\displaymath{\math\displaystyle}%
    \def\enddisplaymath{\endmath}%
    \newcommand*\multimathsep{%
        \endmath
        \math
        \let\\\multimathsep
    }%
    \newenvironment{multimath}{%
        \math
        \let\\\multimathsep
    }{%
        \endmath
    }%
    \newcommand*\multidisplaymathsep{%
        \endmath
        \math\displaystyle
        \let\\\multidisplaymathsep
    }%
    \newenvironment{multidisplaymath}{%
        \math\displaystyle
        \let\\\multidisplaymathsep
    }{%
        \endmath
    }%
}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{key}{standalone.cls}{varwidth}
% Boolean to control if \pkg{varwidth} package should be used.
% If so the content will be placed in a \env{varwidth} environment to avoid extending it to the full line width if a
% paragraph break is inserted.
%
% The option is by default set to true if the \pkg{varwidth} package is available.
%    \begin{macrocode}
\sa@clsoption{varwidth}[true]{%
    \sa@boolorvalue{varwidth}{#1}{\sa@varwidthtrue\def\sa@width{#1}}%
    \ifsa@varwidth
        \def\sa@varwidth{\varwidth{\sa@width}}%
        \def\sa@endvarwidth{\endvarwidth}%
    \else
        \let\sa@varwidth\@empty
        \let\sa@endvarwidth\@empty
    \fi
}
\let\sa@varwidth\@empty
\let\sa@endvarwidth\@empty
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.cls}{tikz}
%    \begin{macrocode}
\sa@clsoption{tikz}[true]{%
    \sa@boolean{tikz}{#1}%
    \ifsa@tikz
        \setkeys{standalone.cls}{multi=tikzpicture,varwidth=false}%
    \fi
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.cls}{pstricks}
%    \begin{macrocode}
\sa@clsoption{pstricks}[true]{%
    \sa@boolean{pstricks}{#1}%
    \ifsa@pstricks
        \setkeys{standalone.cls}{multi=pspicture,varwidth=false}%
    \fi
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.cls}{beamer}
% Boolean to control if the \cls{beamer} class is used.
%
% If true sets the class to \cls{beamer} and switches \opt{preview} off.
% If false the default class is restored if the current class was \cls{beamer}.
%    \begin{macrocode}
\sa@clsoption{beamer}[true]{%
    \sa@boolean{beamer}{#1}%
    \ifstandalonebeamer
        \def\sa@class{beamer}%
        \setkeys{standalone.cls}{preview=false,crop=false,varwidth=false}%
    \else
        \begingroup
        \def\@tempa{beamer}%
        \ifx\@tempa\sa@class
            \endgroup
            \def\sa@class{article}%
        \else
            \endgroup
        \fi
    \fi
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.cls}{class}
%    \begin{macrocode}
\sa@clsoption{class}{%
    \def\sa@class{#1}%
}
\def\sa@class{article}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.cls}{float}
%    \begin{macrocode}
\sa@clsoption{float}[true]{%
    \sa@boolean{float}{#1}%
    \ifsa@float
        \let\@float\sa@origfloat
        \let\end@float\sa@origendfloat
    \else
        \ifx\@float\sa@nofloat\else
            \let\sa@origfloat\@float
        \fi
        \ifx\end@float\sa@endnofloat\else
            \let\sa@origendfloat\end@float
        \fi
        \let\@float\sa@nofloat
        \let\end@float\sa@endnofloat
    \fi
}
\def\sa@nofloat#1{%
    \def\@captype{#1}%
    \trivlist\item[]%
    \@ifnextchar[{%
        \begingroup
        \def\@tempa[####1]{%
            \endgroup
        }\@tempa
    }{}%
}
\def\sa@endnofloat{%
    \endtrivlist
}
%    \end{macrocode}
% \end{key}
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% \begin{key}{standalone.cls}{convert}
%    \begin{macrocode}
\sa@clsoption{convert}[]{%
    \setkeys{standalone.cls/convert}{true,#1}%
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.cls}{disable@convert}
%    \begin{macrocode}
\sa@clsoption{disable@convert}[]{%
    \typeout{Disable conversion}
    \sa@convertfalse
    \let\sa@converttrue\relax
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{macro}{\sa@convertoption}
% Wrapper to define \opt{convert} options.
%    \begin{macrocode}
\def\sa@convertoption{%
    \define@key{standalone.cls/convert}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@convertvar}[2]{name}{initial value}
% Wrapper to define \opt{convert} variables.
%    \begin{macrocode}
\def\sa@convertvar#1#2{%
    \define@key{standalone.cls/convert}{#1}{%
        \@namedef{sa@convert@#1}{##1}%
    }%
    \@namedef{sa@convert@#1}{#2}%
}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{key}{standalone.cls/convert}{true}
%    \begin{macrocode}
\sa@convertoption{true}[]{%
    \sa@converttrue
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.cls/convert}{false}
%    \begin{macrocode}
\sa@convertoption{false}[]{%
    \sa@convertfalse
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.cls/convert}{png}
%    \begin{macrocode}
\sa@convertoption{png}[]{%
    \setkeys{standalone.cls/convert}{true,outext={.png}}%
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.cls}{png}
%    \begin{macrocode}
\sa@clsoption{png}[]{%
    \setkeys{standalone.cls/convert}{png,#1}%
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.cls/convert}{realmainfile}
%    \begin{macrocode}
\sa@convertoption{realmainfile}[]{%
    \RequirePackage{currfile-abspath}%
    \getmainfile
    \let\sa@convert@mainfile\themainfile
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.cls/convert}{jpg}
%    \begin{macrocode}
\sa@convertoption{jpg}[]{%
    \setkeys{standalone.cls/convert}{true,outext={.jpg}}%
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.cls}{jpg}
%    \begin{macrocode}
\sa@clsoption{jpg}[]{%
    \setkeys{standalone.cls/convert}{jpg,#1}%
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.cls/convert}{gif}
%    \begin{macrocode}
\sa@convertoption{gif}[]{%
    \setkeys{standalone.cls/convert}{true,outext={.gif}}%
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.cls}{gif}
%    \begin{macrocode}
\sa@clsoption{gif}[]{%
    \setkeys{standalone.cls/convert}{gif,#1}%
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.cls/convert}{onfailure}
%    \begin{macrocode}
\sa@convertoption{onfailure}{%
    \begingroup
    \edef\@tempa{#1}%
    \def\@tempb{error}%
    \ifx\@tempa\@tempb
        \endgroup
        \let\sa@convert@failuremsg\ClassError
    \else
    \def\@tempb{warning}%
    \ifx\@tempa\@tempb
        \endgroup
        \let\sa@convert@failuremsg\ClassWarning
    \else
    \def\@tempb{info}%
    \ifx\@tempa\@tempb
        \endgroup
        \let\sa@convert@failuremsg\ClassInfo
    \else
    \def\@tempb{ignore}%
    \ifx\@tempa\@tempb
        \endgroup
        \def\sa@convert@failuremsg##1##2##3{}%
        \let\sa@convert@notfoundmsg\@gobbletwo
    \else
        \let\on@line\@empty
        \ClassError{standalone}{Invalid value '\@tempa' for the 'onfailure' option.\MessageBreak
                                Valid values: 'error', 'warning', 'info', 'ignore'}{}%
        \endgroup
    \fi\fi\fi\fi
}
\let\sa@convert@failuremsg\ClassWarning
\let\sa@convert@notfoundmsg\ClassWarning
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.cls/convert}{gsdevice}
%    \begin{macrocode}
\sa@convertoption{defgsdevice}{%
    \sa@defgsdevice#1\relax\relax
}
\def\sa@defgsdevice#1#2{%
    \@namedef{sa@gsdevice@#1}{#2}%
}
\@namedef{sa@gsdevice@.jpg}{jpeg}%
\@namedef{sa@gsdevice@.png}{png16m}%
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.cls/convert}{command}
%    \begin{macrocode}
\sa@convertoption{command}{%
    \def\sa@convert@command{#1}%
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.cls/convert}{pdf2svg}
%    \begin{macrocode}
\sa@convertoption{pdf2svg}[]{%
    \def\sa@convert@command{pdf2svg \infile\space\outfile}%
    \sa@convertvar{outext}{.svg}
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.cls/convert}{imagemagick}
%    \begin{macrocode}
\sa@convertoption{imagemagick}[]{%
    \def\sa@convert@command{\convertexe\space -density \density\space -units PixelsPerInch \infile\space \ifx\size\empty\else -resize \size\fi\space -quality 90 \outfile}%
    \let\sa@convert@pageoffset\m@ne
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.cls/convert}{ghostscript}
%    \begin{macrocode}
\sa@convertoption{ghostscript}[]{%
    \def\sa@convert@command{\gsexe\space -dSAFER -dBATCH -dNOPAUSE -sDEVICE=\gsdevice\space -r\density\space -sOutputFile=\outfile\space \infile}%
    \let\sa@convert@pageoffset\z@
}
%    \end{macrocode}
% \end{key}
%
%    \begin{macrocode}
\sa@convertvar{latexoptions}{ -shell-escape }
\sa@convertvar{subjobname}{\jobname}
\sa@convertvar{mainfile}{\jobname}
\sa@convertvar{quote}{}
\let\sa@convert@quote\relax
\sa@convertvar{size}{}
\sa@convertvar{inname}{\subjobname}
\sa@convertvar{infile}{\inname\inext}
\sa@convertvar{outext}{.png}
\sa@convertvar{outname}{\inname}
\sa@convertvar{outfile}{\outname\ifsa@multi\sa@multi@pagemark\fi\outext}
\def\sa@multi@pagemark{-\percent0d}%
\sa@convertvar{density}{300}
\sa@convertvar{gsdevice}{%
    \expandafter\ifx\csname sa@gsdevice@\outext\endcsname\relax
        \expandafter\@gobble\outext
    \else
        \csname sa@gsdevice@\outext\endcsname
    \fi
}
\ifluatex
    \sa@convertvar{latex}{lualatex}
    \sa@convertvar{inext}{.pdf}
    \sa@convertvar{precommand}{}
    \setkeys{standalone.cls/convert}{imagemagick}
\else
\ifpdf
    \sa@convertvar{latex}{pdflatex}
    \sa@convertvar{inext}{.pdf}
    \sa@convertvar{precommand}{}
    \setkeys{standalone.cls/convert}{imagemagick}
\else
\ifxetex
    \sa@convertvar{latex}{xelatex}
    \sa@convertvar{inext}{.pdf}
    \sa@convertvar{precommand}{}
    \setkeys{standalone.cls/convert}{imagemagick}
\else
    \sa@convertvar{latex}{latex}
    \sa@convertvar{inext}{.ps}
    \sa@convertvar{precommand}{dvips \subjobname.dvi}
    \setkeys{standalone.cls/convert}{ghostscript}
\fi\fi\fi
%    \end{macrocode}
%
% Test for windows to avoid using the 'convert' executable there.
% It is also the FAT-to-NTFS conversion tool!
%    \begin{macrocode}
\begingroup
\ifluatex
  \csname @tempswa\directlua{
      if os.type == "windows" then
        tex.sprint("true")
      else
        tex.sprint("false")
      end
    }\endcsname
\else
    \IfFileExists{/dev/null}{\@tempswafalse}{\@tempswatrue}%
\fi
\if@tempswa
    \endgroup
    \sa@convertvar{convertexe}{imgconvert}
    \sa@convertvar{gsexe}{gswin32c}
\else
    \endgroup
    \sa@convertvar{convertexe}{convert}
    \sa@convertvar{gsexe}{gs}
\fi
%    \end{macrocode}
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{General macros}
%
% \begin{macro}{\standaloneenv}[1]{comma separated list if environment names}
% Loops over all environment names and calls \Macro\@standaloneenv on them.
%    \begin{macrocode}
\newcommand*\standaloneenv[1]{%
    \begingroup
    \edef\@tempa{\endgroup\noexpand\@for\noexpand\@tempa:=\zap@space#1 \@empty}%
    \@tempa\do{\expandafter\@standaloneenv\expandafter{\@tempa}}%
    \setkeys{standalone.cls}{multi}%
}
\@onlypreamble\standaloneenv
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\standaloneconfig}
% User level configuration macro.
%    \begin{macrocode}
\newcommand*{\standaloneconfig}{\setkeys{standalone.cls}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@standaloneenv}
% Default no-op version.
%    \begin{macrocode}
\let\@standaloneenv\@gobble
%    \end{macrocode}
% \end{macro}
%
% Counter to indicate if currently inside a standaloneenv.
%    \begin{macrocode}
\newcount\sa@internal
%    \end{macrocode}
%
% Counter for total number of pages/\opt{multi} environments.
%    \begin{macrocode}
\newcounter{sapage}
%    \end{macrocode}
%
% \begin{environment}{standalone}
% The \env{standalone} environment is defined by default to be without effect.
% The \cs{endstandalone} macro is set to |\relax|, so a redefinition with
% \cs{renewenvironment} in the configuration file is possible and also can later be detected.
%    \begin{macrocode}
\let\standalone\empty
\let\endstandalone\relax
%    \end{macrocode}
% \end{environment}
%
%
% \begin{macro}{\sa@width}
% Default value for \env{varwidth} width.
%    \begin{macrocode}
\def\sa@width{\linewidth}
%    \end{macrocode}
% \end{macro}
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{Load config file, process options and load class}
%
% Load configuration file.
%    \begin{macrocode}
\InputIfFileExists{standalone.cfg}{}{}
%    \end{macrocode}
%
% Process options as normal keys. Only unknown keys are set as global options.
%    \begin{macrocode}
\begingroup
\def\@tempa{\endgroup\setkeys*{standalone.cls}}
\expandafter\expandafter\expandafter\@tempa
\expandafter\expandafter\expandafter{\csname opt@standalone.cls\endcsname}
\let\@classoptionslist\XKV@rm
%    \end{macrocode}
%
% Disable keys which are only allowed as class options.
% The \opt{multi} option is still allowed inside the preamble.
%    \begin{macrocode}
\disable@keys{standalone.cls}{crop,preview,class,beamer,ignorerest}
\AtBeginDocument{%
    \disable@keys{standalone.cls}{multi}%
}
%    \end{macrocode}
%
%
% Loads the class given by the |class| option with the rest of the options.
%    \begin{macrocode}
\expandafter\expandafter\expandafter\LoadClass
\expandafter\expandafter\expandafter[%
\expandafter\@classoptionslist
\expandafter]\expandafter{\sa@class}
%    \end{macrocode}
%
%
%
% \subsubsection{Ignorerest Option}
%
% \begin{macro}{\sa@startignore}
% Starts to box everything if \opt{ignorerest} option is set to true.
% Afterwards the box is discarded so that the content is ignored.
%    \begin{macrocode}
\ifsa@ignorerest
    \def\sa@startignore{\sa@boxit}
\else
    \let\sa@startignore\relax
\fi
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sa@stopignore}
% Closes the ignore box if \opt{ignorerest} option is set to true.
%    \begin{macrocode}
\ifsa@ignorerest
    \def\sa@stopignore{\endsa@boxit}
\else
    \let\sa@stopignore\relax
\fi
%    \end{macrocode}
% \end{macro}
%
%
% \subsubsection{Multido Option}
%
%    \begin{macrocode}
\ifsa@multido
\RequirePackage{multido}
%    \end{macrocode}
%
% \begin{macro}{\multido@}
% Redefine the internal macro of \Macro\multido and friends to produce
% a seperate page for every iteration. This only affects the first level of \Macro\multido,
% i.e. nesting is supported. The definition is compatible with the \opt{ignorerest} option.
%    \begin{macrocode}
\let\sa@orig@multido@\multido@
\renewcommand{\multido@}[6]{%
  \sa@stopignore
  \sa@orig@multido@{#1}{#2}{#3}{#4}{#5}{%
    \sa@startignore
    \begin{samultido}%
      \let\multido@\sa@orig@multido@
      #6%
    \end{samultido}%
    \sa@stopignore
  }%
  \sa@startignore
}
%    \end{macrocode}
% \end{macro}
%
%    \begin{macrocode}
\fi
%    \end{macrocode}
%
% Load Lua\LaTeX{} compatibility packages.
%    \begin{macrocode}
\ifluatex
\RequirePackage{luatex85}
\RequirePackage{pdftexcmds}
\fi
%    \end{macrocode}
%
% Set correct quoting character for conversion option if none was set.
%    \begin{macrocode}
\ifsa@convert
\ifx\sa@convert@quote\relax
\begingroup
\@tempswafalse
%    \end{macrocode}
% If \Macro\pdftexbanner is not defined (XeLaTeX) the distribution can not
% be determined and double quotes are set to ensure proper operation under MiKTeX.
%    \begin{macrocode}
\expandafter\ifx\csname pdftexbanner\endcsname\relax
    \@tempswatrue
\else
%    \end{macrocode}
% Test if there is a `|MiKTeX|' in \Macro\pdftexbanner.
%    \begin{macrocode}
\def\MiKTeX{MiKTeX}
\@onelevel@sanitize\MiKTeX
\expandafter\def\expandafter\testmiktex\expandafter#\expandafter1\MiKTeX#2\relax{%
        \ifx\empty#2\empty
             \@tempswafalse
        \else
             \@tempswatrue
        \fi
}
\expandafter\expandafter
\expandafter\testmiktex\expandafter\pdftexbanner\MiKTeX\relax\relax

\fi
\expandafter
\endgroup
\if@tempswa
\def\sa@convert@quote{"}
\else
\def\sa@convert@quote{'}
\fi
\fi
\fi
%    \end{macrocode}
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{Varwidth Option}
%
%    \begin{macrocode}
\ifsa@varwidth
    \RequirePackage{varwidth}
\fi
%    \end{macrocode}
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{TikZ Option}
%
%    \begin{macrocode}
\ifsa@tikz
    \RequirePackage{tikz}
\fi
%    \end{macrocode}
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{pstricks Option}
%
%    \begin{macrocode}
\ifsa@pstricks
    \RequirePackage{pstricks}
\fi
%    \end{macrocode}
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{Preview Option}
%
% The \env{standalone} environment is redefined to use the |preview| environment as
% long it was not redefined in the configuration file.
%    \begin{macrocode}
\ifsa@preview
%    \end{macrocode}
%
% Note: The used options are in the config file.
%    \begin{macrocode}
\RequirePackage{preview}
\ifsa@multi\else
    \@ifundefined{endstandalone}{%
        \renewenvironment{standalone}
            {\preview\sa@varwidth}
            {\sa@endvarwidth\endpreview}
    }{}% TODO: Add info message?
\fi
%    \end{macrocode}
%
% Set Border
%    \begin{macrocode}
\def\PreviewBbAdjust{-\sa@border@left\space -\sa@border@bottom\space \sa@border@right\space \sa@border@top}%
%    \end{macrocode}
%
% \begin{macro}{\@standaloneenv}
% Preview version. Wrappes a \env{preview} environment around the original environment.
% Also adds the \env{varwidth} macros, which can be empty.
% These \env{varwidth} macros are the reason why \Macro\PreviewEnvironment is not used directly.
%    \begin{macrocode}
\def\@standaloneenv#1{%
    \expandafter\ifx\csname sa@orig@#1\endcsname\relax
        \expandafter\let\csname sa@orig@#1\expandafter\endcsname\csname #1\endcsname
        \expandafter\let\csname sa@orig@end#1\expandafter\endcsname\csname end#1\endcsname
    \fi
    \expandafter\def\csname #1\endcsname{%
        \ifnum\sa@internal=0
            \addtocounter{sapage}\@ne
            \preview
            \sa@varwidth
        \fi
        \advance\sa@internal\@ne
        \csname sa@orig@#1\endcsname
    }%
    \expandafter\def\csname end#1\endcsname{%
        \csname sa@orig@end#1\endcsname
        \advance\sa@internal\m@ne
        \ifnum\sa@internal=0
            \sa@endvarwidth
            \endpreview
        \fi
    }%
}%
%    \end{macrocode}
% \end{macro}
%
%    \begin{macrocode}
\fi
%    \end{macrocode}
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{Crop Option}
%
%    \begin{macrocode}
\ifsa@crop
%    \end{macrocode}
%
% Box register to save the content.
% \begin{macro}{\sa@box}
%    \begin{macrocode}
\newbox\sa@box
%    \end{macrocode}
% \end{macro}
%
% Set all normal page margins etc. to zero.
%    \begin{macrocode}
\pagestyle{empty}
\hoffset=-72.27pt
\voffset=-72.27pt
\topmargin=0pt
\headheight=0pt
\headsep=0pt
\marginparsep=0pt
\marginparwidth=0pt
\footskip=0pt
\marginparpush=0pt
\oddsidemargin=0pt
\evensidemargin=0pt
\topskip=0pt
\textheight=\maxdimen
%    \end{macrocode}
%
% \begin{macro}{\sa@boxit}
%    \begin{macrocode}
\def\sa@boxit{%
    \setbox\sa@box\hbox\bgroup\color@setgroup\sa@varwidth
}%
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\endsa@boxit}
%    \begin{macrocode}
\def\endsa@boxit{%
    \sa@endvarwidth\color@endgroup\egroup
}%
%    \end{macrocode}
% \end{macro}
%
%
%
% \begin{environment}{standalone}
% Redefine the \env{standalone} environment to box the content if \opt{multi} is off,
% in order to use the whole content as single page. If \opt{multi} and \opt{ignorerest} are on
% the content is also boxed, but later discarded. If only \opt{multi} is on the environment
% doesn't have to do anything.
%    \begin{macrocode}
\renewenvironment{standalone}{%
    \ifsa@multi
        \sa@startignore
    \else
        \sa@boxit
    \fi
}{%
    \ifsa@multi
        \sa@stopignore
    \else
        \endsa@boxit
        \sa@handlebox
    \fi
}
%    \end{macrocode}
% \end{environment}
%
%
% \begin{macro}{\@standaloneenv}
% If the \opt{ignorerest} option is used all content outside of \Macro\standaloneenv\relax-ironments is
% boxed and discarded. This requires such environments to close the box first and reopen it afterwards.
%    \begin{macrocode}
\ifsa@multi\else
    \sa@ignorerestfalse
\fi
\ifsa@ignorerest
    \def\@standaloneenv#1{%
        \expandafter\ifx\csname sa@orig@#1\endcsname\relax
            \expandafter\let\csname sa@orig@#1\expandafter\endcsname\csname #1\endcsname
            \expandafter\let\csname sa@orig@end#1\expandafter\endcsname\csname end#1\endcsname
        \fi
        \expandafter\def\csname #1\endcsname{%
            \ifnum\sa@internal=0
                \addtocounter{sapage}\@ne
                \edef\@tempa{\endgroup
                    \noexpand\endsa@boxit
                    \begingroup
                    \def\noexpand\@currenvir{\@currenvir}%
                    \def\noexpand\@currenvline{\@currenvline}%
                }%
                \@tempa
                \sa@boxit
            \fi
            \advance\sa@internal\@ne
            \csname sa@orig@#1\endcsname
        }%
        \expandafter\def\csname end#1\endcsname{%
            \csname sa@orig@end#1\endcsname
            \advance\sa@internal\m@ne
            \ifnum\sa@internal=0
                \endsa@boxit
                \sa@handlebox
                \aftergroup\sa@boxit
            \fi
        }%
    }%
\else
    \def\@standaloneenv#1{%
        \expandafter\ifx\csname sa@orig@#1\endcsname\relax
            \expandafter\let\csname sa@orig@#1\expandafter\endcsname\csname #1\endcsname
            \expandafter\let\csname sa@orig@end#1\expandafter\endcsname\csname end#1\endcsname
        \fi
        \expandafter\def\csname #1\endcsname{%
            \ifnum\sa@internal=0
                \addtocounter{sapage}\@ne
                \sa@boxit
            \fi
            \advance\sa@internal\@ne
            \csname sa@orig@#1\endcsname
        }%
        \expandafter\def\csname end#1\endcsname{%
            \csname sa@orig@end#1\endcsname
            \advance\sa@internal\m@ne
            \ifnum\sa@internal=0
                \endsa@boxit
                \sa@handlebox
            \fi
        }%
    }%
\fi
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sa@handlebox}
% Adds the border as part of the box dimensions and places the result
% using the output format dependent \Macro\sa@placebox macro.
%    \begin{macrocode}
\def\sa@handlebox{%
    \ifcase
        0%
        \ifsa@ignoreempty
            \ifdim\wd\sa@box=\z@
            \ifdim\ht\sa@box=\z@
            \ifdim\dp\sa@box=\z@
                1%
            \fi\fi\fi
        \fi
    \relax
    \sbox\sa@box{%
%    \end{macrocode}
% add left border
%    \begin{macrocode}
        \hskip\sa@border@left
%    \end{macrocode}
% add top border
%    \begin{macrocode}
        \@tempdima=\ht\sa@box
        \advance\@tempdima\sa@border@top\relax
        \ht\sa@box=\@tempdima
%    \end{macrocode}
% add bottom border
%    \begin{macrocode}
        \@tempdima=\dp\sa@box
        \advance\@tempdima\sa@border@bottom\relax
        \dp\sa@box=\@tempdima
%    \end{macrocode}
% Remove all depth, so that height=totalheight
%    \begin{macrocode}
        \raise\dp\sa@box
            \box\sa@box
%    \end{macrocode}
% add right border
%    \begin{macrocode}
        \hskip\sa@border@right
    }%
    \sa@placebox
    \fi
}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sa@placebox}
% Define output dependent macro to place the content box together
% with the required resizing of the page.
%
% PDFLaTeX, LuaLaTeX and XeLaTeX can use all the same definition.
% DVI/PS Output requires a different definition.
%    \begin{macrocode}
\ifcase0%
    \ifpdf\else\ifluatex\else\ifxetex\else 1\fi\fi\fi
  \relax
    \def\sa@placebox{%
        \newpage
        \ifluatex
          \ifnum\luatexversion<85
            % LuaLaTeX < 0.85 does define the PDF-specific globals.
            \global\pdfpagewidth=\wd\sa@box
            \global\pdfpageheight=\ht\sa@box
          \else
            % LuaLaTeX >= 0.85 doesn't define the PDF-specific globals.
            \global\pagewidth=\wd\sa@box
            \global\pageheight=\ht\sa@box
          \fi
        \else
          % Not LuaLaTeX at all, so still need this.
          \global\pdfpagewidth=\wd\sa@box
          \global\pdfpageheight=\ht\sa@box
        \fi
        \global\paperwidth=\wd\sa@box
        \global\paperheight=\ht\sa@box
        \global\hsize=\wd\sa@box
        \global\vsize=\ht\sa@box
        \global\@colht=\ht\sa@box
        \global\@colroom=\ht\sa@box
        \noindent\usebox\sa@box
        \newpage
    }
  \else
    \def\sa@placebox{%
        \global\paperwidth=\wd\sa@box
        \global\paperheight=\ht\sa@box
        \global\@colht=\maxdimen
        \global\@colroom=\maxdimen
        \global\hsize=\maxdimen
        \global\vsize=\maxdimen
        \sa@papersize
        \ifsa@multi
        \begingroup
        \@tempdima0.99626\paperwidth
        \@tempdimb0.99626\paperheight
        \edef\@tempc{\strip@pt\@tempdima}%
        \edef\@tempd{\strip@pt\@tempdimb}%
        \advance\@tempdima by .998pt
        \advance\@tempdimb by .998pt
        \def\strip@float##1.##2\relax{##1}%
        \edef\@tempa{\expandafter\strip@float\the\@tempdima\relax}%
        \edef\@tempb{\expandafter\strip@float\the\@tempdimb\relax}%
        \special{ps::%
            \@percentchar\@percentchar PageBoundingBox: 0 0 \@tempa\space\@tempb^^J%
            \@percentchar\@percentchar HiResPageBoundingBox: 0 0 \@tempc\space\@tempd^^J%
            \@percentchar\@percentchar BeginPageSetup^^J%
            << /PageSize [\@tempc\space\@tempd]
            >> setpagedevice^^J%<<
            0 0 bop^^J%
            \@percentchar\@percentchar EndPageSetup}%
        \endgroup
        \fi
        \topskip=0pt
        \noindent\sa@ps@content
        \newpage
    }
%    \end{macrocode}
% \end{macro}
%
% Other macros required for PostScript output.
% They will redefine themselves to act differently for the very first page than for the remaining ones.
% \begin{macro}{\sa@ps@content}
%
% Simply place the box of the first page. Further pages need to be vertically adjusted because the
% reference point is still for the size of the first page.
%    \begin{macrocode}
\def\sa@ps@content{%
    \noindent\usebox\sa@box
    \global\def\sa@ps@content{%
        \@tempdima\sa@yoffset
        \advance\@tempdima-\topskip
        \dp\sa@box\z@
        \ht\sa@box\z@
        \noindent\lower\@tempdima\copy\sa@box
    }%
}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sa@papersize}
% Declare official papersize as the size of the first page.
% Store offset and disable this macro for all further pages.
%    \begin{macrocode}
\def\sa@papersize{%
    \global\let\sa@papersize\relax
    \global\sa@yoffset=\paperheight
    \global\setbox\@begindvibox\vbox{%
        \special{papersize=\the\paperwidth,\the\paperheight}%
        \special{ps::%
            \@percentchar\@percentchar HiResBoundingBox: 0 0 \the\paperwidth\space\the\paperheight^^J%
        }%
        \unvbox\@begindvibox
        \special{papersize=\the\paperwidth,\the\paperheight}%
    }%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@yoffset}
% Offset required to vertical adjust all further pages according to the first page.
%    \begin{macrocode}
\newlength\sa@yoffset
%    \end{macrocode}
% \end{macro}
%
% End of 'latex' clause
%    \begin{macrocode}
\fi
%    \end{macrocode}
%
% End of \opt{crop} option code.
%    \begin{macrocode}
\fi
%    \end{macrocode}
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{Beamer code}
%
%    \begin{macrocode}
\ifstandalonebeamer
%    \end{macrocode}
% \begin{environment}{standaloneframe}
% Front-end for the beamer |frame| environment. Parses all arguments
% the same way and calls it with an added option.
%    \begin{macrocode}
\newenvironment{standaloneframe}{%
  \@ifnextchar<%
    {\@standaloneframe}%
    {\@@standaloneframe{}}%
}{\end{frame}}%
\def\@standaloneframe<#1>{%
    \@@standaloneframe{<#1>}%
}
\def\@@standaloneframe#1{%
  \@ifnextchar[%]
    {\@@@standaloneframe{#1}}%
    {\@@@standaloneframe{#1}[]}%
}%
\def\@@@standaloneframe#1[{%
  \@ifnextchar<%
    {\@@@@standaloneframe{#1}[}%
    {\@@@@@@standaloneframe{#1}[}%
}%
\def\@@@@standaloneframe#1[#2]{%
  \@ifnextchar[%]
    {\@@@@@standaloneframe{#1}{#2}}%
    {\begin{frame}#1[#2][environment=standaloneframe]}%
}%
\def\@@@@@standaloneframe#1#2[#3]{%
    \begin{frame}#1[#2][environment=standaloneframe,#3]%
}%
\def\@@@@@@standaloneframe#1[#2]{%
    \begin{frame}#1[environment=standaloneframe,#2]%
}%
%    \end{macrocode}
% \end{environment}
%    \begin{macrocode}
\fi
%    \end{macrocode}
%
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{Conversion code}
%    \begin{macrocode}
\expandafter\ifx\csname sa@internal@run\endcsname\relax\else
    \AtEndDocument{%
        \immediate\write\@mainaux{\noexpand\@gobbletwo\noexpand\sa@multi@setnumpages{\arabic{sapage}}}%
    }
    \sa@convertfalse
\fi
\ifsa@convert
%    \end{macrocode}
%
%    \begin{macrocode}
\def\sa@convert@stop{\csname fi\endcsname\stop}%
\begingroup
\let\on@line\@gobble
%    \end{macrocode}
%
% \begin{macro}{\sa@convert}[1]{error message on failure}
% Conversion macro.
%    \begin{macrocode}
\def\sa@convert#1{%
    \IfFileExists{\outfile}{%
        \edef\filemodbefore{\csname pdf\ifluatex @\fi filemoddate\endcsname{\outfile}}%
    }{%
    \IfFileExists{\outname\outext}{%
        \edef\filemodbefore{\csname pdf\ifluatex @\fi filemoddate\endcsname{\outname\outext}}%
    }{%
    \IfFileExists{\outname-0\outext}{%
        \edef\filemodbefore{\csname pdf\ifluatex @\fi filemoddate\endcsname{\outname-0\outext}}%
    }{%
    \IfFileExists{\outname-1\outext}{%
        \edef\filemodbefore{\csname pdf\ifluatex @\fi filemoddate\endcsname{\outname-1\outext}}%
    }{%
        \def\filemodbefore{}%
    }}}}%
    \edef\@tempa{\jobname}%
    \edef\@tempb{\sa@convert@subjobname}%
    \@onelevel@sanitize\@tempa
    \@onelevel@sanitize\@tempb
    \@tempswafalse
    \ifx\@tempa\@tempb
        \@tempswatrue
        \edef\infile@filemodbefore{\csname pdf\ifluatex @\fi filemoddate\endcsname{\infile}}%
    \else
        \global\let\sa@convert@stop\relax
    \fi
    \ShellEscape{\sa@convert@latex\space\sa@convert@latexoptions\space
        -jobname \sa@convert@quote\sa@convert@subjobname\sa@convert@quote\space
        \sa@convert@quote\string\expandafter\string\def\string\csname\space
        sa@internal@run\string\endcsname{1}\string\input{\sa@convert@mainfile}\sa@convert@quote}%
%
    \def\sa@multi@numpages{0}%
    \begingroup
    \IfFileExists{\sa@convert@subjobname.aux}{\@tempswatrue}{\@tempswafalse}%
    \if@tempswa
      \newread\sa@read
      \def\@tempa##1\sa@multi@setnumpages##2##3\@nnil{%
        \def\@tempc{##2}%
        \ifx\@tempc\@nnil\else
          \gdef\sa@multi@numpages{##2}%
        \fi
      }%
      \endlinechar=\m@ne
      \immediate\openin\sa@read=\sa@convert@subjobname.aux\relax
      \loop\unless\ifeof\sa@read
        \read\sa@read to\@tempb
        \expandafter\@tempa\@tempb\sa@multi@setnumpages\@nil\@empty\@nnil
      \repeat
      \immediate\closein\sa@read
    \fi
    \endgroup
%
    \@tempcnta\sa@multi@numpages\relax
    \advance\@tempcnta\sa@convert@pageoffset\relax
    \ifnum\@tempcnta=\z@
        \def\sa@multi@pagemark{}%
        \edef\sa@lastoutfile{\outfile}%
    \else
        \begingroup
        \def\sa@multi@pagemark{-\the\@tempcnta}%
        \xdef\sa@lastoutfile{\outfile}%
        \endgroup
        \@tempcntb\z@
        \loop\ifnum\@tempcnta>0
            \advance\@tempcntb\@ne
            \divide\@tempcnta by 10\relax
        \repeat
        \edef\sa@multi@pagemark{-\percent0\the\@tempcntb d}%
    \fi
%
    \if@tempswa
        \edef\infile@filemodafter{\csname pdf\ifluatex @\fi filemoddate\endcsname{\infile}}%
        \ifx\infile@filemodbefore\infile@filemodafter
            \global\let\sa@convert@stop\relax
        \fi
    \fi
%    \end{macrocode}
%    \begin{macrocode}
    \edef\sa@convert@precommand{\sa@convert@precommand}%
    \ifx\sa@convert@precommand\@empty\else
\message{Executing precommand:^^J\sa@convert@precommand^^J^^J}%
        \ShellEscape{\sa@convert@precommand}%
    \fi
\message{Executing command:^^J\sa@convert@command^^J^^J}%
    \ShellEscape{\sa@convert@command}%
    \@tempswafalse
    \IfFileExists{\sa@lastoutfile}{%
        \edef\filemodafter{\csname pdf\ifluatex @\fi filemoddate\endcsname{\sa@lastoutfile}}%
        \ifx\filemodbefore\filemodafter
            \expandafter\ifx\csname pdf\ifluatex @\fi filemoddate\endcsname\relax\else
                \sa@convert@failuremsg{standalone}{#1}{}%
            \fi
        \else
            \typeout{Class standalone:^^JOutput written on \sa@lastoutfile.}%
        \fi
    }{%
        \sa@convert@failuremsg{standalone}{#1}{}%
    }%
}
%    \end{macrocode}
% \end{macro}
%
% Provide the internal macros to the user level.
%    \begin{macrocode}
\let\subjobname\sa@convert@subjobname
\let\mainfile\sa@convert@mainfile
\let\infile\sa@convert@infile
\let\inext\sa@convert@inext
\let\inname\sa@convert@inname
\let\gsdevice\sa@convert@gsdevice
\let\convertexe\sa@convert@convertexe
\let\gsexe\sa@convert@gsexe
\let\density\sa@convert@density
\let\size\sa@convert@size
\let\outext\sa@convert@outext
\let\outname\sa@convert@outname
\let\outfile\sa@convert@outfile
\let\percent\@percentchar
\let\quote\sa@convert@quote
%    \end{macrocode}
%
%
%    \begin{macrocode}
\edef\sa@shellescape{%
    \ifluatex
      \directlua{tex.write(status.shell_escape or 2)}%
    \else\ifxetex
      \the\shellescape
    \else
    \expandafter\ifx\csname pdfshellescape\endcsname\relax
      0%
    \else
      \the\pdfshellescape
    \fi\fi\fi
}%
\ifcase\sa@shellescape\relax% 0
    \sa@convert@failuremsg
        {standalone}{Shell escape disabled! Cannot convert file '\infile'.}{}%
    \global\let\sa@convert@stop\relax
\or% 1
    \sa@convert{Conversion unsuccessful!\MessageBreak
                There might be something wrong with your\MessageBreak
                conversation software or the file permissions!}%
\else% 2 or 3
    \sa@convert{Conversion failed! Please ensure that shell escape\MessageBreak
                is enabled (e.g. use '-shell-escape').}%
\fi
\endgroup
%    \end{macrocode}
%    \begin{macrocode}
\expandafter\sa@convert@stop
\fi
%    \end{macrocode}
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{Document Environment in Sub-Files}
% This is done at the very end so that all used packages are already loaded.
% Just in case these try also to redefine the \env{document} environment.
%
% \begin{environment}{document}
% Adds own `after begin document' and `before end document` hooks.
%    \begin{macrocode}
\begingroup
\toks@\expandafter{%
    \document
    \sa@cls@afterbegindocument
}
\xdef\document{\the\toks@}%
\toks@\expandafter{%
    \expandafter
    \sa@cls@beforeenddocument
    \enddocument
}
\xdef\enddocument{\the\toks@}%
\endgroup
%    \end{macrocode}
% \end{environment}
%
%
% \begin{macro}{\sa@cls@afterbegindocument}
% \begin{macro}{\sa@cls@beforeenddocument}
% Hooks which add the \env{standalone} environment. Surrounding spaces
% are removed. This hooks are used (instead of calling the content directly in the above macros)
% to add the possibility to fine tune this later, e.g.\ in the configuration file.
%    \begin{macrocode}
\def\sa@cls@afterbegindocument{\standalone\ignorespaces}
\def\sa@cls@beforeenddocument{\ifhmode\unskip\fi\endstandalone}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \iffalse
%</standalone.cls>
% \fi
%
% \iffalse
%<*standalone.sty>
% \fi
%
% \iffalse
%<!COPYRIGHT>
% \fi
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsection{The Package File}
%
%    \begin{macrocode}
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{standalone}[%
%<!DATE>
%<!VERSION>
%<*DRIVER>
    2099/01/01 develop
%</DRIVER>
    Package to include TeX sub-files with preambles]
%    \end{macrocode}
%
% The package file is to be loaded by a main document which includes \cls{standalone} sub-files.
% It is also loaded by the \cls{standalone} class to share code. The class then redefines certain macros.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{If-Switches}
%
% \begin{macro}{\ifstandalone}
% Declare |standalone| if-switch and set it to false. The class will set it to true.
% The |\csname| trickery is used to avoid issues if the switch was already defined.
%    \begin{macrocode}
\@ifundefined{ifstandalone}{%
    \expandafter\newif\csname ifstandalone\endcsname
    \standalonefalse
}{}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifstandalonebeamer}
% \changes{v0.2}{2010/03/23}{New macro}
% Make sure that |standalonebeamer| if-switch is defined and set it to false.
% If the class was loaded beforehand with the |beamer| option it is already defined as true.
% The |\csname| trickery is used to avoid issues if the switch was already defined.
%    \begin{macrocode}
\@ifundefined{ifstandalonebeamer}{%
    \expandafter\newif\csname ifstandalonebeamer\endcsname
    \standalonebeamerfalse
}{}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\onlyifstandalone}
% \changes{v0.3}{2010/03/26}{New macro}
% Macro version of |\ifstandalone|. The |{ }| around the argument protects the content from the package etc. scanners.
% Only defined if not already defined by the class, in the case of a |standalone| file included other |standalone| files.
%    \begin{macrocode}
\@ifundefined{onlyifstandalone}{%
    \let\onlyifstandalone\@gobble
}{}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\IfStandalone}[2]{true clause}{false clause}
% Macro version of |\ifstandalone .. \else .. \fi|. The |{ }| around the argument protects the content from the package etc. scanners.
%    \begin{macrocode}
\@ifundefined{IfStandalone}{%
    \let\IfStandalone\@secondoftwo
}{}
%    \end{macrocode}
% \end{macro}
%
% Define if-switches for TeX formats.
% This loads the corresponding packages if available, but falls back to some own code if they are not installed.
%    \begin{macrocode}
\expandafter\ifx\csname ShellEscape\endcsname\relax
    \IfFileExists{shellesc.sty}{
        \RequirePackage{shellesc}
        \@ifpackagelater{shellesc}{2016/04/29}{
        }{
            \protected\def\ShellEscape{\immediate\write18 }
        }
    }{
        \protected\def\ShellEscape{\immediate\write18 }
    }
\fi
\expandafter\ifx\csname ifluatex\endcsname\relax
    \IfFileExists{ifluatex.sty}{
        \RequirePackage{ifluatex}
    }{
        \begingroup
        \expandafter\ifx\csname directlua\endcsname\relax
            \endgroup
            \global\expandafter\let\csname ifluatex\expandafter\endcsname\csname iffalse\endcsname
        \else
            \endgroup
            \global\expandafter\let\csname ifluatex\expandafter\endcsname\csname iftrue\endcsname
        \fi
    }
\fi
\expandafter\ifx\csname ifpdf\endcsname\relax
    \IfFileExists{ifpdf.sty}{
        \RequirePackage{ifpdf}
    }{
        \begingroup
        \expandafter\ifx\csname pdfoutput\endcsname\relax
            \endgroup
            \global\expandafter\let\csname ifpdf\expandafter\endcsname\csname iffalse\endcsname
        \else
            \endgroup
            \ifnum\pdfoutput<1
                \global\expandafter\let\csname ifpdf\expandafter\endcsname\csname iffalse\endcsname
            \else
                \global\expandafter\let\csname ifpdf\expandafter\endcsname\csname iftrue\endcsname
            \fi
        \fi
    }
\fi
\expandafter\ifx\csname ifxetex\endcsname\relax
    \IfFileExists{ifxetex.sty}{
        \RequirePackage{ifxetex}
    }{
        \begingroup
        \expandafter\ifx\csname XeTeXrevision\endcsname\relax
            \endgroup
            \global\expandafter\let\csname ifxetex\expandafter\endcsname\csname iffalse\endcsname
        \else
            \endgroup
            \global\expandafter\let\csname ifxetex\expandafter\endcsname\csname iftrue\endcsname
        \fi
    }
\fi
%    \end{macrocode}
%
%
% \begin{macro}{\ifsa@subpreambles}
% \begin{macro}{\ifsa@sortsubpreambles}
% \begin{macro}{\ifsa@printsubpreambles}
% \begin{macro}{\ifsa@group}
% \begin{macro}{\ifsa@obeyclassoptions}
% \begin{macro}{\ifsa@comments}
% The if-switches for the options.
%    \begin{macrocode}
\newif\ifsa@subpreambles
\newif\ifsa@sortsubpreambles
\newif\ifsa@printsubpreambles
\newif\ifsa@group
\newif\ifsa@obeyclassoptions
\newif\ifsa@multi
\newif\ifsa@tikz
\newif\ifsa@varwidth
\newif\ifsa@comments
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{Options}
%    \begin{macrocode}
\RequirePackage{xkeyval}
%    \end{macrocode}
%
% \begin{macro}{\sa@pkgoption}
% Wrapper macro to define options.
%    \begin{macrocode}
\def\sa@pkgoption{%
    \define@key{standalone.sty}%
}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sa@boolean}[2]{name of if-switch}{`true' or `false'}
% Sets if-switches.
%    \begin{macrocode}
\def\sa@boolean#1#2{%
    \sa@boolorvalue{#1}{#2}%
        {\ClassError{standalone}{Invalid value '#2' for boolean key '#1'}{}}%
}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sa@boolorvalue}[2]{name of if-switch}{`true', `false' or a value}{code to be executed if it is a value.}
% Sets if-switches.
%    \begin{macrocode}
\def\sa@boolorvalue#1#2{%
    \begingroup
    \edef\@tempa{#2}%
    \def\@tempb{true}%
    \ifx\@tempa\@tempb
        \endgroup
        \csname sa@#1true\endcsname
        \expandafter\@gobble
    \else
    \def\@tempb{false}%
    \ifx\@tempa\@tempb
        \endgroup
        \csname sa@#1false\endcsname
        \expandafter\expandafter
        \expandafter\@gobble
    \else
        \endgroup
        \expandafter\expandafter
        \expandafter\@firstofone
    \fi\fi
}
%    \end{macrocode}
% \end{macro}
%
% \begin{key}{standalone.sty}{sort}
%    \begin{macrocode}
\sa@pkgoption{sort}[true]{%
    \sa@boolean{sortsubpreambles}{#1}%
    \ifsa@sortsubpreambles
        \sa@subpreamblestrue
    \fi
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.sty}{print}
%    \begin{macrocode}
\sa@pkgoption{print}[true]{%
    \sa@boolean{printsubpreambles}{#1}%
    \ifsa@printsubpreambles
        \sa@subpreamblestrue
    \fi
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.sty}{subpreambles}
%    \begin{macrocode}
\sa@pkgoption{subpreambles}[true]{%
    \sa@boolean{subpreambles}{#1}%
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.sty}{group}
%    \begin{macrocode}
\sa@pkgoption{group}[true]{%
    \sa@boolean{group}{#1}%
}
\sa@grouptrue
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.sty}{comments}
%    \begin{macrocode}
\sa@pkgoption{comments}[true]{%
    \sa@boolean{comments}{#1}%
    \ifsa@comments
        \def\sa@percent{\@makeother\%}%
    \else
        \def\sa@percent{\catcode`\%=14\relax}%
    \fi
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.sty}{nocomments}
%    \begin{macrocode}
\sa@pkgoption{nocomments}[]{%
    \begingroup
        \def\@tempa{#1}%
        \ifx\@tempa\@empty\else
            \PackageWarning{standalone}{Unwanted value of 'nocomments' was ignored}{}A
        \fi
    \endgroup
    \setkeys{standalone.sty}{comments=false}%
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.sty}{mode}
%    \begin{macrocode}
\sa@pkgoption{mode}{%
    \begingroup
    \expandafter\let\expandafter\@tempa\csname sa@mode@#1\endcsname
    \ifx\@tempa\relax
        \endgroup
        \PackageError{standalone}{Wrong value for option 'mode'}{}%
    \else
        \expandafter
        \endgroup
        \@tempa
    \fi
}
\def\sa@mode@none{%
    \let\sa@mode\relax%
}
\def\sa@mode@tex{%
    \def\sa@mode{1}%
}
\def\sa@mode@image{%
    \def\sa@mode{2}%
}
\@namedef{sa@mode@image|tex}{%
    \def\sa@mode{0}%
}
\def\sa@mode@build{%
    \def\sa@mode{3}%
}
\def\sa@mode@buildmissing{%
    \def\sa@mode{4}%
}
\def\sa@mode@buildnew{%
    \ifxetex
        \PackageWarning{standalone}{The 'mode=buildnew' option is not available for XeTeX.\MessageBreak
                                    Therefore 'mode=build' will be used instead}%
        \def\sa@mode{3}%
    \else
        \def\sa@mode{5}%
    \fi
}
\sa@mode@tex
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.sty}{obeyclassoptions}
%    \begin{macrocode}
\sa@pkgoption{obeyclassoptions}[true]{%
    \sa@boolean{obeyclassoptions}{#1}%
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.sty}{extension}
%    \begin{macrocode}
\sa@pkgoption{extension}{%
    \def\sa@graphicext{#1}%
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.sty}{build}
%    \begin{macrocode}
\sa@pkgoption{build}[]{%
    \setkeys{standalone.sty/build}{#1}%
}
%    \end{macrocode}
% \end{key}
%
% \begin{macro}{\sa@buildvar}[2]{name}{initial value}
% Wrapper to define \opt{build} variables.
%    \begin{macrocode}
\def\sa@buildvar#1#2{%
    \define@key{standalone.sty/build}{#1}{%
        \@namedef{sa@build@#1}{##1}%
    }%
    \@namedef{sa@build@#1}{#2}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{key}{standalone.sty/build}{jobname}
%    \begin{macrocode}
\sa@buildvar{jobname}{\file}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.sty/build}{latex}
%    \begin{macrocode}
\sa@buildvar{latex}{}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.sty/build}{quote}
%    \begin{macrocode}
\sa@buildvar{quote}{}
\let\sa@build@quote\relax
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.sty/build}{latexoptions}
%    \begin{macrocode}
\sa@buildvar{latexoptions}{%
    -interaction=batchmode -shell-escape -jobname \quote\buildjobname\quote
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.sty/build}{command}
%    \begin{macrocode}
\sa@buildvar{command}{%
    \latex\space\latexoptions\space\file
}
%%    '\string\PassOptionsToClass{border=0pt}{standalone}\string\input{\image}'
%    \end{macrocode}
% \end{key}
%
% Set default values depending on the used compiler.
%    \begin{macrocode}
\def\sa@build@postcommand{}
\ifpdf
    \def\sa@graphicext{.pdf}
    \ifluatex
        \def\sa@build@latex{lualatex}
    \else
        \def\sa@build@latex{pdflatex}
    \fi
\else
\ifxetex
    \def\sa@graphicext{.pdf}
    \def\sa@build@latex{xelatex}
\else
    \def\sa@graphicext{.eps}
    \def\sa@build@latex{latex}
    \def\sa@build@postcommand{dvips -o \quote\file.eps\quote\space \quote\file.dvi\quote}
\fi\fi
%    \end{macrocode}
%
%    \begin{macrocode}
\ProcessOptionsX*<standalone.sty>\relax
\disable@keys{standalone.sty}{subpreambles,print,sort}
%    \end{macrocode}
%
% Set correct quoting character for build option if none was set.
%    \begin{macrocode}
\def\sa@setquote{%
    \ifx\sa@build@quote\relax
    \expandafter\ifx\csname sa@convert@quote\endcsname\relax
    \begingroup
    \@tempswafalse
%    \end{macrocode}
% If \Macro\pdftexbanner is not defined (XeLaTeX) the distribution can not
% be determined and double quotes are set to ensure proper operation under MiKTeX.
%    \begin{macrocode}
    \expandafter\ifx\csname pdftexbanner\endcsname\relax
        \@tempswatrue
    \else
%    \end{macrocode}
% Test if there is a `|MiKTeX|' in \Macro\pdftexbanner.
%    \begin{macrocode}
    \def\MiKTeX{MiKTeX}
    \@onelevel@sanitize\MiKTeX
    \expandafter\def\expandafter\testmiktex\expandafter##\expandafter1\MiKTeX##2\relax{%
            \ifx\empty##2\empty
                \@tempswafalse
            \else
                \@tempswatrue
            \fi
    }
    \expandafter\expandafter
    \expandafter\testmiktex\expandafter\pdftexbanner\MiKTeX\relax\relax
    \fi
    \expandafter
    \endgroup
    \if@tempswa
    \def\sa@build@quote{"}
    \else
    \def\sa@build@quote{'}
    \fi
    \else
    \let\sa@build@quote\sa@convert@quote
    \fi
    \fi
}
%    \end{macrocode}
%
% In non-sorted print mode comments are preserved by default.
%    \begin{macrocode}
\ifsa@printsubpreambles
  \ifsa@sortsubpreambles\else
    \@ifundefined{sa@percent}{%
        \setkeys{standalone.sty}{comments=true}%
    }{}%
  \fi
\fi
%    \end{macrocode}
%
% \begin{macro}{\standaloneconfig}
%    \begin{macrocode}
\@ifclassloaded{standalone}{%
    \def\standaloneconfig{%
        \setkeys{standalone.sty,standalone.cls}%
    }%
}{%
    \newcommand*{\standaloneconfig}{%
        \setkeys{standalone.sty}%
    }%
}
%    \end{macrocode}
% \end{macro}
%
%
% The \pkg{currfile} package is used to get the file paths of the included sub-files.
%    \begin{macrocode}
\RequirePackage{currfile}
%    \end{macrocode}
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{Processing of Sub-Preambles}
%
%    \begin{macrocode}
\ifsa@subpreambles
%    \end{macrocode}
%
% \begin{macro}{\sa@out}
% Write handle.
%    \begin{macrocode}
\newwrite\sa@out
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@write}
% Helper macro for file output.
%    \begin{macrocode}
\def\sa@write{\immediate\write\sa@out}%
%    \end{macrocode}
% \end{macro}
%
%
%    \begin{macrocode}
\ifsa@printsubpreambles
%    \end{macrocode}
%
% \begin{macro}{\sa@removeonlyifstandalone}
% Scans for |\onlyifstandalone| and removes it argument.
%    \begin{macrocode}
\long\def\sa@removeonlyifstandalone#1\onlyifstandalone{%
  \g@addto@macro\sa@preamble{#1}%
  \@ifnextchar\sa@endmarker
    {\@gobble}%
    {\expandafter\sa@gobbleeol\expandafter\sa@removeonlyifstandalone\expandafter^^J\@gobble}%
}
%    \end{macrocode}
% \end{macro}
%
%    \begin{macrocode}
\fi
%    \end{macrocode}
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{Sorting of package options}
%
% Macros only needed for this mode are defined inside the |\if...|
% to save memory otherwise.
%
%    \begin{macrocode}
\ifsa@sortsubpreambles
%    \end{macrocode}
%
% \begin{macro}{\sa@usepackagewithoutoptions}
% Simply calls the original |\usepackage| while skipping the optional
% argument with potential package options.
%    \begin{macrocode}
\newcommand{\sa@usepackagewithoutoptions}[2][]{%
  \sa@orig@usepackage{#2}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@endmarker}
% Unique end marker. Will not be expanded.
%    \begin{macrocode}
\def\sa@endmarker{%
  \@gobble{sa@endmarker}%
}
%    \end{macrocode}
% \end{macro}
%
%    \begin{macrocode}
\ifsa@printsubpreambles
%    \end{macrocode}
%
%
% In sorted print mode all collected package etc. information is printed into the output file, followed
% by the reduced sub-preambles.
%    \begin{macrocode}
\AtEndDocument{%
  \sa@write{\@percentchar\space Packages required by sub-files:}%
  \expandafter\@for\expandafter\pkg\expandafter:\expandafter=\sa@collpkgs\do{%
    \ifx\pkg\empty\else
      \sa@write{%
        \string\usepackage%
        \expandafter\ifx\csname sa@pkgopts@\pkg\endcsname\empty\else%
          [\csname sa@pkgopts@\pkg\endcsname]%
        \fi
        {\pkg}%
        \expandafter\ifx\csname sa@pkgdate@\pkg\endcsname\relax\else%
          [\csname sa@pkgdate@\pkg\endcsname]%
        \fi
        }%
    \fi
  }%
  \ifx\sa@collpgflibs\empty\else
  \sa@write{^^J\@percentchar\space PGF libraries required by sub-files:}%
  \expandafter\@for\expandafter\lib\expandafter:\expandafter=\sa@collpgflibs\do{%
    \ifx\lib\empty\else
      \sa@write{\string\usepgflibrary{\lib}}%
    \fi
  }%
  \fi
  \ifx\sa@colltikzlibs\empty\else
  \sa@write{^^J\@percentchar\space TikZ libraries required by sub-files:}%
  \expandafter\@for\expandafter\lib\expandafter:\expandafter=\sa@colltikzlibs\do{%
    \ifx\lib\empty\else
      \sa@write{\string\usetikzlibrary{\lib}}%
    \fi
  }%
  \fi
  \ifx\sa@colltikztiminglibs\empty\else
  \sa@write{^^J\@percentchar\space TikZ-Timing libraries required by sub-files:}%
  \expandafter\@for\expandafter\lib\expandafter:\expandafter=\sa@colltikztiminglibs\do{%
    \ifx\lib\empty\else
      \sa@write{%
        \string\usetikztiminglibrary%
        \expandafter\ifx\csname sa@tikztimingopts@\lib\endcsname\empty\else%
          [\csname sa@tikztimingopts@\lib\endcsname]%
        \fi
        {\lib}%
        \expandafter\ifx\csname sa@tikztimingdate@\lib\endcsname\relax\else%
          [\csname sa@tikztimingdate@\lib\endcsname]%
        \fi
        }%
    \fi
  }%
  \fi
  \sa@write{\expandafter\unexpanded\expandafter{\sa@preamble}}%
  \message{^^JPackage 'standalone' INFO: See file '\jobname.stp' for list of sub-preambles.^^J}%
  \immediate\closeout\sa@out
}
%    \end{macrocode}
%
% \begin{macro}{\sa@removepackages}
% Scans for |\usepackage|.
%    \begin{macrocode}
\long\def\sa@removepackages#1\usepackage{%
  \sa@removepgflibs#1\usepgflibrary\sa@endmarker
  \@ifnextchar\sa@endmarker
    {\@gobble}%
    {\sa@sortpackages}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@removepgflibs}
% Scans for |\usepgflibrary|.
%    \begin{macrocode}
\long\def\sa@removepgflibs#1\usepgflibrary{%
  \sa@removetikzlibs#1\usetikzlibrary\sa@endmarker
  \@ifnextchar\sa@endmarker
    {\@gobble}%
    {\sa@sortpgflibs}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@removetikzlibs}
% Scans for |\usetikzlibrary|.
%    \begin{macrocode}
\long\def\sa@removetikzlibs#1\usetikzlibrary{%
  \sa@removetikztiminglibs#1\usetikztiminglibrary\sa@endmarker
  \@ifnextchar\sa@endmarker
    {\@gobble}%
    {\sa@sorttikzlibs}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@removetikztiminglibs}
% Scans for |\usetikztiminglibrary|.
%    \begin{macrocode}
\long\def\sa@removetikztiminglibs#1\usetikztiminglibrary{%
  \sa@removeonlyifstandalone#1\onlyifstandalone\sa@endmarker
  \@ifnextchar\sa@endmarker
    {\@gobble}%
    {\sa@sorttikztiminglibs}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@sortpackage}
% Reads \cs{usepackage} arguments and stores them away. A list of all packages is compiled. Every package is only
% added once and has also a list of options used, also only saved once.
% If package dates are requested then the highest one is stored. Trailing newlines are removed.
%    \begin{macrocode}
\def\sa@collpkgs{}%
\newcommand\sa@sortpackages[2][]{%
  \@ifnextchar[%]
    {\sa@@sortpackages{#1}{#2}}%
    {\sa@@sortpackages{#1}{#2}[]}%
}
\def\sa@@sortpackages#1#2[#3]{%
  \@for\pkg:=#2\do {%
    \@ifundefined{sa@pkgopts@\pkg}%
      {%
        \expandafter\g@addto@macro\expandafter\sa@collpkgs\expandafter{\expandafter,\pkg}%
        \global\@namedef{sa@pkgopts@\pkg}{#1}%
        \global\@namedef{sa@pkgopt@\pkg @}{}%
        \ifx\relax#1\relax\else
          \@for\opt:=#1\do{\global\@namedef{sa@pkgopt@\pkg @\opt}{}}%
        \fi
      }%
      {%
        \ifx\relax#1\relax\else
          \@for\opt:=#1\do{%
            \@ifundefined{sa@pkgopt@\pkg @\opt}%
              {%
                \expandafter\g@addto@macro\csname sa@pkgopts@\pkg\expandafter\endcsname\expandafter{\expandafter,\opt}%
                \global\@namedef{sa@pkgopt@\pkg @\opt}{}%
              }{}%
          }%
        \fi
      }%
    \ifx\relax#3\relax\else
    \@ifundefined{sa@pkgdate@\pkg}%
      {\global\@namedef{sa@pkgdate@\pkg}{#3}}%
      {%
        \ifnum\expandafter\expandafter
         \expandafter\sa@@getdate\csname sa@pkgdate@\pkg\endcsname//00\relax<\sa@@getdate#3//00\relax
          \global\@namedef{sa@pkgdate@\pkg}{#3}%
        \fi
      }%
    \fi
  }%
  \sa@gobbleeol\sa@removepackages^^J%
}
\def\sa@@getdate#1/#2/#3#4#5\relax{#1#2#3#4}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@sortpgflibs}
% Reads the \cs{usepgflibrary} argument and stores it away.
% Trailing newlines are removed.
%    \begin{macrocode}
\def\sa@collpgflibs{}%
\def\sa@sortpgflibs#1{%
  \@for\lib:=#1\do {%
    \@ifundefined{sa@pgflib@\lib}%
      {%
        \expandafter\g@addto@macro\expandafter\sa@collpgflibs\expandafter{\expandafter,\lib}%
        \global\@namedef{sa@pgflib@\lib}{}%
      }%
      {}%
  }%
  \sa@gobbleeol\sa@removepgflibs^^J%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@sorttikzlibs}
% Reads the \cs{usetikzlibrary} argument and stores it away.
% Trailing newlines are removed.
%    \begin{macrocode}
\def\sa@colltikzlibs{}%
\def\sa@sorttikzlibs#1{%
  \@for\lib:=#1\do {%
    \@ifundefined{sa@tikzlib@\lib}%
      {%
        \expandafter\g@addto@macro\expandafter\sa@colltikzlibs\expandafter{\expandafter,\lib}%
        \global\@namedef{sa@tikzlib@\lib}{}%
      }%
      {}%
  }%
  \sa@gobbleeol\sa@removetikzlibs^^J%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@sorttikztiminglibs}
% Reads \cs{usetikztiminglibrary} arguments and stores them away.
% Trailing newlines are removed.
%    \begin{macrocode}
\def\sa@colltikztiminglibs{}%
\newcommand\sa@sorttikztiminglibs[2][]{%
  \@ifnextchar[%]
    {\sa@@sorttikztiminglibs{#1}{#2}}%
    {\sa@@sorttikztiminglibs{#1}{#2}[]}%
}
\def\sa@@sorttikztiminglibs#1#2[#3]{%
  \@for\lib:=#2\do {%
    \@ifundefined{sa@tikztimingopts@\lib}%
      {%
        \expandafter\g@addto@macro\expandafter\sa@colltikztiminglibs\expandafter{\expandafter,\lib}%
        \global\@namedef{sa@tikztimingopts@\lib}{#1}%
        \global\@namedef{sa@tikztimingopt@\lib @}{}%
        \ifx\relax#1\relax\else
          \@for\opt:=#1\do{\global\@namedef{sa@tikztimingopt@\lib @\opt}{}}%
        \fi
      }%
      {%
        \ifx\relax#1\relax\else
          \@for\opt:=#1\do{%
            \@ifundefined{sa@tikztimingopt@\lib @\opt}%
              {%
                \expandafter\g@addto@macro\csname sa@tikztimingopts@\lib\expandafter\endcsname\expandafter{\expandafter,\opt}%
                \global\@namedef{sa@tikztimingopt@\lib @\opt}{}%
              }{}%
          }%
        \fi
      }%
    \ifx\relax#3\relax\else
    \@ifundefined{sa@tikztimingdate@\lib}%
      {\global\@namedef{sa@tikztimingdate@\lib}{#3}}%
      {%
        \begingroup
        \edef\@tempa{{\csname sa@tikztimingdate@\lib\endcsname}{#3}}%
        \expandafter\sa@getlargerdate\@tempa
        \expandafter\xdef\csname sa@tikztimingdate@\lib\endcsname{\sa@thedate}%
        \endgroup
      }%
    \fi
  }%
  \sa@gobbleeol\sa@removetikztiminglibs^^J%
}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sa@gobbleopt}
% Gobbles an optional argument and a potential line endings and then executes the command given by |#1|.
%    \begin{macrocode}
\def\sa@gobbleopt#1[#2]{%
  \@ifnextchar^^J%
    {\sa@gobbleeol{#1}}{#1}%
}
%    \end{macrocode}
% \end{macro}
%
%    \begin{macrocode}
\else
%    \end{macrocode}
%
% \begin{macro}{\sa@scanpackages}
% Scans for |\usepackage|.
%    \begin{macrocode}
\def\sa@scanpackages#1\usepackage{%
  \@ifnextchar\sa@endmarker
    {\@gobble}%
    {\sa@collectpackage}
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@collectpackage}
% Reads \cs{usepackage} arguments (ignores optional date) and stores it away.
% The options are later passed to the package to avoid option clashes.
%    \begin{macrocode}
\newcommand\sa@collectpackage[2][]{%
  \ifx\relax#1\relax\else
    \g@addto@macro\sa@collopts{\PassOptionsToPackage{#1}{#2}}%
  \fi
  \sa@scanpackages
}
\fi
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@collopts}
% Accumulator for collected options. Is executed and cleared at the end of this package.
%    \begin{macrocode}
\def\sa@collopts{}
\AtEndOfPackage{\sa@collopts\let\sa@collopts\relax}
%    \end{macrocode}
% \end{macro}
%
% End of |\ifsa@sortsubpreambles|.
%    \begin{macrocode}
\fi
%    \end{macrocode}
%
% \begin{environment}{standalonepreambles}
% This environment simply adds a group and sets the endline character to a printed newline and the argument character
% |#| as a normal character. The first suppresses |\par|'s in the stored sub-preambles while preserving newlines. The latter
% is required to permit macro arguments in the preambles. Otherwise a |#| is doubled to |##| causing compile errors when the
% sub-preambles are used.
% The |.sta| file is closed after this environment.
%    \begin{macrocode}
\def\standalonepreambles{%
  \begingroup
  \endlinechar=\m@ne
  \@makeother\#%
}
\def\endstandalonepreambles{%
  \endgroup
  \endinput
}
%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{subpreambles}
% This environment rereads the sub-preambles from the |.sta| files and stores it globally under the name
% ``\cs{prevsubpreamble@}\meta{file name}''. If sorting is enabled the sub-preambles are also scanned for
% loaded packages.
%    \begin{macrocode}
\long\gdef\subpreamble#1#2\endsubpreamble{%
  \expandafter\gdef\csname prevsubpreamble@#1\endcsname{#2}%
  \ifsa@sortsubpreambles
    \sa@scanpackages#2\usepackage\sa@endmarker
  \fi
}
\def\endsubpreamble{}%
%    \end{macrocode}
% \end{environment}
%
% If in |print| mode open the |.stp| file.
%    \begin{macrocode}
\ifsa@printsubpreambles
  \immediate\openout\sa@out=\jobname.stp\relax
\else
%    \end{macrocode}
% otherwise:
%
% Process |.sta| file from last run. All changes must be made by own macros which define the value globally.
% Therefore the input is wrapped in a group. Some spaces or special line endings could process typeset content,
% which causes errors inside the preamble. To be on the save side the input `content' is stored in a temp box.
% The normal catcode of the `@' character is restored because comparing the previous subpreamble with the current one
% would fail otherwise if the |standalone| package is loaded while |\makeatletter| is active.
%    \begin{macrocode}
\begingroup
  \setbox\@tempboxa\hbox{%
    \makeatother
    \InputIfFileExists{\jobname.sta}{}{\PackageInfo{standalone}{STA file not found!}{}{}}%
  }%
\endgroup
%    \end{macrocode}

% \begin{macro}{\AtBeginDocument}
% At begin of the document the |.sta| file is read again. This time the sub-preamble macros are executed as normal.
% The |standalone| macros are defined to be without effect. If `sorting' is enabled \cs{usepackage} is temporarily
% redefined to ignore any given options, which where already passed (\cs{PassOptionsToPackage}) beforehand.
%    \begin{macrocode}
\AtBeginDocument{%
  \let\subpreamble\@gobble
  \let\endsubpreamble\relax
  \let\standalonepreambles\relax
  \let\endstandalonepreambles\relax
  \ifsa@sortsubpreambles
    \let\sa@orig@usepackage\usepackage
    \let\usepackage\sa@usepackagewithoutoptions
  \fi
  \InputIfFileExists{\jobname.sta}{}{}%
  \ifsa@sortsubpreambles
    \let\usepackage\sa@orig@usepackage
  \fi
  \immediate\openout\sa@out=\jobname.sta\relax
  \immediate\write\sa@out{\string\standalonepreambles}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\AtEndDocument}
% At end of the document write end macro to and close |.sta| file.
%    \begin{macrocode}
\AtEndDocument{%
  \sa@write{\string\endstandalonepreambles}%
  \immediate\closeout\sa@out
}
%    \end{macrocode}
% \end{macro}
%
% End of |\ifsa@printsubpreambles|.
%    \begin{macrocode}
\fi
%    \end{macrocode}
%
% End of |\ifsa@subpreambles|.
%    \begin{macrocode}
\fi
%    \end{macrocode}
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{Skipping of Sub-Preambles in Main Mode}
%
% This macros make the main document skip all preambles in sub-files.
%
% \begin{macro}{\sa@gobbleeol}
% Gobbles all following line endings (i.e.\ empty lines) and then executes the command given by |#1|.
% Because |\@ifnextchar| ignores spaces this also removes lines with only spaces.
%    \begin{macrocode}
\def\sa@gobbleeol#1^^J{%
  \@ifnextchar^^J%
    {\sa@gobbleeol{#1}}{#1}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@endinput}
% Ends the input file and discards all remaining material on the same line.
% To avoid issues with some user input like |%| after |\begin{document}| or
% a changed |\endlinechar| it is reset and any remaining text is discarded
% verbatim. This might also read the next line if the EOL of the current
% one got already commented out.
%    \begin{macrocode}
\def\sa@endinput{%
    \endlinechar`^^J\relax
    \let\do\@makeother
    \dospecials
    \sa@@endinput
}%
\def\sa@@endinput#1^^J{%
    \endgroup
    \endinput
}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sa@substbox}
% The substitute for the content if skipped. Having no content at all can lead to errors caused by e.g.\ an outer
% \Macro\resizebox.
%    \begin{macrocode}
\def\sa@substbox{%
    \leavevmode\hbox to 1pt{\vbox to 1pt{}}%
}%
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\standaloneignore}
% \changes{v0.3}{2010/03/26}{New macro}
% This macro must only be used in a sub-file before a |\documentclass|. It gobbles everything up to this macro
% and then executes the |standalone| definition of it shown further below.
% It should be written as |\csname standaloneignore\endcsname| to ignore errors in standalone mode.
% The second definition allows the user to also write |\csname standaloneignore \endcsname| (note the extra space)
% without errors.
%    \begin{macrocode}
\long\def\standaloneignore#1\documentclass{%
  \sa@documentclass
}
\@namedef{standaloneignore\space}{\standaloneignore}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@documentclass}
% The |standalone| definition of \cs{documentclass}. If the sub-preambles are to be processed then the
% starting content is written into the output file etc., but only for the first time this sub-file is included.
% Some input related settings are set-up (line endings, macro argument and comments).
% Finally \cs{sa@gobble} is called to process the preamble.
%    \begin{macrocode}
\newcommand{\sa@documentclass}[2][]{%
  \let\document\sa@document
  \let\sa@subfile@options\@empty
  \ifsa@obeyclassoptions
    \begingroup
    \edef\@tempa{#2}%
    \edef\@tempb{standalone}%
    \ifx\@tempa\@tempb
        \endgroup
        \def\sa@subfile@options{#1}%
    \else
        \endgroup
    \fi
  \fi
  \begingroup
  \ifsa@subpreambles
    \@ifundefined{sa@written@\currfilepath}%
      {%
        \ifsa@printsubpreambles
          \ifsa@sortsubpreambles
            \begingroup
              \edef\@tempa{^^J\@percentchar\space Preamble from file '\currfilepath'^^J}%
              \expandafter\g@addto@macro\expandafter\sa@preamble\expandafter{\@tempa}%
            \endgroup
          \else
            \sa@write{^^J\@percentchar\space Preamble from file '\currfilepath'}%
          \fi
        \else
          \sa@write{\string\subpreamble{\currfilepath}}%
        \fi
      }{}%
    \global\@namedef{subpreamble@\currfilepath}{}%
    \ifsa@printsubpreambles
      \endlinechar=`\^^J\relax
    \else
      \endlinechar=\m@ne
    \fi
    \@makeother\#%
    \@nameuse{sa@percent}%
  \fi
  \def\sa@gobbleto{document}%
  \sa@gobbleeol\sa@gobble^^J%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@gobble}
% Gobbles everything to the next |\begin|, then checks if it was a |\begin{document}|.
% If sub-preamble extraction is activated it accumulates the skipped content in macros
% named ``\cs{subpreamble@}\meta{file name}''. Every sub-file is remembered and its preamble is only saved once.
% In |print| mode the file body is ignored and a appropriate warning is printed,
% otherwise the current and previous sub-preamble of the current processed file are compared. If different the file body is also
% ignored to avoid errors due to possible newly required but not loaded packages. The user is warned again about this
% and is asked to rerun \LaTeX{}.
%    \begin{macrocode}
\def\sa@preamble{}%
\long\def\sa@gobble#1\begin#2{%
  \def\@tempa{#2}%
  \ifx\@tempa\sa@gobbleto
    \ifsa@subpreambles
      \expandafter\g@addto@macro\csname subpreamble@\currfilepath\endcsname{#1}%
      \@ifundefined{sa@written@\currfilepath}%
        {%
          \ifsa@printsubpreambles
            \ifsa@sortsubpreambles
              \sa@removepackages#1\usepackage\sa@endmarker
            \else
              \begingroup
              \let\sa@preamble\empty
              \sa@removeonlyifstandalone#1\onlyifstandalone\sa@endmarker
              \expandafter\sa@write\expandafter{\expandafter\unexpanded\expandafter{\sa@preamble}}%
              \endgroup
            \fi
          \else
            \sa@write{\unexpanded{#1}}%
            \sa@write{\string\endsubpreamble}%
          \fi
        }{}%
      \global\@namedef{sa@written@\currfilepath}{}%
      \ifsa@printsubpreambles
        \def\next{%
          \PackageWarning{standalone}{Running 'standalone' package in sub-preamble print mode. All body content of file `\currfilepath' is ignored!}{}{}%
          \sa@substbox
          \sa@endinput
        }%
      \else
      \expandafter
      \ifx
      \csname prevsubpreamble@\currfilepath\expandafter\endcsname
      \csname     subpreamble@\currfilepath\endcsname
        \def\next{\expandafter\endgroup\expandafter\begin\expandafter{\sa@gobbleto}}%
      \else
        %\expandafter\show\csname prevsubpreamble@\currfilepath\endcsname
        %\expandafter\show\csname     subpreamble@\currfilepath\endcsname
        \def\next{%
          \PackageWarning{standalone}{Sub-preamble of file '\currfilepath' has changed. Content will be ignored. Please rerun LaTeX!}{}{}%
          \immediate\write\@mainaux{%
            \@percentchar\space standalone package info: Rerun LaTeX!
          }%
          \sa@substbox
          \sa@endinput
        }%
      \fi
      \fi
    \else
      \def\next{\expandafter\endgroup\expandafter\begin\expandafter{\sa@gobbleto}}%
    \fi
  \else
    \ifsa@subpreambles
      \expandafter\g@addto@macro\csname subpreamble@\currfilepath\endcsname{#1\begin{#2}}%
      \@ifundefined{sa@written@\currfilepath}%
        {\sa@write{\unexpanded{#1\begin{#2}}}}{}%
    \fi
    \def\next{\sa@gobble}%
  \fi
  \next
}
%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{standalone}
% Provide an empty definition of the |standalone| environment. The class is defining it with the code required in |standalone| mode.
%    \begin{macrocode}
\@ifundefined{standalone}
  {\newenvironment{standalone}[1][]{}{}}
  {}
%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{standalone}
% Provide an `empty' definition of the |standaloneframe| environment.
% It only gobbles all arguments: |<...>[<...>][...]{...}{...}|. Please note that the last two |{ }| arguments are also optional.
% The class is defining it with the code required in |standalone| mode.
%    \begin{macrocode}
\@ifundefined{standaloneframe}
  {\@ifundefined{beamer@newenv}
    {\newenvironment{standaloneframe}[1][]{%
      \@ifnextchar[%]
        {\sa@framegobbleopt}{\sa@framegobbleargs}}{}%
    }
    {\newenvironment<>{standaloneframe}[1][]{%
      \@ifnextchar[%]
        {\sa@framegobbleopt}{\sa@framegobbleargs}}{}%
    }
   \def\sa@framegobbleopt[#1]{\sa@framegobbleargs}
   \def\sa@framegobbleargs{%
     \@ifnextchar\bgroup
       {\sa@framegobbleargs@}%
       {}%
   }
   \def\sa@framegobbleargs@#1{%
    \@ifnextchar\bgroup
      {\@gobble}%
      {}%
   }
  }
  {}
%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\sa@orig@document}
% \begin{macro}{\sa@orig@enddocument}
% Store original |document| environment.
%    \begin{macrocode}
\let\sa@orig@document\document
\let\sa@orig@enddocument\enddocument
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\document}
% Redefine the |\begin{document}| of the main file to redefine \cs{documentclass}.
% This can not be done using \cs{AtBeginDocument} because the original redefines
% \cs{documentclass} itself after executing the hook.
%    \begin{macrocode}
\begingroup
\toks@\expandafter{%
    \document
    \let\documentclass\sa@documentclass
    \ignorespaces
}
\xdef\document{\the\toks@}%
\endgroup
%    \end{macrocode}
% \end{macro}
%
%
%    \begin{macrocode}
\ifsa@obeyclassoptions
%    \end{macrocode}
%
%    \begin{macrocode}
\IfFileExists{varwidth.sty}{%
    \RequirePackage{varwidth}%
}{}
%    \end{macrocode}
%
% \begin{key}{standalone.sty/class}{12pt}
%    \begin{macrocode}
\define@key{standalone.sty/class}{12pt}[]{%
    \def\sa@subfile@size{12}%
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.sty/class}{11pt}
%    \begin{macrocode}
\define@key{standalone.sty/class}{11pt}[]{%
    \def\sa@subfile@size{11}%
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.sty/class}{10pt}
%    \begin{macrocode}
\define@key{standalone.sty/class}{10pt}[]{%
    \def\sa@subfile@size{10}%
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{key}{standalone.sty/class}{class}
%    \begin{macrocode}
\define@key{standalone.sty/class}{class}{%
    \def\sa@subfile@class{#1}%
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.sty/class}{multi}
%    \begin{macrocode}
\define@key{standalone.sty/class}{multi}[true]{%
    \sa@boolorvalue{multi}{#1}{%
        \sa@multitrue\AtEndOfClass{\standaloneenv{#1}}%
    }%
    \ifsa@multi
        \def\sa@requestedpage{1}%
        \def\standaloneenv##1{%
            \begingroup
            \edef\@tempa{\endgroup\noexpand\@for\noexpand\@tempa:=\zap@space##1 \@empty}%
            \@tempa\do{\expandafter\@standaloneenv\expandafter{\@tempa}}%
        }%
        \def\@standaloneenv##1{%
            \expandafter\ifx\csname sa@orig@##1\endcsname\relax
                \expandafter\let\csname sa@orig@##1\expandafter\endcsname\csname ##1\endcsname
                \expandafter\let\csname sa@orig@end##1\expandafter\endcsname\csname end##1\endcsname
            \fi
            \expandafter\def\csname ##1\endcsname{%
                \ifnum\sa@internal=0
                    \global\advance\sa@pagenum\@ne
                    \sa@boxit
                \fi
                \advance\sa@internal\@ne
                \csname sa@orig@##1\endcsname
            }%
            \expandafter\def\csname end##1\endcsname{%
                \csname sa@orig@end##1\endcsname
                \advance\sa@internal\m@ne
                \ifnum\sa@internal=0
                    \endsa@boxit
                    \ifx\sa@requestedpage\@empty
\let\sa@requestedpage\sa@allpages
    \fi
                    \ifx\sa@requestedpage\sa@allpages
                        \usebox\sa@box
                    \else
                    \ifnum\sa@requestedpage=\sa@pagenum
                        \usebox\sa@box
                    \fi\fi
                \fi
                \@ignoretrue
            }%
        }%
    \else
        \let\standaloneenv\@gobble
    \fi
}
\newcount\sa@internal
\newcount\sa@pagenum
\def\sa@allpages{-1}%
\let\sa@box\@tempboxa
%    \end{macrocode}
% \end{key}
%
%
% \begin{macro}{\sa@boxit}
%    \begin{macrocode}
\def\sa@boxit{%
    \setbox\sa@box\hbox\bgroup\color@setgroup\sa@varwidth
}%
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\endsa@boxit}
%    \begin{macrocode}
\def\endsa@boxit{%
    \sa@endvarwidth\color@endgroup\egroup
}%
%    \end{macrocode}
% \end{macro}
%
% \begin{key}{standalone.sty/class}{tikz}
%    \begin{macrocode}
\define@key{standalone.sty/class}{tikz}[true]{%
    \sa@boolean{tikz}{#1}%
    \ifsa@tikz
        \setkeys*{standalone.sty/class}{multi=tikzpicture,varwidth=false}%
    \fi
}
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.sty/class}{varwidth}
%    \begin{macrocode}
\define@key{standalone.sty/class}{varwidth}[true]{%
    \sa@boolorvalue{varwidth}{#1}{\sa@varwidthtrue\def\sa@width{#1}}%
    \ifsa@varwidth
        \expandafter\ifx\csname ver@varwidth.sty\endcsname\relax
            \PackageWarning{standalone}{A standalone file which uses the varwidth package\MessageBreak
                                        has been encountered while obeyclassoptions=true.\MessageBreak
                                        Please load this package in the preamble.\MessageBreak
                                        The file in question is loaded}%
            \sa@varwidthfalse
        \fi
    \fi
    \ifsa@varwidth
        \def\sa@varwidth{\varwidth{\sa@width}}%
        \def\sa@endvarwidth{\endvarwidth}%
    \else
        \let\sa@varwidth\@empty
        \let\sa@endvarwidth\@empty
    \fi
}
\let\sa@varwidth\@empty
\let\sa@endvarwidth\@empty
\def\sa@width{\linewidth}
%    \end{macrocode}
% \end{key}
%
%
%
%
% \begin{key}{standalone.sty/class}{beamer}
% The if-switch is always set the `|false|' aftwards, because we are not in standalone mode.
%    \begin{macrocode}
\define@key{standalone.sty/class}{beamer}[true]{%
    \sa@boolean{beamer}{#1}%
    \ifstandalonebeamer
        \setkeys*{standalone.sty/class}{class=beamer,preview=false,crop=false,varwidth=false}%
    \fi
    \standalonebeamerfalse
}
\let\sa@beamertrue\standalonebeamertrue
\let\sa@beamerfalse\standalonebeamerfalse
%    \end{macrocode}
% \end{key}
%
% \begin{key}{standalone.sty/class}{border}
%    \begin{macrocode}
\define@key{standalone.sty/class}{border}{%
    \sa@readborder#1 {} {} {} {} \@nnil
}
%    \end{macrocode}
% \end{key}
%
%
% \begin{macro}{\sa@border@left}
% \begin{macro}{\sa@border@right}
% \begin{macro}{\sa@border@top}
% \begin{macro}{\sa@border@margin}
%    \begin{macrocode}
\def\sa@border@left{0.50001bp}
\let\sa@border@right\sa@border@left
\let\sa@border@top\sa@border@left
\let\sa@border@bottom\sa@border@left
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\rem@bp}
%    \begin{macrocode}
\def\rem@bp#1bp\relax#2\@nnil{#1}%
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\default@bp}
%    \begin{macrocode}
\def\default@bp#1#2{%
    \begingroup
    \afterassignment\remove@to@nnil
    \dimen@ #2bp\relax\@nnil
    \expandafter
    \endgroup
    \expandafter
    \def\expandafter#1\expandafter{\the\dimen@}%
}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sa@readborder}
%    \begin{macrocode}
\def\sa@readborder#1 #2 #3 #4 #5\@nnil{%
    \ifx\\#2#3#4\\%
        \default@bp\sa@border@left{#1}%
        \let\sa@border@right\sa@border@left
        \let\sa@border@top\sa@border@left
        \let\sa@border@bottom\sa@border@left
    \else
    \ifx\\#4\\%
        \default@bp\sa@border@left{#1}%
        \let\sa@border@right\sa@border@left
        \default@bp\sa@border@top{#2}%
        \let\sa@border@bottom\sa@border@top
    \else
        \default@bp\sa@border@left{#1}%
        \default@bp\sa@border@bottom{#2}%
        \default@bp\sa@border@right{#3}%
        \default@bp\sa@border@top{#4}%
    \fi\fi
}%
%    \end{macrocode}
% \end{macro}
%
%    \begin{macrocode}
\IfFileExists{adjustbox.sty}{%
    \IfFileExists{trimclip.sty}{%
        \RequirePackage{trimclip}%
    }{%
        \RequirePackage{adjustbox}%
    }%
    \def\sa@beginbox{%
        \ifcase0%
            \ifdim\sa@border@left<\z@ 1\fi
            \ifdim\sa@border@right<\z@ 1\fi
            \ifdim\sa@border@top<\z@ 1\fi
            \ifdim\sa@border@bottom<\z@ 1\fi
        \relax
            \marginbox{{\sa@border@left} {\sa@border@bottom} {\sa@border@right} {\sa@border@top}}\bgroup
        \else
            \clipbox{{-\sa@border@left} {-\sa@border@bottom} {-\sa@border@right} {-\sa@border@top}}\bgroup
        \fi
    }%
    \let\sa@endbox\egroup
}{%
    \PackageInfo{standalone}{The 'adjustbox' bundle was not found. Negative borders will not be clipped.}%
    \def\sa@beginbox{%
        \setbox\@tempboxa\color@hbox
    }%
    \def\sa@endbox{%
        \color@endbox
        \sbox\@tempboxa{%
            \setlength\@tempdima{\sa@border@left}%
            \hskip\@tempdima
            \setlength\@tempdima{\sa@border@right}%
            \setlength\@tempdimb{\sa@border@bottom}%
            \setlength\@tempdimc{\sa@border@top}%
            \advance\@tempdima\wd\@tempboxa
            \wd\@tempboxa\@tempdima
            \advance\@tempdimb\dp\@tempboxa
            \dp\@tempboxa\@tempdimb
            \advance\@tempdimc\ht\@tempboxa
            \ht\@tempboxa\@tempdimc
            \raise\dp\@tempboxa\box\@tempboxa
        }%
        \usebox\@tempboxa
    }%
}
%    \end{macrocode}
%
%
%    \begin{macrocode}
\fi
%    \end{macrocode}
%
%
% \begin{macro}{\sa@document}
% This is the |\begin{document}| of the sub files. It does nothing except of
% redefining |\end{document}| and calling our own |atbegindocument| hook.
%    \begin{macrocode}
\def\sa@document{%
    \ifsa@group
        \let\enddocument\sa@enddocument
        \ifx\sa@subfile@options\@empty\else
% Process class options
            \def\sa@subfile@size{10}%
            \def\sa@subfile@class{article}%
            \let\NeedsTeXFormat\@gobble
            \let\sa@atendofclass\@empty
            \def\AtEndOfClass{\g@addto@macro\sa@atendofclass}%
            \def\standaloneconfig{\setkeys*{standalone.sty/class}}%
            \let\sa@@latex@error\@latex@error
            \let\@latex@error\@gobbletwo
            \let\sa@selectfont\selectfont
            \let\selectfont\relax
            \makeatletter
            \nullfont
            \InputIfFileExists{standalone.cfg}{}{}%
            \begingroup
            \def\@tempa{\setkeys*{standalone.sty/class}}%
            \expandafter\expandafter
            \expandafter\endgroup
            \expandafter\@tempa\expandafter{\sa@subfile@options}%
            \sa@atendofclass
    \let\sa@requestedpage\Gin@page
            \sa@pagenum\z@
            \sa@beginbox
% Determinate required size files (normal classes or KOMA Script).
% If the main file does not use a KOMA class itself, the KOMA size files
% can't be used.
            \@ifundefined{KOMAClassName}{%
                \def\@tempa{size}%
            }{%
                \def\@tempa##1##2##3##4\relax{\def\@tempa{##1##2##3}}%
                \expandafter\@tempa\sa@subfile@class{}{}{}\relax
                \def\@tempb{scr}%
                \ifx\@tempa\@tempb
                    \def\@tempa##1{scrsize##1pt}%
                \else
                    \def\@tempa{size}%
                \fi
            }%
% Load size file. Redefine macros to avoid errors and spaces be introduced.
            \let\sa@newcommand\newcommand
            \let\sa@@ifundefined\@ifundefined
            \let\newcommand\renewcommand
            \let\@ifundefined\@thirdofthree
            \edef\@tempa{%
                \noexpand\input{\@tempa\sa@subfile@size.clo}%
                \catcode`\noexpand\@=\the\catcode`\@
            }\@tempa
            \let\newcommand\sa@newcommand
            \let\@latex@error\sa@@latex@error
            \let\@ifundefined\sa@@ifundefined
            \let\selectfont\sa@selectfont
            \normalsize
        \fi
    \else
        \endgroup
        \global\let\enddocument\sa@enddocument
    \fi
    \sa@atbegindocument
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@enddocument}
% This is the |\end{document}| of the sub files. It does nothing except of
% calling our own |atenddocument| hook and then the `after end document' handler.
% Also spaces after the environment are ignored. Otherwise a following line break
% will cause a space even if |\endinput| follows directly.
%    \begin{macrocode}
\def\sa@enddocument{%
    \sa@atenddocument
    \ifsa@group
        \ifx\sa@subfile@options\@empty\else
            \sa@endbox
        \fi
    \else
        \global\let\document\sa@orig@document
        \global\let\enddocument\sa@orig@enddocument
        \begingroup
        \def\@currenvir{document}%
    \fi
    \@ignoretrue
    \aftergroup\endinput
}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sa@@enddocument}
% This is a `after end document' handler for the sub-files. It restores macros and
% ends the input of the file.
%    \begin{macrocode}
%\def\sa@@enddocument{%
%  %\let\document\sa@orig@document
%  \let\enddocument\sa@orig@enddocument
%  \endinput
%}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@atbegindocument}
% This hook simply ignores all spaces after |\begin{document}| in the sub files.
%    \begin{macrocode}
\def\sa@atbegindocument{%
  \ignorespaces
}%
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sa@atenddocument}
% This hook simply ignores the last skip (normally the spaces) before |\end{document}| in the sub files.
%    \begin{macrocode}
\def\sa@atenddocument{%
  \ifhmode\unskip\fi
}%
%    \end{macrocode}
% \end{macro}
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsubsection{Include Standalone}
%
% \begin{macro}{\includestandalone}
%    \begin{macrocode}
\IfFileExists{gincltex.sty}{%
    \RequirePackage{gincltex}
    \newcommand*\includestandalone[2][]{%
        \begingroup
        \setkeys*{standalone.sty}{##1}%
        \edef\@tempa{{##2\sa@graphicext}}%
        \expandafter\expandafter\expandafter\includestandalone@
        \expandafter\expandafter\expandafter{\expandafter\XKV@rm\expandafter}\@tempa{##2}%
        \endgroup
    }
}{%
    \begingroup
    \let\on@line\@gobble
    \PackageWarning{standalone}{Required package 'gincltex' not found.\MessageBreak
                                The \string\includestandalone\space feature is disabled.}
    \endgroup
    \newcommand*\includestandalone[2][]{%
        \begingroup
        \input{##2}%
        \endgroup
    }
}
%    \end{macrocode}
% \end{macro}
%
%    \begin{macrocode}
\ifxetex\else
    \RequirePackage{filemod-expmin}
\fi
\newif\ifsa@buildsuccess
%    \end{macrocode}
%
% \begin{macro}{\includestandalone@}[3]{<options>}{<filename>.<graphic ext>}{<filename>}
%% 0 = PDF if exists, TEX otherwise
%% 1 = force TEX
%% 2 = force PDF
%% 3 = build PDF if not exists
%% 4 = build PDF if older than TEX
%    \begin{macrocode}
\def\includestandalone@#1#2#3{%
    \ifcase\sa@mode
    \relax% 0
        \IfFileExists{#2}%
            {\includegraphics[#1]{#2}}%
            {\includegraphics[#1]{#3.tex}}%
    \or% 1
        \includegraphics[#1]{#3.tex}%
    \or% 2
        \includegraphics[#1]{#2}%
    \or% 3
        \sa@buildgraphic{#3}%
        \ifsa@buildsuccess
            \includegraphics[#1]{#2}%
        \else
            \PackageWarning{standalone}%
                {Graphic '#2' could not be build.^^J%
                Shell escape activated?}%
                \includegraphics[#1]{#3.tex}%
        \fi
    \or% 4
        \IfFileExists{#2}%
            {\includegraphics[#1]{#2}}%
            {\sa@buildgraphic{#3}%
             \ifsa@buildsuccess
                \includegraphics[#1]{#2}%
             \else
                \PackageWarning{standalone}%
                 {Graphic '#2' could not be build.^^J%
                  Shell escape activated?}%
                 \includegraphics[#1]{#3.tex}%
             \fi
            }%
    \or% 5
        \filemodCmp{#3.tex}{#2}%
            {\sa@buildgraphic{#3}%
             \ifsa@buildsuccess
                \includegraphics[#1]{#2}%
             \else
                \PackageWarning{standalone}%
                 {Graphic '#2' could not be build.^^J%
                  Shell escape activated?}%
                 \includegraphics[#1]{#3.tex}%
             \fi
            }%
            {%
                \PackageInfo{standalone}%
                    {generated file #2 newer then source file #3.tex}%
                \includegraphics[#1]{#2}%
            }%
    \fi
}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sa@buildgraphic}
% Compiles the given external file.
% The state of the shell escape is checked.
%    \begin{macrocode}
\def\sa@buildgraphic#1{%
    \ifcase
      \ifx\pdfshellescape\@undefined
        \ifx\shellescape\@undefined
          \ifx\directlua\@undefined
            \z@
          \else
            \directlua{%
              tex.sprint((status.shell_escape or os.execute()) .. " ")}
          \fi
        \else
          \shellescape
        \fi
      \else
        \pdfshellescape
      \fi
        \PackageError{standalone}{Shell escape needed to create graphic! Use the '-shell-escape' option.}{}%
    \else
        \begingroup
        \edef\file{#1}%
        \edef\outfile{\file\sa@graphicext}%
        \edef\filemodbefore{\csname pdffilemoddate\endcsname{\outfile}}%
        \let\latex\sa@build@latex
        \let\latexoptions\sa@build@latexoptions
        \let\buildjobname\sa@build@jobname
        \sa@setquote
        \let\quote\sa@build@quote
        \ShellEscape{\sa@build@command}%
        \ifx\sa@build@postcommand\@empty\else
            \ShellEscape{\sa@build@postcommand}%
        \fi
        \IfFileExists{\outfile}{%
            \edef\filemodafter{\csname pdffilemoddate\endcsname{\outfile}}%
            \ifx\filemodbefore\filemodafter
                \expandafter\ifx\csname pdffilemoddate\endcsname\relax
                    \global\sa@buildsuccesstrue
                \else
                    \global\sa@buildsuccessfalse
                \fi
            \else
                \global\sa@buildsuccesstrue
            \fi
        }{%
            \global\sa@buildsuccessfalse
        }%
        \endgroup
    \fi
}
%    \end{macrocode}
% \end{macro}
%
% \iffalse
% \fi
%
% \iffalse
%</standalone.sty>
% \fi
%
% \iffalse
%<*standalone.tex>
% \fi
%
%\iffalse
%<*tex>
% \fi
% \subsection{Simple TeX File}
%
%    \begin{macrocode}
%%\ProvidesFile{standalone.tex}[2010/02/28 v0.4 Provides if-switch to show if file is compiled standalone]%
%    \end{macrocode}
%
% \begin{macro}{\ifstandalone}
% Provides \cs{ifstandalone} switch which is |\iftrue| if the normal |\documentclass|
% was not yet executed (and subsequently redefined to be |\@twoclasseserror|).
%    \begin{macrocode}
\expandafter\ifx\csname ifstandalone\endcsname\relax
\expandafter\newif\csname ifstandalone\endcsname
\expandafter\ifx\csname @twoclasseserror\endcsname\documentclass
\else
  \standalonetrue
\fi
\fi
%    \end{macrocode}
% \end{macro}
%
% \iffalse
%</tex>
% \fi
%
% \iffalse
%</standalone.tex>
% \fi
%
% \iffalse
%<*standalone.cfg>
% \fi
%
% \subsection{Config File}
% Default content of the configuration file. Users can override this by placing an own
% |standalone.cfg| file somewhere where \TeX\ can find it (user |texmf| directory or local directory).
% This user file can load the default config file using
% using |\InputIfFileExists{standalone/standalone.cfg}{}{}|.
% Be default only the |preview| package option are set and
% the navigation symbols of beamer standalones are disabled.
%    \begin{macrocode}
\NeedsTeXFormat{LaTeX2e}
\ProvidesFile{standalone.cfg}[%
%<!DATE>
%<!VERSION>
%<*DRIVER>
    2099/01/01 develop
%</DRIVER>
    Default configuration file for 'standalone' class]%
%    \begin{macrocode}
%    \end{macrocode}
%
%    \begin{macrocode}
%% Enabled the "varwidth" option if the "varwidth" package is available:
%%\IfFileExists{varwidth.sty}{%
%%    \standaloneconfig{varwidth}%
%%}{}%

%% Default options:
\standaloneconfig{crop}

%% Option which 'preview' should be loaded with
%% (will be ignored outside preamble)
\expandafter\ifx\csname @notprerr\endcsname\PassOptionsToPackage\else
\PassOptionsToPackage{active,tightpage}{preview}%
\fi

%% Enable 'preview' option by default:
%%\standaloneconfig{preview}

%% Remove the border:
\standaloneconfig{border=0pt}

%% Default preview border (used by standalone v0.x):
%%\standaloneconfig{border=0.50001bp}

%% Disable navigation symbols in beamer.
%% This must be done AtEndOfClass because the options are not processed yet,
%% so "beamer" mode is not enabled yet.
\AtEndOfClass{%
\ifstandalonebeamer
  \setbeamertemplate{navigation symbols}{}%
\fi
}
%    \end{macrocode}
% \iffalse
%% vim: ft=tex
% \fi
% \iffalse
%</standalone.cfg>
% \fi
%
% \Finale
% \endinput
