Subject: bug#69370: Preview breaks with \listoftodos in article class due to chapter not being defined

From: Daniel Kessler <[email-masked]>
Date: Sat, 24 Feb 2024 15:17:32 -0800

I noticed that when I attempted to preview some latex buffers in emacs,
that the compilation process would get stuck and hang when it encountered
the \listoftodos macro from the todonotes package. Here's the definition of
\listoftodos:

\newcommand{\listoftodos}[1][\@todonotes@todolistname]
    {\@ifundefined{chapter}{\section*{#1}}{\chapter*{#1}} \@starttoc{tdo}}

I was able to reproduce the issue outside of emacs/AUCTeX and noticed that
the issue seemed to be that it had encountered the unknown command
\chapter* (these errors were suppressed by the auctex option when using
preview from within emacs). In brief, \listoftodos behaves differently
depending on whether or not \chapter is defined (and in the article class,
it isn't). However, when preview is active and the sections option is
passed, it runs

  \PreviewMacro[*[[!]{\chapter}%]]

*regardless *of whether chapter is defined or not. The \PreviewMacro
command is a bit mysterious to me, but as far as I can tell it defines
\chapter in such a way that it will expand to a macro that does some
preprocessing first, calls the original definition of chapter, and
(perhaps) does some postprocessing. However, that second step will fail
since \chapter doesn't have an original definition in the article class.

Here's an MWE latex file that demonstrates the issue with
todonotes's \listoftodos:

\documentclass{article}
\usepackage{todonotes}
\usepackage[active,sections]{preview}
\begin{document}
\listoftodos
\end{document}

However, the problem isn't really with todonotes specifically, as can be
appreciated with the following two MWE latex files that demonstrate the
crux of the issue with chapter without involving todonotes at all. The
first yields an error, the second compiles cleanly. They differ only in
whether the preview package is active or not.

\documentclass{article}
\usepackage[active,sections]{preview}
\begin{document}
\makeatletter
\@ifundefined{chapter}{\section{Section One}}{\chapter{Chapter One}}
\makeatother
\end{document}

vs

\documentclass{article}
\usepackage[inactive,sections]{preview}
\begin{document}
\makeatletter
\@ifundefined{chapter}{\section{Section One}}{\chapter{Chapter One}}
\makeatother
\end{document}

Compiling the first yields

! Undefined control sequence.
<argument> \pr@\chapter
                        {Chapter One}
l.7 ...ection{Section One}}{\chapter{Chapter One}}

I think this could be fixed by adding some logic into around where the
sections options is declared so that

\PreviewMacro[*[[!]{\chapter}%]]

is run *only* if \chapter is already defined. Perhaps there's some
additional logic that be built into the \PreviewMacro instead, but the code
used in that definition exceeds my understanding of (la)tex.

-Dan