I'm not sure whether I'm allowed to extend my previous question so I'm asking here.
I wanted a way to number paragraphs automatically and Ulrike Fischer provided an excellent solution. I want to extend this solution to require less manual intervention. The provided method explicitly requires temporarily switching the paragraph numbering off. I am sure it is possible to amend the \section
and \subsection
and \subsubsection
commands but I have been unable to make it compile let alone work. Ideally I'd like to learn how to do this for these commands and probably others where I won't paragraph numbering such as captions and footnotes.
MWE 1: Manual intervention (works)
\documentclass[11pt]{article}
\usepackage{etoolbox}
\usepackage{lipsum}
\newbool{myparbool}
\booltrue{myparbool}
\newcounter{mypar}
\AddToHook{para/begin}
{\ifbool{myparbool}{\stepcounter{mypar}\llap{\P\themypar\quad}}{}}
\begin{document}
\boolfalse{myparbool}
\section{First}
\booltrue{myparbool}
All paragraphs should be numbered in the left margin but sections and subsections should not have paragraph numbers. This works but needs explicit manual control.
\lipsum[1]
\boolfalse{myparbool}
\subsection{Second}
\booltrue{myparbool}
\lipsum[2]
\boolfalse{myparbool}
\subsubsection{Third}
\booltrue{myparbool}
\lipsum[3]
\boolfalse{myparbool}
\section{Fourth}
\booltrue{myparbool}
\lipsum[4]
\end{document}
MWE 2: No manual intervention (needs fixing)
\documentclass[11pt]{article}
\usepackage{etoolbox}
\usepackage{lipsum}
\newbool{myparbool}
\booltrue{myparbool}
\newcounter{mypar}
\AddToHook{para/begin}
{\ifbool{myparbool}{\stepcounter{mypar}\llap{\P\themypar\quad}}{}}
% New stuff that doesn't work: want to patch the \section, \subsection and \subsubsection commands
\usepackage{xpatch}
\newbool{parboolstatus}
\xpretocmd{\section}{%
\bgroup%
\ifbool{myparbool}%then
{\setbool{parboolstatus}{true}}%else
{\setbool{parboolstatus}{false}}
\setbool{myparbool}{false}%
}{}{}
\xapptocmd{\section}{%
\ifbool{parboolstatus}%then
{\setbool{myparbool}{true}}%else
{\setbool{myparbool}{false}}%
}{}{}
\apptocmd{\@xsect}{\egroup}{}{}
\begin{document}
\section{First}
All paragraphs should be numbered in the left margin but sections should not have paragraph numbers.
\lipsum[1]
\subsection{Second}
\lipsum[2]
\subsubsection{Third}
\lipsum[3]
\section{Fourth}
\lipsum[4]
\end{document}
Results in a compilation error.
I have tried \addto
and \addtocmd
but these also resulted in compilation errors. I had different errors initially because I wasn't beginning and ending a group.
I have seen this question but I can't adapt the solution. I found this but I can't adapt that either.
I haven't been able to find a beginners guide to this. I expect there isn't one because it's not really a beginner's topic. I can't find a list of the hooks either. @Ulrike's original answer uses para/begin
but I don't know if there's a section/begin
or equivalent.