% \iffalse meta-comment
%
% Copyright (C) 2018-2019 by Richard Grewe <r-g+tex@posteo.net>
% -------------------------------------------------------
% 
% This file may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either version 1.2
% 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.2 or later is part of all distributions of LaTeX 
% version 1999/12/01 or later.
%
% \fi
%
% \iffalse
%<*driver>
\ProvidesFile{rgltxdoc.dtx}
%</driver>
%<package>\NeedsTeXFormat{LaTeX2e}[1999/12/01]
%<package>\ProvidesPackage{rgltxdoc}
%<*package>
    [2019/01/05 v1 Common documentation code used for Richard Grewe's packages]
%</package>
%
%<*driver>
\documentclass{ltxdoc}
\RequirePackage{rgltxdoc}
\EnableCrossrefs
\CodelineIndex
\RecordChanges
\begin{document}
  \DocInput{rgltxdoc.dtx}
  \PrintChanges
  \PrintIndex
\end{document}
%</driver>
% \fi
%
% \CheckSum{0}
%
% \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}{2019/01/05}{Initial version}
%
% \GetFileInfo{rgltxdoc.dtx}
%
% \DoNotIndex{\newcommand,\newenvironment,\def,\gdef,\edef}
%
%
% \title{The \pkgname{rgltxdoc} package\thanks{This document
%   corresponds to \pkgname{rgltxdoc}~\fileversion, dated \filedate.
%   The package is available online at
%   \url{http://www.ctan.org/pkg/rgltxdoc} and
%   \url{https://github.com/Ri-Ga/rgltxdoc}.}}
% \author{Richard Grewe\\ \texttt{r-g+tex@posteo.net}}
%
% \maketitle
%
% \section{Introduction}
%
% This package combines several other packages and defines additional
% macros and environments for the purpose of documenting LaTeX code.
% The package mainly serves the purpose of combining the preferences
% used in the author's package documentations. However, others can
% use the package as well. Compatibility between versions cannot be
% guaranteed, however.
%
% \StopEventually{}
%\iffalse
%<*package>
%\fi
%
% \section{Basic Dependencies}
%
% Generally, the documentation can be compiled with \hologo{pdfLaTeX}
% and with \hologo{LuaLaTeX}. Other processors are untested. There is no
% assertion as to how close the \hologo{pdfLaTeX} and \hologo{LuaLaTeX}
% results are to each other.
%    \begin{macrocode}
\RequirePackage{ifluatex}
%    \end{macrocode}
% The \pkgname{etoolbox} package is used to simplify some of the
% package's code.
%    \begin{macrocode}
\RequirePackage{etoolbox}
%    \end{macrocode}
%
% \section{Documentation Input}
%
% The documentation is expected to be written in UTF-8 and in US-english
% language.
%    \begin{macrocode}
\ifbool{luatex}{
  \RequirePackage[utf8]{luainputenc}
  \RequirePackage{polyglossia}
  \setmainlanguage[variant=american]{english}
}{
  \RequirePackage[utf8]{inputenc}
  \RequirePackage[english]{babel}
}
%    \end{macrocode}
%
% \section{General Appearance}
%
% Code in this section determines the general appearance of
% documentation text and is not specific to documenting \hologo{LaTeX}
% code.
%
% \subsection{Page Layout}
%
% For the page layout, A4 is used for the paper size.
% Border correction established wider left margins for typesetting long
% macro names.
% The |DIV| value is tuned to make the lines wide enough to support
% at least 72~characters in the package documentation code.
%    \begin{macrocode}
\RequirePackage[a4paper,twoside=false]{geometry}
\RequirePackage[DIV=9,BCOR=2.25cm]{typearea}
%    \end{macrocode}
%
% \subsection{Fonts}
%
% For the font, Latin Modern is used.
% Particularly, a light version of the typewriter font is used, such
% that highlighting in listings is possible via a bold font series.
%    \begin{macrocode}
\ifbool{luatex}{
  \RequirePackage{fontspec}
  \setmainfont[SmallCapsFont={* Caps}]{Latin Modern Roman}
  \setsansfont{Latin Modern Sans}
  \setmonofont[Scale=MatchLowercase,
               SmallCapsFont={Latin Modern Mono Caps}]
    {Latin Modern Mono Light}
}{
  \RequirePackage[T1]{fontenc}
  \RequirePackage[lighttt]{lmodern}
%    \end{macrocode}
% With just the above code, a construct like |\cs{foo\meta{bar}}| for
% documenting parameter-dependent macro names fails due to missing
% fonts.  The following two lines fix this.  The first line ensures that
% the typewriter font is loaded (via an |\hbox| with typewriter text
% that is not actually displayed) and the second line declares the
% required font shape (see
% \url{https://tex.stackexchange.com/questions/234003/italic-font-in-lmodern-lighttt}).
%    \begin{macrocode}
  \bgroup\setbox\z@\hbox{\ttfamily ignore}\egroup
  \DeclareFontShape{T1}{lmtt}{m}{it}{<->sub*lmtt/m/sl}{}
}
%    \end{macrocode}
% Finally, \pkgname{microtype} is used for small font improvements.
%    \begin{macrocode}
\RequirePackage{microtype}
%    \end{macrocode}
% We simplify quoting names through the \pkgname{csquotes} package and
% register |"| to produce double opening/closing quotation marks.
%    \begin{macrocode}
\RequirePackage{csquotes}
\MakeOuterQuote{"}
%    \end{macrocode}
%
% \subsection{Document Structure}
%
% For the most part, documentations are structured as usual, through a
% title as well as sections and sub-sections and so forth.
% The following two packages improve the possibilities for using lists
% in documentation and visually improve the index through a two-column
% layout.
%    \begin{macrocode}
\RequirePackage{enumitem}
\RequirePackage[columns=2]{idxlayout}
%    \end{macrocode}
%
% The \pkgname{cleveref} and \pkgname{varioref} packages shall be used
% for referencing structural entities, such as sections and figures.
% Hyperlinks are enabled through \pkgname{hypdoc}.
%    \begin{macrocode}
\RequirePackage{varioref}
\RequirePackage{hypdoc}
\RequirePackage[capitalise,noabbrev,nameinlink]{cleveref}
%    \end{macrocode}
%
%
% \section{Documenting Things}
%
% This package builds on the \pkgname{doc} package for several
% documentation macros, such as |\marg|, |\oarg|, and |\meta|.
%    \begin{macrocode}
\RequirePackage{doc}
%    \end{macrocode}
%
% \subsection{Macros and Environments}\label{sec:MacrosEnvs}
%
% The main macros here, |\NiceDescribeMacro| and |\NiceDescribeEnv|, are
% references to |\DescribeMacro| and |\DescribeEnv| of the \pkgname{doc}
% package, with which they share the purpose.
% The main difference is the appearance in that the "nice" macros
% include the argument list.
%
% \NiceDescribeMacros{2}
%   {\NiceDescribeMacro}{\oarg{idx}\marg{macro}\marg{parameters}}
%   {\NiceDescribeMacros}{\marg{n}\oarg{idx$_1$}\marg{macro$_1$}\marg{params$_1$}\ldots\oarg{idx$_n$}\marg{macro$_n$}\marg{params$_n$}}
% These macros produce a description header for a single macro or,
% respectively, for multiple macros.
% The above two lines are an example of such a description header, which
% is produced by the following code:
% \begin{lstlisting}
% \NiceDescribeMacros{2}
%   {\NiceDescribeMacro}{\oarg{idx}\marg{macro}\marg{parameters}}
%   {\NiceDescribeMacros}{\marg{n}
%     \oarg{idx$_1$}\marg{macro$_1$}\marg{params$_1$}\ldots
%     \oarg{idx$_n$}\marg{macro$_n$}\marg{params$_n$}}
% \end{lstlisting}
% The arguments to the macro are described below:
% \begin{KeyValTable}{ArgDesc}
% \Row{arg=\meta{n},
%   desc={This argument specifies the number of macros to be
%   described.}}
% \Row{arg=\pbox[t]{\linewidth}{\meta{macro},\\\meta{macro$_1$},\ldots,\\\meta{macro$_n$}},
%   desc={These arguments specify the macros for which a description
%     header shall be produced.}}
% \Row{arg=\pbox[t]{\linewidth}{\meta{parameters},\\\meta{params$_1$},\ldots,\\\meta{params$_n$}},
%   desc={These arguments take the sequence that specifies all optional
%     and mandatory arguments of the respective \meta{macro}.
%     Typically, these would be sequences of \cs{oarg} and \cs{marg}
%     instances.}}
% \Row{arg=\pbox[t]{\linewidth}{\meta{idx},\\\meta{idx$_1$},\ldots,\\\meta{idx$_N$}},
%   desc={These optional arguments arguments specify which index entries
%     shall be documented, if they differ from the respective
%     \meta{macro} parameters. This, for instance allows \meta{macro} to
%     be "\texttt{\cs{foo}(*)}" whereas the \meta{idx} parameter could be
%     "\texttt{\cs{foo},\cs{foo}*}".}}
% \end{KeyValTable}
%
% \NiceDescribeMacros{2}
%   {\NiceDescribeEnv}{\oarg{idx}\marg{environment}\marg{parameters}}
%   {\NiceDescribeEnvs}{\marg{n}\oarg{idx$_1$}\marg{env$_1$}\marg{params$_1$}\ldots\oarg{idx$_n$}\marg{env$_n$}\marg{params$_n$}}
% These macros are the counterparts of |\NiceDescribeMacro| and,
% respectively, |\NiceDescribeMacros| when it comes to \hologo{LaTeX}
% environments.  The \meta{environment} (resp.\ \meta{env$_1$} to
% \meta{env$_n$}) parameters are the names of the respective environments.
% A usage example can be found in the implementation part of
% \vref{sec:KeysValues:impl}.
%
% \NiceDescribeMacros{2}
%   {\NiceDescribeCounte}{\oarg{idx}\marg{counter}\marg{qualifiers}}
%   {\NiceDescribeCounters}{\marg{n}\oarg{idx$_1$}\marg{ctr$_1$}\marg{qual$_1$}\ldots\oarg{idx$_n$}\marg{ctr$_n$}\marg{qual$_n$}}
% These macros are analogous to the above macros, but aimed for
% documenting \hologo{LaTeX} counters.
%
% \NiceDescribeMacro{\NewNiceDescription}{\marg{type}\marg{efmt}\marg{afmt}\marg{icmd}}
% This macro is used internally for defining the above macros and can be
% used for defining new types of entity descriptions. The following
% table describes the arguments of the macro.
% \begin{KeyValTable}{ArgDesc}
% \Row{arg=\meta{type},
%   desc={The \meta{type} argument is the name of the type of entities.}}
% \Row{arg=\meta{efmt},
%   desc={The \meta{efmt} argument is \hologo{TeX} code that formats the
%     entities in the margin. It can -- and should -- reference the
%     positional parameter |\#1|, through which it is passed the name of
%     the entities.}}
% \Row{arg=\meta{afmt},
%   desc={The \meta{afmt} argument is \hologo{TeX} code that formats the
%     arguments or qualifiers of the entities in the body of the
%     documentation. Analogous to \meta{efmt}, also \meta{afmt} receives
%     the arguments/qualifiers through the positional parameter |\#1|.}}
% \Row{arg=\meta{icmd},
%   desc={The \meta{icmd} argument is \hologo{TeX} code that adds a
%     usage entry for the entity to the index. It takes one argument,
%     through which \meta{icmd} is passed the entity name.}}
% \end{KeyValTable}
% A usage example for |\NewNiceDescription| can be found in the
% implementation below.
% 
%
% \paragraph{Implementation}
%
% \begin{macro}{\NewNiceDescription}
% The |\NewNiceDescription|\marg{type}\marg{efmt}\marg{afmt}\marg{icmd}
% macro defines the \cs{NiceDescribe\meta{type}} and
% \cs{NiceDescribe\meta{type}s} macros and saves the \meta{efmt} and
% \meta{afmt} parameters for use by \cs{NiceDescribe\meta{type}s}.
%    \begin{macrocode}
\newcommand\NewNiceDescription[4]{%
  \expandafter\newcommand\csname NiceDescribe#1\endcsname{%
    \csname NiceDescribe#1s\endcsname{1}}%
  \expandafter\newcommand\csname NiceDescribe#1s\endcsname{%
    \rgltxdoc@Desc
      {\csuse{rgltxdoc@@efmt@#1}}
      {\csuse{rgltxdoc@@afmt@#1}}
      {#4}}%
  \csdef{rgltxdoc@@efmt@#1}##1{#2}%
  \csdef{rgltxdoc@@afmt@#1}##1{#3}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\NiceDescribeMacro}
% \begin{macro}{\NiceDescribeMacros}
% Macro names are formatted detokenized through |\string|.
% Arguments are formatted as is.
% For the index, |\SpecialUsageIndex| of the \pkgname{doc} package is
% used.
%    \begin{macrocode}
\NewNiceDescription{Macro}{\string#1}{#1}{\SpecialUsageIndex}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \begin{macro}{\NiceDescribeEnv}
% \begin{macro}{\NiceDescribeEnvs}
% Environment names are formatted with a gray |\begin| and |\end|.
% The arguments of environments are formatted as is.
% For the index, |\SpecialEnvIndex| of the \pkgname{doc} package is
% used.
%    \begin{macrocode}
\NewNiceDescription{Env}
  {\textcolor{gray}{\cs{begin}}\cmarg{#1}\\
   \textcolor{gray}{\cs{end}}\cmarg{#1}}
  {#1}{\SpecialEnvIndex}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \begin{macro}{\NiceDescribeCounter}
% \begin{macro}{\NiceDescribeCounters}
% Counter names are formatted as is. Arguments or qualifiers should
% usually not be present for counters, but if provided, they would be
% formatted as is.
% The index entry is produced through |\SpecialOtherIndex| (see its
% documentation below).
%    \begin{macrocode}
\NewNiceDescription{Counter}{#1}{#1}
                   {\SpecialOtherIndex{counter}{counters}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \begin{macro}{\SpecialOtherIndex}
% The |\SpecialOtherIndex|\marg{type}\marg{types}\marg{name} macro
% adds an index entry of the given \meta{type} (with plural form
% \meta{types}) and given \meta{name}.
% The macro is a straightforward generalization of |\SpecialEnvIndex|.
%    \begin{macrocode}
\newcommand\SpecialOtherIndex[3]{\@bsphack
  \index{#3\actualchar{\protect\ttfamily#3}
    (#1)\encapchar usage}%
  \index{#2:\levelchar#3\actualchar
    {\protect\ttfamily#3}\encapchar usage}\@esphack}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\rgltxdoc@DescRec}
% The
% |\rgltxdoc@Desc|\marg{efmt}\marg{afmt}\marg{icmd}\marg{n}\oarg{idx}\marg{entity}\marg{args}
% macro formats a description header for \meta{n} entities, of which the
% first are specified through \meta{idx}, \meta{entity}, and
% \meta{args}.
% The margin parts are formatted through the \meta{efmt}\marg{entity}
% macro, the parts in the text body through the \meta{afmt}\marg{args}
% macro. The index entries are created through the
% \meta{icmd}\marg{idx} macro.
% In its implementation, |\rgltxdoc@Desc| builds on |\pbox| from the
% \pkgname{pbox} package. It uses |\rgltxdoc@DescRec| and
% |\rgltxdoc@DescRec@i| (both with the same argument lists) for the
% parsing of arguments and for recursively grabbing the arguments for
% the \meta{n} entities.
% At first, |\rgltxdoc@Desc| creates some vertical space above a
% list of description headers. Afterwards it starts the recursion.
%    \begin{macrocode}
\RequirePackage{pbox}
\newcommand\rgltxdoc@Desc{\medskip\par\noindent\rgltxdoc@DescRec}
\newcommand\rgltxdoc@DescRec[4]{%
  \@ifnextchar[%]
    {\rgltxdoc@DescRec@i{#1}{#2}{#3}{#4}}%
    {\rgltxdoc@DescRec@i{#1}{#2}{#3}{#4}[]}}
\def\rgltxdoc@DescRec@i#1#2#3#4[#5]#6#7{%
%    \end{macrocode}
% The following code creates the "margin" text (more precisely, a box to
% the left of the text) and the \meta{args} next to it.
%    \begin{macrocode}
  \leavevmode\null\hbox to\z@{\hss%
    \pbox[t]{3\marginparwidth}{\ttfamily #1{#6}}%
%    \end{macrocode}
% If there is no \meta{args}, then the margin part is moved towards the
% left by a |\quad|.
%    \begin{macrocode}
    \ifstrempty{#7}{\quad}{}}%
  #2{#7}\relax
%    \end{macrocode}
% Next, the index entries are created, through the comma-separated
% \meta{idx} if this optional argument is given.
%    \begin{macrocode}
  \ifstrempty{#5}%
    {#3{#6}}%
    {\forcsvlist{#3}{#5}}%
%    \end{macrocode}
% Next, we check whether $\meta{n}>1$ and recurse, after a line break,
% if this is satisfied.
%    \begin{macrocode}
  \ifnumgreater{#4}{1}%
    {\\\rgltxdoc@DescRec{#1}{#2}{#3}{#4-1}}%
%    \end{macrocode}
% Finally, the following code ends a list of description headers, taking
% into account that an empty \meta{args} allows the documentation text
% to already start in the same line as the "margin" text.
%    \begin{macrocode}
    {\ifstrempty{#7}{}{\smallskip\par\noindent}\ignorespaces}}
%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Arguments, Keys, and Values}
%
% Longer descriptions of macro/environment arguments as well as of keys
% (in key-value lists) and special values can be typeset in tables.
% For a common appearance, the \pkgname{keyvaltable} package is used.
%
% \NiceDescribeEnv{KeyValTable}{\cmarg{KeyDesc}}
% This table is used for describing keys in key-value lists. It has
% three columns: |key|, |desc|, and |default|. The former two have the
% obvious meaning. The latter allows for specifying a default value for
% the key that is used when the key is not provided.
%
% \NiceDescribeEnv{KeyValTable}{\cmarg{ValDesc}}
% This table is used for describing special values (constants). It has
% two columns, |val| and |desc|, with their obvious meaning.
% 
% \NiceDescribeEnv{KeyValTable}{\cmarg{ArgDesc}}
% This table is used for describing arguments of macros and environments
% in a structured fashion. It has two columns, |arg| and |desc|.
% Examples of this kind of table can be found in \cref{sec:MacrosEnvs}. 
% 
% \paragraph{Implementation}\label{sec:KeysValues:impl}
%
% The \pkgname{keyvaltable} package is used for creating the tables that
% document keys, values etc.
%    \begin{macrocode}
\RequirePackage{keyvaltable}
\kvtSet{headbg=black!10,rowbg=white..black!5}
%    \end{macrocode}
% The following code defines the table types. The code should be
% self-explanatory in terms of which columns exist and what their
% alignment and purpose is.
%    \begin{macrocode}
\NewKeyValTable{KeyDesc}{%
  key:  align=l,    format=\texttt, head=\textbf{Key};
  desc: align=X,    head=\textbf{Description and Possible Values};
  default: align=l, format=\texttt, head=\textbf{Default};
}
\NewKeyValTable[showhead=false]{ValDesc}{%
  val:  align=l,    format=\texttt, head=\textbf{Value};
  desc: align=X,                    head=\textbf{Description};
}
\NewKeyValTable[showhead=false]{ArgDesc}{%
  arg:  align=l, head=\textbf{Argument};
  desc: align=X, head=\textbf{Description};
}
%    \end{macrocode}
%
%
% \subsection{Individual Entities}
%
% \begin{macro}{\env}
% The |\env|\marg{environment} macro is the counterpart of |\cs| for
% environment names instead of command names.
%    \begin{macrocode}
\newcommand\env[1]{\texttt{#1}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pkgname}
% The |\pkgname|\meta{package-name} macro typesets package names in a
% uniform font (sans-serif). Moreover, the package checks whether the
% package actually exists, in order to identify embarrassing typos in
% the package name.
%    \begin{macrocode}
\newrobustcmd\pkgname[1]{%
  \IfFileExists{#1.sty}
    {\textsf{#1}}
    {\rgltxdoc@err{Package `#1' not found. Spelling?}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cmarg}
% \begin{macro}{\coarg}
% The |\cmarg|\marg{const-arg} and |\coarg|\marg{const-arg} macros are
% counterparts for |\marg| and |\oarg|. They format constant argument
% values, though.
%    \begin{macrocode}
\newcommand\cmarg[1]{\mbox{\texttt{\string{#1\string}}}}
\newcommand\coarg[1]{\mbox{\texttt{[#1]}}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% The following enables references to various \hologo{LaTeX} tools in
% the common formatting of their names.
%    \begin{macrocode}
\RequirePackage{hologo}
%    \end{macrocode}
%
%
% \section{Typesetting Examples}
%
% For typesetting examples, the \pkgname{showexpl} package is used.
% Some specific settings for the appearance of the example listings are
% defined and some auxiliary macros simplify special examples.
%
% Generally, code examples shall be typeset in one of two ways:
% \begin{enumerate}
% \item through \env{lstlisting} environments, if only code shall be
%   displayed but no visualization of the code's output;
% \item through \env{LTXexample} environments, if the code as well as its
%   output shall be displayed.
% \end{enumerate}
% Below follows an example of \env{LTXexample} that uses some of the
% features provided by \pkgname{rgltxdoc} on top of \pkgname{showexpl}:
% Labels/references and sections.
% \begin{LTXexample}
%   \section{Test}
%   \label{sec:test}
%   \cref{sec:test} has number~\ref{sec:test}.
% \end{LTXexample}
%
% The following code performs the setup for both (because
% \env{LTXexample} builds on \env{lstlisting}).
%    \begin{macrocode}
\RequirePackage{showexpl}
\lstset{%
  gobble=2,
  frame=trbl,
  backgroundcolor=\color{black!5!white},
  explpreset={%
    numbers=none, columns=flexible, basicstyle=\footnotesize\ttfamily},
  numbers=none, columns=flexible, basicstyle=\footnotesize\ttfamily,
  preset={\rgltxdoc@ExampleFix\rgltxdoc@SaveSecs\small\sffamily},
  overhang=2cm,
  pos=r,
  captionpos=b}
%    \end{macrocode}
% The following enables references to \env{LTXexample} and
% \env{lstlisting} environments through |\cref| and |\vref|.
%    \begin{macrocode}
\crefname{lstlisting}{Listing}{Listings}
%    \end{macrocode}
%
% The following adds the |morepreset| key to \env{listing} environments,
% to allow for extending |preset| code rather than overwriting it.
%    \begin{macrocode}
\lst@Key{morepreset}\relax{\appto\SX@preset{#1}}
%    \end{macrocode}
%
% \begin{macro}{\rgltxdoc@ExampleFix}
% The |\rgltxdoc@ExampleFix| macro performs some setup to enable, to
% some extent, functionality that \pkgname{showexpl} disables or does
% not implement. Concretely,
% \begin{itemize}
% \item the macro simulates labels and references, as long as labels are
%   only referenced after they have been defined (in \env{LTXexample}
%   environments, the normal label and ref mechanism is otherwise
%   disabled);
% \item the macro re-enables the default |\marginpar| macro, which is
%   disabled by \env{LTXexample} presumably due to its suboptimal
%   appearance; for the cases in which the appearance can be justified,
%   the macro is enabled.
% \end{itemize}
%    \begin{macrocode}
\newcommand\rgltxdoc@ExampleFix{%
%    \end{macrocode}
% The fake |\label|\oarg{type}\marg{label} macro takes the optional
% \meta{type}, as the \pkgname{cleveref} package defines it. The macro
% first saves the current label value in a global macro for basic
% |\ref|s. Then, for |\cref|s, the macro also stores the label's type,
% either from \meta{type} or from \pkgname{cleveref}'s routines.
%    \begin{macrocode}
  \renewcommand\label[2][]{%
    \global\csletcs{rgltxdoc@@lbl@##2}{@currentlabel}%
    \ifstrempty{##1}
      {\csxdef{rgltxdoc@@lbltype@##2}{\rgltxdoc@curlbltype}}
      {\csgdef{rgltxdoc@@lbltype@##2}{##1}}}%
%    \end{macrocode}
% The |\ref| and |\cref| macros simply use the values stored by
% |\label|. Note that the multitude of further \pkgname{cleveref} and
% \pkgname{varioref} macros, e.g., |\crefrange| are currently not
% implemented. They would need to be defined when there is actual
% demand for them.
%    \begin{macrocode}
  \def\ref##1{\csuse{rgltxdoc@@lbl@##1}}%
  \def\cref##1{%
    \csuse{cref@\csuse{rgltxdoc@@lbltype@##1}@name}~\ref{##1}}%
  \let\marginpar=\rgltxdoc@@marginpar
}
\let\rgltxdoc@@marginpar=\marginpar
%    \end{macrocode}
% The |\rgltxdoc@curlbltype| and |\rgltxdoc@curlbltype@i| macros are
% auxiliary macros for parsing the content of |\cref@currentlabel|, as set
% by the \pkgname{cleveref} package. The first bracketet value in the
% content is the label type we're interested in here.
% If there's no current label type, we silently use the empty string.
%    \begin{macrocode}
\def\rgltxdoc@curlbltype{%
  \@ifundefined{cref@currentlabel}{}
    {\expandafter\rgltxdoc@curlbltype@i\cref@currentlabel\@nil}}
\def\rgltxdoc@curlbltype@i[#1][#2][#3]#4\@nil{#1}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\rgltxdoc@SaveSecs}
% \begin{macro}{\rgltxdoc@RestoreSecs}
% The |\rgltxdoc@SaveSecs| macro saves the section counters and the
% |\rgltxdoc@RestoreSecs| macro restores the values of the section
% counters. This allows one to use sectioning commands in code examples
% without interfering with the section numbering in the documentation.
%    \begin{macrocode}
\newcommand\rgltxdoc@SaveSecs{%
  \@for\SC:=chapter,section,subsection,subsubsection\do{%
    \@ifundefined{c@\SC}{}
      {\csedef{rgltx@@ctr@\SC}{\the\value{\SC}}%
       \setcounter{\SC}{0}}}}
\newcommand\rgltxdoc@RestoreSecs{%
  \@for\SC:=chapter,section,subsection,subsubsection\do{%
    \@ifundefined{c@\SC}{}
      {\setcounter{\SC}{\csuse{rgltx@@ctr@\SC}}}}}
\patchcmd{\SX@resultInput}{\par}{\rgltxdoc@RestoreSecs\par}
  {}
  {\rgltxdoc@warn{Could not patch showexpl to reset section counters.}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \section{Shared Internal Code}
%
% \begin{macro}{\rgltxdoc@err}
% \begin{macro}{\rgltxdoc@warn}
% The |\rgltxdoc@err|\marg{error} macro raises the given \meta{error}.
% The |\rgltxdoc@warn|\marg{warning} macro raises the given
% \meta{warning}.
%    \begin{macrocode}
\newcommand\rgltxdoc@err[1]{%
  \PackageError{rgltxdoc}{#1}{}}
\newcommand\rgltxdoc@warn[1]{%
  \PackageWarning{rgltxdoc}{#1}{}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%\iffalse
%</package>
%\fi
% \Finale
\endinput
