6

I'm using the lineno package to number lines in a document. By default, lineno attempts to number everything, including section headers. I would like disable line numbering on section headers, preferably in an automated way so I don't need to manually edit every section header in my document.

The lineno manual provides the following ways to disable line numbering:

\nolinenumbers
... text ...
\linenumbers

\begin{nolinenumbers}
... text ...
\end{nolinenumbers}

This works fine except I need to manually add this code around every \section{...} call in my document.

Presumably I could \renewcommand{\section} to do this automatically, but I am not sure of the Right Way (TM) to do this. The following naive code appears to work, but I am not convinced that I won't trip over some nasty edge case by doing this. Among other things, I'll need to redefine \subsection and \subsubsection in addition to \section for this to work in general.

\let\oldsection\section
\renewcommand{\section}[1]{\nolinenumbers \oldsection{#1} \linenumbers}

Is there a more robust and/or elegant way of doing this?

  • Are you using any packages that could affect sectional units/headers (like titlesec, or hyperref, or...)? – Werner Nov 11 '13 at 6:02
  • I'm not using any of those (and do not expect to), although I would be willing to consider using one if it would make solving the problem easier. – Elliott Slaughter Nov 12 '13 at 1:01
7

If you're not using any special packages, the following would be sufficient:

enter image description here

\documentclass{article}
\usepackage{etoolbox,lineno}% http://ctan.org/pkg/{etoolbox,lineno}
\usepackage{lipsum}% http://ctan.org/pkg/lipsum
\makeatletter
% \patchcmd{<cmd>}{<search>}{<replace>}{<success>}{<failure>}
\patchcmd{\@startsection}{\@ifstar}{\nolinenumbers\@ifstar}{}{}
\patchcmd{\@xsect}{\ignorespaces}{\linenumbers\ignorespaces}{}{}
\makeatother
\linenumbers
\begin{document}
\section{A section} \lipsum[2]
\subsection{Another section} \lipsum[2]
\subsubsection{Final section} \lipsum[2]
\end{document}

There are two patches applied with the aid of etoolbox.

  • The first inserts \nolinenumbers as part of \@startsection - called just after \par is issued to ensure there is no line numbers in the sectional title line;
  • The second inserts \linenumbers just after the sectional title has been set.

The specific location of these insertions will allow for unnumbered sectional units of all types (starred or not), although the effect will not be visible in some instances (like \paragraph and \subparagraph, by default), since run-in sections have text immediately following the title.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.