# LaTeX Grammar and Nesting Rule

Is there any grammar and rule describing the allowed nestings and combinations and the allowed format of the arguments in LaTeX? E.g.

\section{\verb|mySec|}

\section{\begin{huge}mySec\end{huge}}

\section{\section{mySec}}


is invalid LaTeX code. Or something that astonished me was

\begin{section}{mySec}
bla bla
\end{section}


and

\begin{figure}[b]
\includegraphics{image.png}
\begin{caption}{myCaption}
bla bla
\end{caption}
\end{figure}


I never saw section and caption declared like this but it is valid. I am working on a semi LaTeX parser and such a rule would help me.

• A LaTeX parser can (and will) be quite tricky to build. Take a look at this answer of mine. The use case is different, but the principle still applies. \begin{section}{mySec} bla bla \end{section} because the \begin part effectively does \section{mySec} and the \end part does \relax, which is nothing. This syntax can cause some unexpected behavior in the document though, so it really shouldn't be used. The same goes for the \begin{caption}{myCaption}. – Phelype Oleinik Aug 30 '18 at 23:25

\verb has a non-grammatical constraint that it can not be used in the argument of any command so

\section{\verb|mySec|}


is a syntax error.

\section{\begin{huge}mySec\end{huge}}


is not a syntax error and has well defined output but it is really poor style, there should be no formatting in the argument of \section the whole point of latex is that styling for things like section heads is in class setup not inline in the document. the particular markup \begin{huge}mySec\end{huge} is poor even if not in a section heading as it specifies huge text on a normal baseline so uneven linespacing. But again this is a matter of poor user style not a grammar error that a parser can pick up.

 \section{\section{mySec}}


there is no specific rule preventing this but it is nonsensical input that gives some more or less accidental low level error

! Incomplete \iffalse; all text was ignored after line 5.


\begin{section}{mySec}
bla bla
\end{section}


is valid, if unusual, markup equivalent by design to

{\section{mysec} bla bla }


\begin{figure}[b]
\includegraphics{image.png}
\begin{caption}{myCaption}
bla bla
\end{caption}
\end{figure}


This is also valid but unusual markup but in this case probably not what the author intended. It is equivalent to

\begin{figure}[b]
\includegraphics{image.png}
{\caption{myCaption}
bla bla
}
\end{figure}


A classic test for latex parsers would be:

\documentclass{article}
\newcommand\biggskip{\par\vspace{5pt}}
\begin{document}

\let ~\catcode~76~A13~F1~j00~P2jdefA71F~7113jdefPALLF
PA''FwPA;;FPAZZFLaLPA//71F71iPAHHFLPAzzFenPASSFthP;AFevP