%D \module
%D   [      file=t-ltcmds,
%D        version=2005.07.xx,
%D          title=\CONTEXT\ User Module,
%D       subtitle=\LaTeX\ compatibility command definitions,
%D         author=Brooks Moses,
%D           date=\currentdate,
%D      copyright={Brooks Moses; The LaTeX3 Project}]

%D This \ConTeXt\ module is part of the \LaTeX-compatibility
%D module set.  It provides \type{\newcommand} and related
%D definitions.

\usemodule[ltbase]
\unprotect

%D \section{Definitions}
%D
%D This reproduces a \type{ltdefns.dtx}.  (Some of this appears to
%D relate more to \type{t-lterr}, but the two files are interdependent
%D and it's simpler to retain the original organization.)  A number of
%D the commands are duplicates of \ConTeXt\ commands, and thus are
%D merely aliased rather than redefined.

%D \subsection{Initex Initializations}
%D
%D Prefix a number less than 10 with `0'.

% Used in ltclass, ltfsstrc and ltdirchk.

\def\two@digits#1{\ifnum#1<10 0\fi\number#1}

%D Display something on the terminal.

% Used in ltclass, ltdirchk, lterror, ltfiles, ltfinal, ltfssbas,
% ltfssini, ltidxglo, ltoutput, ltvers, ltxdoc, and various other
% non-kernel files.

\def\typeout#1{\begingroup\set@display@protect
    \immediate\write\@unused{#1}\endgroup}

%D A char to be used as new-line in output to files.

\newlinechar`\^^J

%D \subsection{Command Definitions}
%D
%D Types a message, asks the user to type in a command, and then either
%D executes it or assigns it to the optional argument.

\def\typein{%
  \let\@typein\relax
  \@testopt\@xtypein\@typein}

\def\@xtypein[#1]#2{%
  \typeout{#2}%
  \advance\endlinechar\@M
  \read\@inputcheck to#1%
  \advance\endlinechar-\@M
  \@typein}

%D \type{\@namedef} and \type{\@nameuse} are synonyms of \ConTeXt commands.

% Used in ltfiles, ltfssbas, ltfsstrc, ltmath, ltmiscen, ltoutenc, lttab,
% ltthm, and ltxref.

\let\@namedef\setvalue
\let\@nameuse\getvalue

%D \type{\@cons} has been moved to \type{t-ltcnts}.

% \@car is used in ltlogos, ltoutenc, and ltxref.  \@cdr is in ltxref.

\def\@car#1#2\@nil{#1}
\def\@cdr#1#2\@nil{#2}
\def\@carcube#1#2#3#4\@nil{#1#2#3}

%D \type{\@onlypreamble} adds its argument to the list of commands stored in
%D \type{\@preamblecmds} to be disabled after \type{starttext} (which was, of
%D course, originally \type{\begin{document}})  These commands are redefined
%D to generate \type{\@notprerr} at this point.

\def\@preamblecmds{}
\def\@onlypreamble#1{%
  \expandafter\gdef\expandafter\@preamblecmds\expandafter{%
       \@preamblecmds\do#1}}
\@onlypreamble\@onlypreamble
\@onlypreamble\@preamblecmds

%D Look ahead for a \type{*}. If present, reset \type{\l@ngrel@x} so that
%D the next definition, \type{#1}, will be non-long.

\def\@star@or@long#1{%
  \@ifstar
   {\let\l@ngrel@x\relax#1}%
   {\let\l@ngrel@x\long#1}}

%D This is either \type{\relax} or \type{\long} depending on whether the
%D \type{*}-form of a definition command is being executed.

\let\l@ngrel@x\relax

%D User level \type{\newcommand}.

\def\newcommand{\@star@or@long\new@command}

\def\new@command#1{%
  \@testopt{\@newcommand#1}0}

%D Handling arguments for \type{\newcommand}.

\def\@newcommand#1[#2]{%
  \kernel@ifnextchar[{\@xargdef#1[#2]}%
                {\@argdef#1[#2]}}

%D Define \type{#1} if it is definable.
%
%D Both here and in |\@xargdef| the replacement text is absorbed as
%D an argument because this removes any space-token that may appear
%D after the optional argument(s).   

\long\def\@argdef#1[#2]#3{%
   \@ifdefinable #1{\@yargdef#1\@ne{#2}{#3}}}

%D Handle the second optional argument.

\long\def\@xargdef#1[#2][#3]#4{%
  \@ifdefinable#1{%
%
%D Define the actual command to be:
%D \type{\def\foo{\@protected@testopt\foo\\foo{default}}}
%D where \type{\\foo} is a csname generated from applying \type{\csname}
%D and \type{\string} to \type{\foo}, i.e. the actual name contains a
%D backslash and therefore can't clash easily with exisiting command names.
%D ``Default'' is the contents of the second optional argument of
%D \type{(re)newcommand}.
%D
%D The \type{\aut@global} command below is only used in the autoload
%D format. If it is \type{\global} then a global definition will be made.
%
%<autoload>\aut@global
     \expandafter\def\expandafter#1\expandafter{%
          \expandafter
          \@protected@testopt
          \expandafter
          #1%
          \csname\string#1\endcsname
          {#3}}%
%
%D Now we define the internal macro ie \type{\\foo} which is supposed to
%D pick up all arguments (optional and mandatory).
%
       \expandafter\@yargdef
          \csname\string#1\endcsname
           \tw@
           {#2}%
           {#4}}}

%D We expect this to eventually use the \ConTeXt optional-argument
%D handling.
%D ### Make this better!

\long\def\@testopt#1#2{%
  \kernel@ifnextchar[{#1}{#1[{#2}]}}

%D I have no idea what's going on with the protected versions of stuff, 
%D and the name-use is likely to conflict badly with \ConTeXt's 
%D \type{\protect}, so for now it's aliased to a nonexistent command.

\let\@protected@testopt\ThisShouldNeverBeCalled

%D These generate a primitive argument specification, from a
%D \LaTeX\ \type{[} digit \type{]} form; in fact digit can be
%D anything such that \type{\number}~digit is single digit.

\long \def \@yargdef #1#2#3{%
  \ifx#2\tw@
    \def\reserved@b##11{[####1]}%
  \else
    \let\reserved@b\@gobble
  \fi
  \expandafter
    \@yargd@f \expandafter{\number #3}#1%
}

\long \def \@yargd@f#1#2{%
  \def \reserved@a ##1#1##2##{%
    \expandafter\def\expandafter#2\reserved@b ##1#1%
    }%
  \l@ngrel@x \reserved@a 0##1##2##3##4##5##6##7##8##9###1%
}

\long\def\@reargdef#1[#2]{%
  \@yargdef#1\@ne{#2}}

%D Check the command name is already used.  If not give an error
%D message. Then temporarily disable \type{\@ifdefinable} then call
%D \type{\newcommand}.

\def\renewcommand{\@star@or@long\renew@command}

\def\renew@command#1{%
  \begingroup \escapechar\m@ne\xdef\@gtempa{{\string#1}}\endgroup
  \expandafter\@ifundefined\@gtempa
     {\@latex@error{\noexpand#1undefined}\@ehc}%
     \relax
  \let\@ifdefinable\@rc@ifdefinable
  \new@command#1}

%D Test is user is allowed to define a command.

\long\def\@ifdefinable #1#2{%
      \edef\reserved@a{\expandafter\@gobble\string #1}%
     \@ifundefined\reserved@a
         {\edef\reserved@b{\expandafter\@carcube \reserved@a xxx\@nil}%
          \ifx \reserved@b\@qend \@notdefinable\else
            \ifx \reserved@a\@qrelax \@notdefinable\else
              #2%
            \fi
          \fi}%
         \@notdefinable}

%D Saved definition of |\@ifdefinable|.

\let\@@ifdefinable\@ifdefinable

%D Version of \type{\@ifdefinable} for use with \type{\renewcommand}.  Does
%D not do the check this time, but restores the normal definition.

\long\def\@rc@ifdefinable#1#2{%
  \let\@ifdefinable\@@ifdefinable
  #2}

%D \subsubection{Define a new user environment.}
%D
%D \type{#1} is the environment name. \type{#2} Grabs all the tokens up to
%D the first brace.  These will be any optional arguments. They are not
%D parsed at this point, but are just passed to \type{\@newenv} which
%D will eventually call \type{\newcommand}. Any optional arguments will
%D then be parsed by \type{\newcommand} as it defines the command that
%D executes the `begin code' of the environment.

\def\newenvironment{\@star@or@long\new@environment}

\def\new@environment#1{%
  \@testopt{\@newenva#1}0}

\def\@newenva#1[#2]{%
   \kernel@ifnextchar [{\@newenvb#1[#2]}{\@newenv{#1}{[#2]}}}

\def\@newenvb#1[#2][#3]{\@newenv{#1}{[#2][{#3}]}}

%D Redefine an environment.
%D For \type{\renewenvironment} disable \type{\@ifdefinable} and then call
%D \type{\newenvironment}.  It is OK to \type{\let} the argument to
%D \type{\relax} here as there should not be a \type{@temp}\ldots\ environment.
%D
%D [Note that we've redefined this to name the environment commands as
%D \type{\start#1} and \type{\stop#1}, rather than \LaTeX's usual versions!]

\def\renewenvironment{\@star@or@long\renew@environment}

\def\renew@environment#1{%
  \@ifundefined{start#1}%
     {\@latex@error{Environment #1 undefined}\@ehc
     }\relax
  \expandafter\let\csname start#1\endcsname\relax
  \expandafter\let\csname stop#1\endcsname\relax
  \new@environment{#1}}

%D The internal version of \type{\newenvironment}.
%D
%D Call \type{\newcommand} to define the begin-code for the environment.
%D \type{\def} is used for the end-code as it does not take arguments
%D (but may contain \type{\par}s).
%D
%D [Note that we've redefined this to name the environment commands as
%D \type{\start#1} and \type{\stop#1}, rather than \LaTeX's usual versions!]
%D
%D [It appears that \type{\start#1} is being \type{\let} to \type{\stop#1}
%D so that (by way of \type{\newcommand}) both get checked.

\long\def\@newenv#1#2#3#4{%
  \@ifundefined{start#1}%
    {\expandafter\let\csname start#1\expandafter\endcsname
                         \csname stop#1\endcsname}%
    \relax
  \expandafter\new@command
     \csname start#1\endcsname#2{#3}%
     \l@ngrel@x\expandafter\def\csname stop#1\endcsname{#4}}

%D And here's a different sort of allocation:
%D For example, \type{\newif\iffoo} creates \type{\footrue} and
%D \type{\foofalse} to go with \type{\iffoo}.
%D
%D [This is already defined in \ConTeXt, and need not be 
%D duplicated here.]

%D \type{\providecommand} takes the same arguments as \type{\newcommand}, but
%D discards them if \type{#1} is already defined, Otherwise it just acts like
%D \type{\newcommand}. This implementation currently leaves any discarded
%D definition in \type{\reserved@a} (and possibly \type{\\reserved@a}) this 
%D wastes a bit of space, but it will be reclaimed as soon as these 
%D scratch macros are redefined. 

\def\providecommand{\@star@or@long\provide@command}

\def\provide@command#1{%
  \begingroup
    \escapechar\m@ne\xdef\@gtempa{{\string#1}}%
  \endgroup
  \expandafter\@ifundefined\@gtempa
    {\def\reserved@a{\new@command#1}}%
    {\def\reserved@a{\renew@command\reserved@a}}%
   \reserved@a}%

%D \type{\CheckCommand} takes the same arguments as \type{\newcommand}. If
%D the command already exists, with the same definition, then nothing happens,
%D otherwise a warning is issued. Useful for checking the current state before
%D a macro package starts redefining things.  Currently two macros are
%D considered to have the same definition if they are the same except for
%D different default arguments.  That is, if the old definition was:
%D \type{\newcommand\xxx[2][a]{(#1)(#2)}} then
%D \type{\CheckCommand\xxx[2][b]{(#1)(#2)}} would \emph{not} generate a
%D warning, but, for instance \type{\CheckCommand\xxx[2]{(#1)(#2)}} would.

\def\CheckCommand{\@star@or@long\check@command}

\@onlypreamble\CheckCommand

\def\check@command#1#2#{\@check@c#1{#2}}
\@onlypreamble\check@command

%D \type{\CheckCommand} itself just grabs all the arguments we need,
%D without actually looking for \type{[} optional argument forms.  Now
%D define \type{\reserved@a}. If \type{\\reserved@a} is then defined, compare
%D it with the ``\type{\#1}' otherwise compare \type{\reserved@a} with
%D \type{#1}.

\long\def\@check@c#1#2#3{%
  \expandafter\let\csname\string\reserved@a\endcsname\relax
  \renew@command\reserved@a#2{#3}%
  \@ifundefined{\string\reserved@a}%
   {\@check@eq#1\reserved@a}%
   {\expandafter\@check@eq
           \csname\string#1\expandafter\endcsname
           \csname\string\reserved@a\endcsname}}
\@onlypreamble\@check@c

%D Complain if \type{#1} and \type{#2} are not \type{\ifx} equal.

\def\@check@eq#1#2{%
  \ifx#1#2\else
     \@latex@warning@no@line
               {Command \noexpand#1 has 
                changed.\MessageBreak
                Check if current package is valid}%
  \fi}
\@onlypreamble\@check@eq

%D The gobble macros already exist in \ConTeXt; we simply \type{\let}
%D them here.

%D The |\@gobble| macro is used to get rid of its argument.

\let\@gobble=\gobbleoneargument
\let\@gobbletwo=\gobbletwoarguments
\let\@gobblefour=\gobblefourarguments

%D Some argument-grabbers.

\let\@firstofone=\firstofoneargument
\let\@firstoftwo=\firstoftwoarguments
\let\@secondoftwo=\secondoftwoarguments

%D \type{\@iden} is another name for |\@firstofone| for compatibility reasons.

\let\@iden\@firstofone

%D Another grabber now used in the encoding specific section.

\let\@thirdofthree=\thirdofthreearguments

%D A macro to totally expand two arguments to another macro.

\def\@expandtwoargs#1#2#3{%
\edef\reserved@a{\noexpand#1{#2}{#3}}\reserved@a}

%D A category code 12 backslash.

\edef\@backslashchar{\expandafter\@gobble\string\\}

%D \subsection{Robust commands and protect}
%D
%D [For now, we simply are duplicating the \LaTeX\ protection 
%D mechanism, but calling it \type{\latexprotect} to prevent name
%D collision.  There is no guarantee that this will work perfectly.]
%D
%D Fragile and robust commands are one of the thornier issues in
%D \LaTeX's commands.  Whilst typesetting documents, \LaTeX{} makes use
%D of many of \TeX's features, such as arithmetic, defining macros, and
%D setting variables.  However, there are (at least) three different
%D ocassions when these commands are not safe.  These are called
%D `moving arguments' by \LaTeX, and consist of:
%D \startitemize
%D \item writing information to a file, such as indexes or tables of
%D    contents. 
%D \item writing information to the screen.
%D \item inside an \type{\edef}, \type{\message}, \type{\mark}, or other command which
%D    evaluates its argument fully.
%D \stopitemize
%D The method \LaTeX{} uses for making fragile commands robust is to
%D precede them with \type{\latexprotect}.  This can have one of four possible
%D values: 
%D \startitemize
%D \item \type{\relax}, for normal typesetting.  So \type{\latexprotect\foo} will
%D    execute |\foo}.
%D \item \type{\string}, for writing to the screen.  So \type{\latexprotect\foo} will
%D    write \type{\foo}.
%D \item \type{\noexpand}, for writing to a file.  So \type{\latexprotect\foo} will
%D    write \type{\foo} followed by a space.
%D \item \type{\@unexpandable@protect}, for writing a moving argument to a
%D    file.  So \type{\latexprotect\foo} will write \type{\latexprotect\foo} followed by a
%D    space.  This value is also used inside \type{\edef}s, \type{\mark}s and
%D    other commands which evaluate their arguments fully.
%D \stopitemize

%D These commands are used for setting |\latexprotect| inside |\edef|s.

\def\@unexpandable@protect{\noexpand\latexprotect\noexpand}

%D This is a package-writers command, which has the same syntax as
%D \type{\newcommand}, but which declares a protected command.  It does
%D this by having \type{\DeclareRobustCommand\foo} define \type{\foo} to be
%D \type{\latexprotect\foo<space>}, and then use \type{\newcommand\foo<space>}.
%D Since the internal command is \type{\foo<space>}, when it is written
%D to an auxiliary file, it will appear as \type{\foo}.  
%D
%D We have to be a bit cleverer if we're defining a short command, such
%D as \type{\_}, in order to make sure that the auxiliary file does not
%D include a space after the command, since \type{\_ a} and \type{\_a}
%D aren't the same.  In this case we define \type{\_} to be:
%D \starttyping 
%D    \x@protect\_\latexprotect\_<space>
%D \stoptyping
%D which expands to:
%D \starttyping 
%D    \ifx\latexprotect\@typeset@protect\else
%D       \@x@protect@\_
%D    \fi
%D    \latexprotect\_<space>
%D \stoptyping
%D Then if \type{\latexprotect} is \type{\@typeset@protect} (normally \type{\relax})
%D then we just perform \type{\_<space>}, and otherwise \type{\@x@protect@}
%D gobbles everything up and expands to \type{\latexprotect\_}. 
%D
%D \emph{Note}: setting \type{\latexprotect} to any value other than \type{\relax}
%D whilst in `typesetting' mode will cause commands to go into an
%D infinite loop!  In particular, setting \type{\relax} to \type{\@empty} will
%D cause \type{\_} to loop forever.  It will also break lots of other
%D things, such as protected \type{\ifmmode}s inside \type{\halign}s.  If you
%D really really have to do such a thing, then please set
%D \type{\@typeset@protect} to be \type{\@empty} as well.  (This is what the
%D code for \type{\patterns} does, for example.)
%D
%D More fun with \type{\expandafter} and \type{\csname}.

\def\DeclareRobustCommand{\@star@or@long\declare@robustcommand}

\def\declare@robustcommand#1{%
   \ifx#1\@undefined\else\ifx#1\relax\else
      \@latex@info{Redefining \string#1}%
   \fi\fi
   \edef\reserved@a{\string#1}%
   \def\reserved@b{#1}%
   \edef\reserved@b{\expandafter\strip@prefix\meaning\reserved@b}%
   \edef#1{%
      \ifx\reserved@a\reserved@b
         \noexpand\x@protect
         \noexpand#1%
      \fi
      \noexpand\latexprotect
      \expandafter\noexpand\csname
         \expandafter\@gobble\string#1 \endcsname
   }%
   \let\@ifdefinable\@rc@ifdefinable
   \expandafter\new@command\csname
      \expandafter\@gobble\string#1 \endcsname
}

\def\x@protect#1{%
   \ifx\latexprotect\@typeset@protect\else
      \@x@protect#1%
   \fi
}
\def\@x@protect#1\fi#2#3{%
   \fi\latexprotect#1%
}

\let\@typeset@protect\relax

%D These macros set \type{\latexprotect} appropriately for typesetting or
%D displaying. 

\def\set@display@protect{\let\latexprotect\string}
\def\set@typeset@protect{\let\latexprotect\@typeset@protect}

%D The commands \type{\protected@edef} and \type{\protected@xdef} perform
%D `safe' \type{\edef}s and \type{\xdef}s, saving and restoring \type{\latexprotect}
%D appropriately.  For cases where restoring \type{\latexprotect} doesn't
%D matter, there's an `unsafe' \type{\unrestored@protected@xdef}, useful
%D if you know what you're doing!

\def\protected@edef{%
   \let\@@protect\latexprotect
   \let\latexprotect\@unexpandable@protect
   \afterassignment\restore@protect
   \edef
}
\def\protected@xdef{%
   \let\@@protect\latexprotect
   \let\latexprotect\@unexpandable@protect
   \afterassignment\restore@protect
   \xdef
}
\def\unrestored@protected@xdef{%
   \let\latexprotect\@unexpandable@protect
   \xdef
}
\def\restore@protect{\let\latexprotect\@@protect}

%D The normal meaning of \type{\latexprotect}

\set@typeset@protect


%D \subsection{Internal defining commands}
%D
%D These commands are used internally to define other \LaTeX\
%D commands. 

\def\@ifundefined#1{%
  \expandafter\ifx\csname#1\endcsname\relax
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi}

%D The following define \type{\@qend} and \type{\@qrelax} to be the strings 
%D `\type{end}' and `\type{relax}' with the characters \type{\catcode}d 12.

\edef\@qend{\expandafter\@cdr\string\end\@nil}
\edef\@qrelax{\expandafter\@cdr\string\relax\@nil}

%D \type{\@ifnextchar} peeks at the following character and compares it
%D with its first argument. If both are the same it executes its
%D  second argument, otherwise its third.
%D
%D [This already exists in \ConTeXt.  The internal string names are
%D different, however; hopefully, this won't be a problem.]

\let\@ifnextchar\doifnextcharelse

%D This macro is the kernel version of |\@ifnextchar| which is used
%D in a couple of places to prevent the AMS variant from being used
%D since in some places this produced chaos....
%D
%D ### Since we're defining the AMS stuff, this isn't needed.

\let\kernel@ifnextchar\@ifnextchar

%D Make internal control sequences accessible or inaccessible.
%D
%D [Deprecated; \ConTeXt's \type{\unprotect} and \type{\protect} are
%D the more general form.]

\def\makeatletter{\catcode`\@11\relax}
\def\makeatother{\catcode`\@12\relax}

%D The new implementation below avoids passing the ``true code''
%D through one more \type{\def} than the ``false code'', which previously
%D meant that \type{#} had to be written as \type{####} in one argument, but
%D \type{##} in the other. The \type{*} is gobbled by \type{\@firstoftwo}.

\def\@ifstar#1{\@ifnextchar *{\@firstoftwo{#1}}}


\long\def\@dblarg#1{\kernel@ifnextchar[{#1}{\@xdblarg{#1}}}
\long\def\@xdblarg#1#2{#1[{#2}]{#2}}

%D The command \type{\@sanitize} changes the catcode of all special characters
%D except for braces to `other'.  It can be used for commands like
%D \type{\index} that want to write their arguments verbatim.  Needless to
%D say, this command should only be executed within a group, or chaos
%D will ensue.

\def\@sanitize{\@makeother\ \@makeother\\\@makeother\$\@makeother\&%
\@makeother\#\@makeother\^\@makeother\_\@makeother\%\@makeother\~}

%D This makes the whole ``meaning'' of \type{#1} (its one-level
%D expansion) into catcode 12 tokens: it could be used in
%D \type{\DeclareRobustCommand}.
%D    
%D If it is to be used on default float specifiers, this should be
%D done when they are defined.

\def \@onelevel@sanitize #1{%
  \edef #1{\expandafter\strip@prefix
           \meaning #1}%
}


%D Modules to load after this one.

\protect
\usemodule[lterr]
