[Tex/LaTex] Difference between renewing commands before and after \begin{document}

best practicespreamble

I was wondering what could be reasons for differences when I redefine control sequences in the preamble or after \begin{document}?

For example, this code typesets abcd when compiled by any of pdflatex, htlatex, and mk4ht oolatex.

\documentclass{article}
\begin{document}
\renewcommand\b{b}
a\b cd
\end{document}

But if \renewcommand\b{b} is moved to the preamble, pdflatex and htlatex will still output abcd, while mk4ht oolatex will now output ac̱d. That is, instead of b, \b will expand to the standard sub-macron (0x331).

\documentclass{article}
\renewcommand\b{b}
\begin{document}
a\b cd
\end{document}

I assume the missing b in these examples is not due to a bug in mk4ht oolatex.

Best Answer

Here are some reasons or considerations:

  • From a programming point of view, structure promotes good practice. As such, document style/structure is typically performed within the document preamble (between \documentclass and \begin{document}), while document content follows within the document environment.

  • Some commands are defined to be used only within the preamble. With the LaTeX kernel this is identified via \@onlypreamble. These include, amongst a host of others, \usepackage.

  • Depending on your document structure, you may be inclined to construct your layout in a compartmentalized fashion. To that end, you insert both structural/stylistic and content matter inside a single file which you include using \input somewhere within your document. This is fine as long as the commands used are not designated as \@onlypreamble.

  • Some package perform redefinitions \AtBeginDocument. So, performing a usual \renewcommand may not have the expected effect, unless you place it inside an \AtBeginDocument-delayed clause yourself.

So, why not? It depends on the use case, but as long as there is consistency (via structure or compartmentalization alone), there is no need to stick to this rule.

Related Question