Automatic numbering of paragraphs in the margin

numberingparagraphs

I want a way to number paragraphs automatically in a way that doesn't require explicit extra code at the end of every paragraph in a document built on LaTeX3. I want the paragraph numbers to appear in the left margin or maybe the outside margin if it's a two-sided document. Ideally I'd like a mechanism to start, pause, resume, stop, and reset the numbering. And preferably have a way to control the display of the number, probably prefix it with a paragraph mark. Basically something like the lineno package.

I feel this should be a solved problem already but I can't find any suitable packages. The nearest on tex stackexchange seems to be this but I'm not sure how to adapt it.

MWE

\documentclass[11pt]{article}

\usepackage{lipsum}

% This part needs replacing
\usepackage{marginnote}\reversemarginpar

\begin{document}

\marginnote{\P1}First paragraph.

\marginnote{\P2}Second paragraph.

The above two paragraphs illustrate the desired outcome but have to be done explicitly in the source. The aim is for paragraphs like this and subsequent ones to be numbered automatically.

\lipsum[1-2]

\end{document}

Approximation of the desired effect

Best Answer

Well you can use the new para hooks. But the main problem is not to add something, but to prevent that it gets added in places where you don't want it, paragraphs are in more places than you expect. Use some boolean e.g. from the etoolbox package that you can switch on and off.

\documentclass[11pt]{article}

\usepackage{lipsum,etoolbox}

\newbool{myparbool}
\booltrue{myparbool}
\newcounter{mypar}
\AddToHook{para/begin}
  {\ifbool{myparbool}{\stepcounter{mypar}\llap{\P\themypar\quad}}{}}
\begin{document}

\boolfalse{myparbool}
\section{Section}
\booltrue{myparbool}

First paragraph.

Second paragraph.

The above two paragraphs illustrate the desired outcome but have to be done explicitly in the source. The aim is for paragraphs like this and subsequent ones to be numbered automatically.

\lipsum[1-2]

\end{document}

enter image description here

Related Question