[Tex/LaTex] \@ifnextchar and friends documentation

bookslatex-basemacros

While reading this question and its answers I tried to find where, for instance, \@ifnextchar is documented. I'm afraid I couldn't… I looked in TeX: The Program and TeX for the Impatient which can be found in texdoc(link) and of course in Google, but found no real documentation. My question is where is it documented?

Actually a broader question is where similar internal commands of (La)TeX are documented? I encounter in TeX.SE many answers which involve core components of La(Tex) but I usually fail to find a rigorous documentation of these elements.
This makes it more difficult to have deeper understanding of the answer, and in particular try to modify/adopt the solutions to slightly different problems. So the main question is: Where core command are documented?

Edit: Let me fine tune my question since most of the answer aimed mainly at the \@ifnextchr. What is a (the?) canonical documentation of both TeX and LaTeX, where magic like \@ifnextchr and similar @ involving elements are documented? Is it only TeXbook? What is the LaTeX equivalent of TeXbook?

Best Answer

The definitive source for the documentation of the LaTeX kernel is source2e.pdf, compiled from the .dtx files from which latex.ltx and the auxiliary files loaded at format creation time are extracted. The PDF file should be available in your TeX distribution (texdoc source2e).

For example \@ifnextchar is documented in section 11.3 of source2e.pdf

Its definition is in lines 253ff. of ltdefns.dtx, but it's best understood by examples.

\def\input{\@ifnextchar\bgroup\@iinput\@@input}

If the token following \input is an open brace, then execute \@iinput, otherwise execute \@@input (which is the primitive meaning of \input).

\DeclareRobustCommand\sqrt{\@ifnextchar[\@sqrt\sqrtsign}

If the token following \sqrt is an open (square) bracket, then execute \@sqrt (there's the optional argument), otherwise execute the simpler \sqrtsign: \def\@sqrt[#1]{\root #1\of} reduces \@sqrt[#1] to the Plain TeX derived construction.

Notice that the following token is not removed (unless it's a space token), so after \sqrt[3]{x} there will be

\@sqrt[3]{x}

that is then parsed correctly.

\@ifnextchar is used in the definition of \@ifstar:

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

So \def\xyz{\@ifstar\s@xyz\@xyz} will do, with a following *,

\xyz*
\@ifstar\s@xyz\@xyz*
\@ifnextchar *{\@firstoftwo{\s@xyz}}\@xyz*
\@firstoftwo{\s@xyz}*
\s@xyz

and, when there's no *,

\xyz t
\@ifstar\s@xyz\@xyz t
\@ifnextchar *{\@firstoftwo{\s@xyz}}\@xyz t
\@xyz t

so we see that \@ifstar does remove the * (with a clever trick). Here t stands for any token that's not a *.

It's quite important to note that \@ifnextchar uses \if to perform the test, so, for example,

\let\myasterisk=*
\xyz\myasterisk

will be the same as \xyz*.