% \iffalse meta-comment
%
% Copyright (C) 2016 by Pierre Senellart
%
% 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 Pierre Senellart
% <pierre@senellart.com> and a version control system for this work
% is available at http://github.com/PierreSenellart/apxproof
%
% This work consists of the files apxproof.dtx and apxproof.ins
% and the derived file apxproof.sty.
%
% \fi
% 
% \iffalse
%<package>\NeedsTeXFormat{LaTeX2e}[2005/12/01]
%<package>\ProvidesPackage{apxproof}
%<package>  [2016/12/13 v1.0.2 Automatic proofs in appendix]
%
%<*driver>
\documentclass{ltxdoc}
\usepackage{apxproof}
\usepackage{hypdoc}
\usepackage{textcomp}
\usepackage[TS1,T1]{fontenc}
\usepackage{microtype}
\newtheorem{example}{Example}
\newtheoremrep{foobar}{Foobar}
\EnableCrossrefs
\CodelineIndex
\RecordChanges
\begin{document}
  \DocInput{apxproof.dtx}
\end{document}
%</driver>
% \fi
%
% \CheckSum{445}
%
% \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{v1.0.0}{2016/10/31}{Initial released version}
% \changes{v1.0.1}{2016/11/07}{Prevent empty bibliography environment;
% fix typos}
% 
% \GetFileInfo{apxproof.sty}
%
% \makeatletter\c@IndexColumns=2\makeatother
% \DoNotIndex{
%  \newcommand,\newenvironment,\end,\begin,\edef,\if,\else,\fi,\def,
%  \begingroup,\endgroup,\csname,\let,\noexpand,\protect,\expandafter,
%  \ifthenelse,\equal,\endcsname,\@empty,\@ifnotempty,\immediate,
%  \addtocounter,\newcounter,\newtoggle,\global,\ifdefined,\iftoggle,
%  \ifx,\jobname,\makeatletter,\makeatother,\newwrite,\NewEnviron,
%  \patchcmd,\relax,\renewcommand,\renewenvironment,\RequirePackage,
%  \roman,\space,\undefined
% }
%
% \title{The \textsf{apxproof} package}
% 
% \author{Pierre Senellart \\ \texttt{pierre@senellart.com} \\
% \url{http://github.com/PierreSenellart/apxproof}}
% \date{\filedate \quad \fileversion}
%
% \maketitle
% 
% \begin{abstract}
% This package makes it easier to write articles where proofs and other material
% are deferred to the appendix. The appendix material is written in the \LaTeX{}
% code along with the main text which it naturally complements, and it is
% automatically deferred. The package can automatically send proofs to the
% appendix, can repeat in the appendix the theorem environments stated in the
% main text, can section the appendix automatically based on the sectioning of
% the main text, and supports a separate bibliography for the appendix material.
% \end{abstract}
%
% \section{Usage}
% The \textsf{apxproof} package is intended to simplify the writing of articles where some of
% the content needs to be deferred to an appendix. This is in particular
% useful for the submission of scientific articles to conferences or
% journals that limit the number of pages in the main text but allow an
% extra appendix, where proofs of theorems and other material can be added.
%
% \subsection{Basics}
% To use \textsf{apxproof}, first load it in the header of your document:
% \begin{quote}|\usepackage{apxproof}|\end{quote}
% On its own, this does not do anything and should not change the
% appearance of your document. To add an appendix with some material from
% your document, use the |toappendix| environment:
% \begin{quote}
% |\begin{toappendix}|\DescribeEnv{toappendix}\\
% \hspace*{1em}\dots\\
% |\end{toappendix}|
% \end{quote}
% The content will appear at the end of your document, in an
% automatically generated section that refers to the current section in the main
% text.
% \begin{example}
% Throughout this documentation, all examples produce content
% deferred to the appendix, at the very end of this document.
% \begin{verbatim}
% \begin{toappendix}
% This content is in the appendix.
% \end{toappendix}
% \end{verbatim}
% \begin{toappendix}
%<*driver>
This content is in the appendix.
%</driver>
% \end{toappendix}
% \end{example}
% \subsection{Repeated Theorems and Proofs}
% In some scientific papers that include proofs, it is common to defer
% proofs to the appendix. This can easily be achieved using the
% |appendixproof| environment:
% \begin{quote}
% |\begin{appendixproof}|\DescribeEnv{appendixproof}\\
% \hspace*{1em}\dots\\
% |\end{appendixproof}|
% \end{quote}
% This behaves like the |toappendix| environment, except that 
% a proof environment is generated.
% \begin{example}We now send a proof to the appendix:
% \begin{verbatim}
% \begin{appendixproof}
% This proof is in the appendix.
% \end{appendixproof}
% \end{verbatim}
% \begin{appendixproof}
%<*driver>
This proof is in the appendix.
%</driver>
% \end{appendixproof}
% \end{example}
%
% When deferring proofs to the appendix, an annoying problem is that the
% statement of the theorem remains in the main text; it is hard to read a
% proof that is far away from the statement it proves. \textsf{apxproof}
% solves this issue by allowing statements of theorems to be \emph{repeated}:
% once in the main text, and once in the appendix before the proof of
% the statement. To use this feature, you can define a new
% \emph{repeated theorem} environment using the |\newtheoremrep| command:
% \begin{quote}
% |\newtheoremrep|\marg{name}\oarg{counter}\marg{title}\DescribeMacro{\newtheoremrep}
% \end{quote}
% Usage is exactly the same as that of AMS \LaTeX{}'s |\newtheorem|
% macro: \meta{name} (e.g., |theorem|) is the name of an environment that is created for this kind of
% theorem, \meta{counter} (e.g., |definition|) is an optional counter describing
% from which kind of enviroment should the numbering of these environments be
% inherited, and \meta{title}
% (e.g., |Theorem|) is
% the title that will be used to display this theorem environment. What
% differs from |\newtheorem| is that, when the following is written:
% \begin{quote}
% |\newtheoremrep{foobar}{Foobar}|
% \end{quote}
% then \emph{two} environments are defined: the \verb|foobar|
% environment, which behaves as if |\newtheorem| had been used, and the
% |foobarrep| environment, which results in the statement of this
% environment being repeated in the appendix.
%
% One interesting feature of \textsf{apxproof} is that in most
% situations, there is no need to use the |appendixproof| environment.
% Indeed, the |proof| \DescribeEnv{proof} environment is redefined by \textsf{apxproof} to
% automatically put the proof either in the main text (if it follows a
% regular theorem) or in the appendix (if it follows a repeated
% theorem).
% \begin{example}
% Assume we have first defined a repeated theorem environment |foobar| as
% above.
% We can now use this theorem environment, first for a regular theorem in
% the main text, then for a theorem repeated in the main text and in the
% appendix:
% \begin{quote}
% \begin{verbatim}
% \begin{foobar}
% This foobar is a regular one, in the main text.
% \end{foobar}
% \begin{proof}
% This is the proof of the regular foobar.
% \end{proof}
% \end{verbatim}
% \end{quote}
% We obtain:
% \begin{foobar}
% This foobar is a regular one, in the main text.
% \end{foobar}
% \begin{proof}
% This is the proof of the regular foobar.
% \end{proof}
% \begin{quote}
% \begin{verbatim}
% \begin{foobarrep}
% This foobar is repeated in the appendix.
% \end{foobarrep}
% \begin{proof}
% This is the proof of the repeated foobar.
% \end{proof}
% \end{verbatim}
% \end{quote}
% We now obtain:
% \begin{foobarrep}
% This foobar is repeated in the appendix.
% \end{foobarrep}
% \begin{proof}
%<*driver>
This is the proof of the repeated foobar.
%</driver>
% \end{proof}
% Note that, since |hyperref| is loaded, there is a hyperlink
% created from the statement of the theorem in the appendix to that in
% the main text.
% \end{example}
%
% When the proof is deferred to the appendix, it is common practice to
% add a proof sketch in the main text. \textsf{apxproof} defines a simple
% |proofsketch| environment for this purpose:
% \begin{quote}
% |\begin{proofsketch}|\DescribeEnv{proofsketch}\\
% \hspace*{1em}\dots\\
% |\end{proofsketch}|
% \end{quote}
% The proof sketch is typeset similarly to a proof, but is always in the
% main text. Similarly, an |inlineproof| \DescribeEnv{inlineproof}
% environment is provided so as to
% be able to have both a proof in the appendix (using the regualr |proof|
% environment, or alternatively the |appendixproof| environment) and a
% different proof in the main text (using the |inlineproof| environment).
% \begin{example} Here are simple examples of proof sketches and inline
% proofs:
% \begin{verbatim}
% \begin{proofsketch}
% This is a proof sketch.
% \end{proofsketch}
% \end{verbatim}
% \begin{proofsketch}
% This is a proof sketch.
% \end{proofsketch}
% \begin{verbatim}
% \begin{inlineproof}
% This is an inline proof.
% \end{inlineproof}
% \end{verbatim}
% \begin{inlineproof}
% This is an inline proof.
% \end{inlineproof}
% \end{example}
% 
% \subsection{Bibliography}
% \textsf{apxproof} automatically adds a bibliography in the appendix
% with only the references cited in the appendix material. This allows for a
% clean separation of references used solely in the main text, and those
% used in the appendix.
% \begin{example}
% Assume we have citations both in the main text and in the appendix.
% \begin{verbatim}
% This is a citation in the main text~\cite{lamport86}.
% \begin{toappendix}
% This is a citation in the appendix~\cite{proofsAreHard}.
% \end{toappendix}
% \end{verbatim}
% This is a citation in the main text~\cite{lamport86}.
% \begin{toappendix}
%<*driver>
This is a citation in the appendix~\cite{proofsAreHard}.
%</driver>
% \end{toappendix}
% \end{example}
% The bibliography in the appendix can use
% a different style and heading than the bibliography in the main text (and, by
% default, it does). See
% Section~\ref{sec:customization} for how to configure the appearance of
% that bibliography.
% \subsection{Mode}
% An optional \meta{mode} can be specified when loading the package:
% \begin{quote}|\usepackage[appendix=|\meta{mode}|]{apxproof}|\end{quote}
% \meta{mode} can take one of the following three values:
% \begin{description}
% \item[|append|] This is the default.
% Appendix material gathered by \textsf{apxproof} is appended to
% the main text.
% \item[|inline|] In this mode, \textsf{apxproof} simply inline the
% content along with the main text.
% \item[|strip|] This mode functions similarly to |append| except that
% the appendix is not appended at the end of the document. All appendix
% material is therefore removed.
% \end{description}
%
% \subsection{Customization}
% \label{sec:customization}
% \textsf{apxproof} provides a few macros that can be redefined (using
% |\renewcommand|) to customize the appearance of the appendix:
% \begin{description}
% \item[\textbackslash|appendixsectionformat|\marg{number}\marg{title}]\DescribeMacro{\appendixsectionformat} is a macro
% that indicates how to format the section titles in the Appendix, given
% the number and title of the section in the main text. By
% default, they appear as ``Proofs for Section~\meta{number}
% (\meta{title})''.
% \item[\textbackslash|appendixrefname|]\DescribeMacro{\appendixrefname} contains the heading that is displayed before
% the bibliography. By default, this is ``References for the
% Appendix''.
% \item[\textbackslash|appendixbibliographystyle|]\DescribeMacro{\appendixbibliographystyle} contains the |.bst| bibliography
% style that is used in the bibliography in appendix. By default, this is
% |alpha|.
% \item[\textbackslash|appendixbibliographyprelim|]\DescribeMacro{\appendixbibliographyprelim} contains arbitrary code that is executed
% just before the production of the bibliography in appendix, which can
% be used to configure the way it is displayed.
% \end{description}
%
% \subsection{Advanced Commands}
% We now describe a few advanced macros and environments, whose usage is limited to
% special cases:
% \begin{description}
% \item[|nestedproof|]\DescribeEnv{nestedproof} is an environment that
% can be used within a |proof| environment deferred in the appendix; this
% is required because, for technical reasons, no |proof| environment can
% be nested within a deferred |proof| environment.
% \item[\textbackslash|noproofinappendix|]\DescribeMacro{\noproofinappendix}
% can be used inside repeated theorems that are not followed by a
% |proof| or |appendixproof| theorem; the point is to ensure that a further
% |proof| environment cannot be mistakenly understood as a proof of the repeated
% theorem. It should not be needed in most situations as
% \textsf{apxproof} tries figuring out when a proof follows a repeated
% theorem automatically, but may occasionally be needed in complex
% scenarios.
% \item[\textbackslash|nosectionappendix|]\DescribeMacro{\nosectionappendix}
% is to be used inside a section that \emph{does} contain appendix material, but
% for which a section in the appendix should not be created. This should
% be rarely needed. When this command is present, appendix material is
% appended to the end of the previously created section.
% \end{description}
% \section{Supported Document Classes}
% Because \textsf{apxproof} modifies sectioning commands, bibliographies,
% and proofs, it may not work straight away with arbitrary document classes.
% It has currently been tested with and is supported for the following
% document classes:
% \begin{itemize}
% \item \LaTeX{} standard document classes (e.g., |article.cls|)
% \item \href{https://www.ctan.org/pkg/koma-script}{KOMA-Script}
% (e.g., |scrartcl.cls|)
% \item \href{https://www.acm.org/publications/proceedings-template}{ACM
% SIG Proceedings} (e.g., |sig-alternate.cls|)
% \item \href{https://www.springer.com/computer/lncs/lncs+authors}{
% Springer's Lecture Notes in Computer Science} (e.g.,
% |llncs.cls|)
% \item
% \href{https://www.dagstuhl.de/en/publications/lipics}{Schlo\ss{}
% Dagstuhl's Leibniz International Proceedings in Informatics} (e.g.,
% |lipics.cls|)
% \end{itemize}
% Other classes may work out of the box. Adding support for specific
% classes is possible and can be requested from the
% author of this package.
% \section{Known Issues and Limitations}
% We report here some issues we are currently aware of:
% \begin{itemize}
% \item When using \textsf{hyperref}, the appendix in the bibliography is
% not hyperlinked. This is to avoid possible issues with multiply defined
% bibliography entries.
% \item |appendixproof|, |proof|, |toappendix| environments cannot be nested. This is a limitation of
% the \textsf{fancyvrb} package that \textsf{apxproof} relies on. Note
% the existence of the |nestedproof| environment for nested proofs.
% \item \textsf{apxproof} is incompatible with a separate use of the
% \textsf{fancyvrb} package. This is because \textsf{apxproof} redefines
% some internal mechanisms of \textsf{fancyvrb}.
% \end{itemize}
%
% Issues not listed here should be reported to the author.
%
% \section{License}
% Copyright \textcopyright{} 2016 by Pierre Senellart.
% 
% 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
% \url{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.
% 
% \section{Contact}
% \begin{itemize}
% \item \url{https://github.com/PierreSenellart/apxproof}
% \item 
% Pierre Senellart
% \href{mailto:pierre@senellart.com}{<pierre@senellart.com>}
% \end{itemize}
% Bug reports and feature requests should
% preferably be submitted through the \emph{Issues} feature of GitHub.
%
% \section{Acknowledgments}
% Thanks to Antoine Amarilli for feedback and proofreading. 
%
% \StopEventually{
%   \PrintChanges
%   \PrintIndex
% }
% 
% \section{Implementation}
% We now describe the entire code of the package, in a literate programming
% fashion. Throughout the package, we use the |axp@| prefix to identify
% local macros and environment names, which are not meant to be used by the final
% user.
% \subsection{Dependencies}
% We first load a few package dependencies:
% \begin{itemize}
% \item \textsf{bibunits} to add a second bibliography for the appendix
% material.
%    \begin{macrocode}
\RequirePackage{bibunits}
%    \end{macrocode}
% \item \textsf{environ} to easily define the repeated theorem
% environments.
%    \begin{macrocode}
\RequirePackage{environ}
%    \end{macrocode}
% \item \textsf{etoolbox} to define simple toggles.
%    \begin{macrocode}
\RequirePackage{etoolbox}
%    \end{macrocode}
% \item \textsf{fancyvrb} for the bulk of the work of exporting appendix
% material in an auxiliary file.
%    \begin{macrocode}
\RequirePackage{fancyvrb}
%    \end{macrocode}
% \item \textsf{ifthen} for easier comparison of character strings.
%    \begin{macrocode}
\RequirePackage{ifthen}
%    \end{macrocode}
% \item \textsf{kvoptions} to manage options passed to the package.
%    \begin{macrocode}
\RequirePackage{kvoptions}
%    \end{macrocode}
% \item \textsf{amsthm} for its |\newteorem| macro.
% Some document classes (e.g., \textsf{lipics})
% preload \textsf{amsthm}: this is fine, |\RequirePackage{amsthm}|
% will simply have no effect. On the other hand, some other document
% classes (e.g., \textsf{llncs} or \textsf{sig-alternate}) define a
% |proof| environment that conflicts with \textsf{amsthm}, so we have to
% undefine this environment before loading \textsf{amsthm}.
%    \begin{macrocode}
\@ifpackageloaded{amsthm}{
  }{
    \let\proof\undefined
    \let\endproof\undefined
  }
\RequirePackage{amsthm}
%    \end{macrocode}
% \end{itemize}
% \subsection{Option Processing}
% Many names throughout the package use an arobase (|@|) to avoid name
% conflict with user-defined names. To simplify the compilation of the
% documentation, we simply make it a regular character in all the rest.
%    \begin{macrocode}
\makeatletter
%    \end{macrocode}
% \begin{macro}{\axp@appendix}
% We setup the processing of options using \textsf{keyval} facilities;
% the only declared option is named |appendix|, with a default value of
% |append|:
%    \begin{macrocode}
\SetupKeyvalOptions{
  family=axp,
  prefix=axp@
}
\DeclareStringOption[append]{appendix}
\ProcessLocalKeyvalOptions*
%    \end{macrocode}
% \end{macro}
% We check that the value of the |appendix| option is valid, and add a
% message to the compilation log.
%    \begin{macrocode}
\ifthenelse{\equal{\axp@appendix}{append}}{
  \message{apxproof: Appendix material appended to the document}
}{\ifthenelse{\equal{\axp@appendix}{strip}}{
  \message{apxproof: Appendix material stripped}
}{\ifthenelse{\equal{\axp@appendix}{inline}}{
  \message{apxproof: Appendix material inlined within the document}
}{
  \errmessage{Error: unsupported option appendix=\axp@appendix for
  package apxproof}
}}}
%    \end{macrocode}
% \subsection{Macros Common to All Compilation Modes}
% \begin{macro}{\newtheoremrep}
% We define the high-level |\newtheoremrep| to have the same syntax as
% \textsf{amsthm}'s |\newtheorem|. For this purpose, we need a little
% trick to deal with the second optional argument, which is what
% |\@oparg| is used for. |\axp@newtheoremrep| is defined differently
% depending on the compilation mode
%    \begin{macrocode}
\newcommand\newtheoremrep[1]{%
  \@oparg{\axp@newtheoremrep{#1}}[]%
}
%    \end{macrocode}
% \end{macro}
% \begin{environment}{proofsketch}
% Simple |proofsketch| environment.
%    \begin{macrocode}
\newenvironment{proofsketch}
  {\vskip3pt\noindent\textit{Proof sketch.} \upshape}
  {\hfill\qed\vskip3pt}
%    \end{macrocode}
% \end{environment}  
% \begin{macro}{\thmhead}  
% \changes{v1.0.2}{2016/12/13}{Fix display of repeated theorem counter in
% some document classes}
% We redefine AMS-\LaTeX{}'s |\thmhead| to use a format where the
% repeated version of a theorem, using a theorem note, can look exactly
% like the original version of the theorem and its theorem counter.
%    \begin{macrocode}
\AtBeginDocument{%
  \def\thmhead#1#2#3{%
    \thmname{#1}\thmnumber{\@ifnotempty{#1}{ }\@upn{#2}}%
    \thmnote{ #3}}%
}
%    \end{macrocode}
% \end{macro}  
% \begin{macro}{\appendixrefname}
% \begin{macro}{\appendixbibliographystyle}
% \begin{macro}{\appendixbibliographyprelim}
% \begin{macro}{\appendixsectionformat}
% We provide sensible defaults for these three user-customizable macros.
% Even though they are only useful in append mode, we define them for
% all modes so that a |\renewcommand| works in all cases.
%    \begin{macrocode}
\newcommand{\appendixrefname}{References for the Appendix}
\newcommand{\appendixbibliographystyle}{alpha}
\newcommand{\appendixbibliographyprelim}{}
\newcommand{\appendixsectionformat}[2]{Proofs for Section~#1 (#2)}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% Finally, some class-specific behavior ensures that the theorems created by
% |\newtheoremrep| appear with the correct style.
% For now, only the styling for ACM document classes (e.g.,
% \textsf{sig-alternate}) needs to be adapted.  
%    \begin{macrocode}
\ifdefined\@acmtitlebox
  \newtheoremstyle{mystyle}
    {3pt}
    {3pt}
    {\itshape}
    {}
    {\scshape}
    {.}
    {.5em}
    {}
  \theoremstyle{mystyle}
\fi
%    \end{macrocode}
% \subsection{Inline Compilation Mode}
%    \begin{macrocode}
\ifthenelse{\equal{\axp@appendix}{inline}}{
%    \end{macrocode}
% \begin{macro}{\axp@newtheoremrep}
% In inline mode, |\axp@newtheoremrep| undefines the existing
% theorem environment if it has already been defined (e.g., by the
% document class), invokes |\newtheorem| and creates a repeated theorem
% environment that behaves exactly as the regular theorem environment.
%    \begin{macrocode}
  \def\axp@newtheoremrep#1[#2]#3{%
    \expandafter\let\csname #1\endcsname\undefined
    \expandafter\let\csname c@#1\endcsname\undefined
    \newtheorem{#1}[#2]{#3}%
    \NewEnviron{#1rep}[1][]{%
      \begin{#1}[##1]\BODY\end{#1}%
    }
  }
%    \end{macrocode}
% \end{macro}  
% \begin{environment}{inlineproof}
% \begin{environment}{nestedproof}
% \begin{environment}{appendixproof}
% In inline mode, these environments behave like the regular |proof|
% environment.
%    \begin{macrocode}
  \let\inlineproof\proof
  \let\endinlineproof\endproof
  \let\nestedproof\proof
  \let\endnestedproof\endproof
  \let\appendixproof\proof
  \let\endappendixproof\endproof
%    \end{macrocode}
% \end{environment}  
% \end{environment}  
% \end{environment}  
% \begin{environment}{toappendix}
% \begin{macro}{\noproofinappendix}
% \begin{macro}{\nosectionappendix}
% In inline mode, this environment and these macros are no-ops.  
%    \begin{macrocode}
  \newenvironment{toappendix}{}{}
  \let\noproofinappendix\relax
  \let\nosectionappendix\relax
%    \end{macrocode}
% \end{macro}
% \end{macro}  
% \end{environment}  
%    \begin{macrocode}
} 
%    \end{macrocode}
% \subsection{Append or Strip Compilation Modes}
%    \begin{macrocode}
{
%    \end{macrocode}
% We now deal with the case where \textsf{apxproof} really does something
% useful: either append the appendix material to the document, or strip
% it entirely.
% \bigskip
%    \subsubsection{Auxiliary File for the Appendix}  
% \begin{macro}{\axp@proofsfile}  
% We open a new auxiliary file, with extension |.axp|, where the appendix
% material will be dumped.  
%    \begin{macrocode}  
  \newwrite\axp@proofsfile
  \immediate\openout\axp@proofsfile=\jobname.axp
%    \end{macrocode}  
% \end{macro}  
% \begin{environment}{proof}
% \begin{macro}{\section}
% At the beginning of this file, we make |@| a regular character (since
% it will be used in several places for internal names) and reestablish the original definition of
% the |proof| environment and the |\section| macro.
%    \begin{macrocode}  
  \immediate\write\axp@proofsfile{%
    \noexpand\makeatletter
    \noexpand\let\noexpand\proof\noexpand\axp@oldproof
    \noexpand\let\noexpand\endproof\noexpand\endaxp@oldproof
    \noexpand\let\noexpand\section\noexpand\axp@oldsection
  }
%    \end{macrocode}  
% \end{macro}  
% \end{environment}  
% \begin{macro}{\FVB@VerbatimOut}  
% \begin{macro}{\FVE@VerbatimOut}  
% We modify the internal behavior of the \textsf{fancyvrb} package to
% write to the |\axp@proofsfile|, without closing it and re-opening it
% on every write.  
%    \begin{macrocode}  
  \def\FVB@VerbatimOut{%
    \@bsphack
    \begingroup
      \FV@UseKeyValues
      \FV@DefineWhiteSpace
      \def\FV@Space{\space}%
      \FV@DefineTabOut
      \def\FV@ProcessLine{\immediate\write\axp@proofsfile}%
      \let\FV@FontScanPrep\relax
      \let\@noligs\relax
      \FV@Scan}
  \def\FVE@VerbatimOut{\endgroup\@esphack}
%    \end{macrocode}  
% \end{macro}  
% \end{macro}  
% \begin{environment}{toappendix}
% The entire content of this environment is put in appendix,
% starting a new appendix section beforehand if needed.
%    \begin{macrocode}  
  \newenvironment{toappendix}
    {\axp@writesection\VerbatimOut}
    {\endVerbatimOut}
%    \end{macrocode}  
% \end{environment}
%    \subsubsection{Definition of New Theorems}  
% \begin{macro}{axp@seenreptheorem}
% Used to indicate whether a repeated theorem was just typeset, without
% its proof.
%    \begin{macrocode}  
  \newtoggle{axp@seenreptheorem}
%    \end{macrocode}  
% \end{macro}  
% \begin{macro}{axp@rpcounter}
% Sequentially incremented for every repeated theorem, used to create labels.
%    \begin{macrocode}  
  \newcounter{axp@rpcounter}
%    \end{macrocode}  
% \end{macro}  
% \begin{macro}{axp@newtheoremrep}
% When called with first argument |foobar|, we first undefine the existing
% |foobar| environment (and its counter) if it has already been defined (e.g., by the
% document class), then invoke |\newtheorem| for the regular version
% of the theorem |foobar| (patching the |\begin{foobar}| so as not to
% expect a proof in the appendix) and |\newtheorem*| for an internal version |axp@foobarrp| that
% will be used in the appendix to restate the existing theorem.
%    \begin{macrocode}  
  \def\axp@newtheoremrep#1[#2]#3{%
    \expandafter\let\csname #1\endcsname\undefined
    \expandafter\let\csname c@#1\endcsname\undefined
    \newtheorem{#1}[#2]{#3}%
    \expandafter\pretocmd\csname #1\endcsname{\noproofinappendix}{}{}%
    \newtheorem*{axp@#1rp}{#3}%
%    \end{macrocode}  
% We then define a |foobarrep| environment that increments the
% |axp@rpcounter| and typeset the regular |foobar| theorem with a label
% derived from the counter.    
%    \begin{macrocode}  
    \NewEnviron{#1rep}[1][]{%
      \addtocounter{axp@rpcounter}{1}%
      \begin{#1}[##1]\label{axp@r\roman{axp@rpcounter}}\BODY\end{#1}%
%    \end{macrocode}  
% We set the |axp@seenreptheorem| toggle to indicate that we are looking
% for the proof of the theorem, then store in a macro the content of the
% theorem's body.
%    \begin{macrocode}  
      \global\toggletrue{axp@seenreptheorem}%
      \global\expandafter\let\csname rplet\roman{axp@rpcounter}%
                             \endcsname
      \BODY
%    \end{macrocode}  
% Possibly after starting a new appendix section if needed, we typeset a
% repeated version of the theorem using the |axp@foobarrp| environment
% and a reference to the previously defined label.
% We ignore any use of |\label| in this environment to avoid multiply
% defined labels.
% \changes{v1.0.2}{2016/12/13}{Fix missing space between repeated theorem
% counter and theorem note}
%    \begin{macrocode}  
      \axp@writesection%
      \immediate\write\axp@proofsfile{%
        \noexpand\begin{axp@#1rp}
          [\noexpand\ref{axp@r\roman{axp@rpcounter}}%
           \@ifnotempty{##1}{ \noexpand##1}]%
          \noexpand\let\noexpand\label\noexpand\@gobble%
          \expandafter\noexpand\csname rplet\roman{axp@rpcounter}%
                               \endcsname
        \noexpand\end{axp@#1rp}
      }
    }
  }
%    \end{macrocode}  
% \end{macro}  
%    \subsubsection{Proof Environments}  
% \begin{environment}{axp@oldproof}
%   We save the definition of the existing |proof| environment.
%    \begin{macrocode}  
  \let\axp@oldproof\proof
  \let\endaxp@oldproof\endproof
%    \end{macrocode}  
% \end{environment}
% \begin{macro}{\noproofinappendix}
%   Utility macro that toggles |axp@seenreptheorem| to false.
%    \begin{macrocode}  
  \newcommand\noproofinappendix{%
    \global\togglefalse{axp@seenreptheorem}%
  }
%    \end{macrocode}  
% \end{macro}
% \begin{environment}{appendixproof}
% We dump the content of this in appendix, within an original |proof|
% environment, possibly after creating a new appendix section.
%    \begin{macrocode}  
  \newenvironment{appendixproof}
    {%
      \axp@writesection
      \immediate\write\axp@proofsfile{%
        \noexpand\begin{axp@oldproof}%
      }%
      \VerbatimOut
    }
    {%
      \endVerbatimOut
      \immediate\write\axp@proofsfile{%
        \noexpand\end{axp@oldproof}%
      }%
      \noproofinappendix
    }
%    \end{macrocode}  
% \end{environment}
% \begin{environment}{proof}
% This environment either puts the proof in appendix, if we are after a repeated
% theorem without its proof, or inlines it otherwise.    
%    \begin{macrocode}  
  \renewenvironment{proof}
    {%
      \iftoggle{axp@seenreptheorem}{%
        \appendixproof
      }{%
        \axp@oldproof
      }%
    }
    {%
      \iftoggle{axp@seenreptheorem}{%
        \endappendixproof
      }{%
        \endaxp@oldproof
      }%
    }
%    \end{macrocode}  
% \end{environment}
% \begin{environment}{inlineproof}
% \begin{environment}{nestedproof}
% These two environments are synonyms for the original |proof|
% environment.    
%    \begin{macrocode}  
  \let\inlineproof\axp@oldproof
  \let\endinlineproof\endaxp@oldproof
  \let\nestedproof\axp@oldproof
  \let\endnestedproof\endaxp@oldproof
%    \end{macrocode}  
% \end{environment}
% \end{environment}
%    \subsubsection{Section Management}  
% \begin{macro}{axp@seccounter}
% Sequentially incremented for every section, used to create labels.
%    \begin{macrocode}  
  \newcounter{axp@seccounter}
%    \end{macrocode}  
% \end{macro}  
% \begin{macro}{\axp@sectitle}
% Saves the title of the last encountered section.
%    \begin{macrocode}  
  \def\axp@sectitle{}
%    \end{macrocode}  
% \end{macro}  
% \begin{macro}{\axp@section}  
% \begin{macro}{\axp@@ssection}  
% \begin{macro}{\axp@@section}  
% This command behaves similarly to |\axp@oldsection|, except that it first
% tests whether a |\section| follows, and if so, does not produce
% anything. This is useful to avoid producing empty sections in the
% appendix. As usual, we have to process starred and unstarred version
% separately.
%    \begin{macrocode}  
  \def\axp@section{\@ifstar\axp@@ssection\axp@@section}
  \def\axp@@ssection#1{%
    \@ifnextchar\section{}{\axp@oldsection*{#1}}%
  }
  \def\axp@@section#1{%
    \@ifnextchar\section{}{\axp@oldsection{#1}}%
  }
%    \end{macrocode}  
% \end{macro}  
% \end{macro}  
% \end{macro}  
% \begin{macro}{\axp@oldsection}
% \begin{macro}{\section}
% \begin{macro}{\@section}
% \begin{macro}{\@@section}
% We redefine the |\section| command to create a label based on
% |axp@seccounter| and to store its title in |\axp@sectitle|. Two definitions are necessary to cover the
% starred and unstarred use of |\section|, though most likely the former
% is not going to be used (since no section number will appear to refer
% to that section in the appendix).
%    \begin{macrocode}
  \let\axp@oldsection\section
  \def\section{\@ifstar\@section\@@section}
  \def\@section#1{%
    \global\edef\axp@sectitle{#1}%
    \axp@oldsection*{#1}%
    \addtocounter{axp@seccounter}{1}%
    \label{axp@s\roman{axp@seccounter}}%
  }
  \def\@@section#1{%
    \global\edef\axp@sectitle{#1}%
    \axp@oldsection{#1}%
    \addtocounter{axp@seccounter}{1}%
    \label{axp@s\roman{axp@seccounter}}%
  }
%    \end{macrocode}  
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \begin{macro}{\nosectionappendix}
% We remove the current section title, to indicate no section should be
% created in the appendix.
%    \begin{macrocode}  
  \newcommand{\nosectionappendix}{
    \global\def\axp@sectitle{}%
  }
%    \end{macrocode}  
% \end{macro}
% \begin{macro}{\axp@writesection}
% If |\axp@sectitle| is not empty, we create
% a new section in the appendix, referring to the main text section.
%    \begin{macrocode}  
  \newcommand\axp@writesection{%
    \ifx\axp@sectitle\@empty
    \else
      \immediate\write\axp@proofsfile{%
        \noexpand\def\noexpand\axp@tmp{%
          \noexpand\ref{axp@s\roman{axp@seccounter}}
        }
        \noexpand\axp@section{%
          \noexpand\appendixsectionformat{\protect\noexpand\axp@tmp}%
                                         {\axp@sectitle}%
        }%
      }%
      \nosectionappendix
    \fi
  }
%    \end{macrocode}  
% \end{macro}
%    \subsubsection{Append Compilation Mode}  
%    \begin{macrocode}  
  \ifthenelse{\equal{\axp@appendix}{append}}{
%    \end{macrocode}  
% \begin{macro}{\axp@oldbibliography}    
% \begin{macro}{\bibliography}    
% Thanks to \textsf{bibunits}'s |\defaultbibliography| macro, we set the appendix
% bibliography source to be the same as that of the main text.    
%    \begin{macrocode}  
    \let\axp@oldbibliography\bibliography
    \renewcommand\bibliography[1]{%
      \defaultbibliography{#1}%
      \axp@oldbibliography{#1}%
    }
%    \end{macrocode}  
% \end{macro}
% \end{macro}
% After the end of the main text, we add the appendix (on a new page, set
% in single-column mode) within a |bibunit| environment so as to typeset
% a separate bibliography for the appendix. There is an extra test to
% ensure an empty bibliography environment is not produced.
%    \begin{macrocode}
    \AtEndDocument{
      \clearpage\onecolumn\appendix
      \begin{bibunit}[\appendixbibliographystyle]
        \immediate\closeout\axp@proofsfile
        \input{\jobname.axp}
        \renewcommand{\refname}{\appendixrefname}
        \let\axp@oldthebibliography\thebibliography
        \renewcommand\thebibliography[1]{%
          \ifx\relax#1\relax\else\axp@oldthebibliography{#1}\fi}
        \appendixbibliographyprelim
        \putbib
      \end{bibunit}
    }
%    \end{macrocode}  
%    \begin{macrocode}  
  }{}
%    \end{macrocode}
% \subsubsection{Class-Specific Behavior}    
% We conclude with some class-specific behavior.
% \begin{macro}{\@getcl@ss}
% \begin{macro}{\@getclass}
% \begin{macro}{\@currentclass}
% We first use a little trick to store the document class in
% macro |\@currentclass|, from
% \url{http://tex.stackexchange.com/a/43541}.
%    \begin{macrocode}
  \def\@getcl@ss#1.cls#2\relax{\def\@currentclass{#1}}
  \def\@getclass{\expandafter\@getcl@ss\@filelist\relax}
  \@getclass
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \paragraph{ACM Document Classes}
%    \begin{macrocode}
  \ifdefined\@acmtitlebox
%    \end{macrocode}
% \begin{macro}{\thebibliography}
% \begin{macro}{\refname}
% \begin{macro}{\appendixrefname}
% The section title of the bibliography is in uppercase in these document
% classes. In addition, the |\thebibliography| macro hard-codes twice
% the section title, so we un-hardcode it so that it can be modified
% in the appendix.    
%    \begin{macrocode}
    \patchcmd{\thebibliography}{References}{\protect\refname}{}{}
    \patchcmd{\thebibliography}{References}{\protect\refname}{}{}
    \newcommand{\refname}{REFERENCES}
    \renewcommand{\appendixrefname}{REFERENCES FOR THE APPENDIX}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \begin{macro}{\section}
% \begin{macro}{\@@section}
% These document classes redefine |\section| in a weird way, adding
% the possibility of an optional argument. We redefine them in a sane
% way.    
%    \begin{macrocode}
    \def\section{\@ifstar\@section{\@dblarg{\@@section}}}
    \def\@@section[#1]#2{%
      \global\edef\axp@sectitle{#2}%
      \axp@oldsection{#2}%
      \addtocounter{axp@seccounter}{1}%
      \label{axp@s\roman{axp@seccounter}}%
    }
%    \end{macrocode}
% \end{macro}
% \end{macro}
%    \begin{macrocode}
  \fi
%    \end{macrocode}
% \paragraph{\textsf{lipcs}}
%    \begin{macrocode}
   \ifthenelse{\equal{\@currentclass}{lipics}}{
%    \end{macrocode}
% \begin{macro}{\appendixbibliographyprelim}  
% The default bibliography in the \textsf{lipics} document class
% formatting is not compatible with the
% \textsf{alpha} bibliography style. We fix this here.
%    \begin{macrocode}
    \renewcommand{\appendixbibliographyprelim}{%
      \global\let\@oldbiblabel\@biblabel
      \def\@biblabel{\hspace*{-2em}\small\@oldbiblabel}%
    }    
%    \end{macrocode}
% \end{macro}    
%    \begin{macrocode}
  }
%    \end{macrocode}
%    \begin{macrocode}
}
%    \end{macrocode}
% \Finale
% \bibliographystyle{plain}
% \bibliography{apxproof}
