Structurally Triggered Metal-Insulator Transition in Rare-Earth Nickelates

Abstract: Rare-earth nickelates form an intriguing series of correlated perovskite oxides. Apart from LaNiO3, they exhibit on cooling a sharp metal-insulator electronic phase transition, a concurrent structural phase transition and a magnetic phase transition toward an unusual antiferromagnetic spin order. Appealing for various applications, full exploitation of these compounds is still hampered by the lack of global understanding of the interplay between their electronic, structural and magnetic properties. Here, we show from first-principles calculations that the metal-insulator transition of nickelates arises from the softening of an oxygen breathing distortion, structurally triggered by oxygen-octahedra rotation motions. The origin of such a rare triggered mechanism is traced back in their electronic and magnetic properties, providing a united picture. We further develop a Landau model accounting for the evolution of the metal-insulator transition in terms of the $R cations and rationalising how to tune this transition by acting on oxygen rotation motions.

\section{%
Introductions
\unskip}

(New v4.00)           Parts of former first section
have been rendered separate subsections for package
version_v4.00.                         (/New v4.00)

\subsection
Introduction to versions $\textrm{v}\lessthan4$
\unskip}

This package provides line numbers on paragraphs.
After \TeX\ has broken a paragraph into lines there will
be line numbers attached to them, with the possibility to
make references  through the \LaTeX\ ~\ref~, ~\pageref~
cross reference mechanism.  This includes four issues:
\begin{itemize}
\item   attach a line number on each line,
\item   create references to a line number,
\item   control line numbering mode,
\item   count the lines and print the numbers.
\end{itemize}
The first two points are implemented through patches to
the output routine.  The third by redefining ~\par~, ~\@par~
and ~\@@par~.  The counting is easy, as long as you want
the line numbers run through the text.  If they shall
start over at the top of each page, the aux-file as well
as \TeX s memory have to carry a load for each counted line.

I wrote this package for my wife Petra, who needs it for
transcriptions of interviews.  This allows her to
precisely refer to passages in the text.  It works well
together with ~\marginpar~s, but not too well with displaymath.
~\footnote~s are a problem, especially when they
are split, but we may get there.
(New v4.00 UL) Version v4.00 overcomes the problem, I believe.
(/UL /New v4.00)

lineno.sty works
surprisingly well with other packages, for
example, ~wrapfig.sty~.  So please try if it
works with whatever you need, and if it does,
please tell me, and if it does not, tell me as
well, so I can try to fix it.

\subsection{%
Introduction to versions v4.00ff. (UL)
\unskip}

~lineno.sty~ has been maintained by Stephan until version_v3.14.
From version_v4.00 onwards, maintenance is shifting towards
Uwe L\"uck (UL), who is the author of v4\dots code and of v4\dots
changes in documentation. This came about as follows.

Since late 2002, Christian Tapp and Uwe L\"uck have employed
~lineno.sty~ for their ~ednotes.sty~, a package supporting
critical editions---cf.
\[\mbox{\tt
http://ednotes.sty.de.vu
\unskip}\]
---while you find ~ednotes.sty~ and surrounding files in
CTAN folder \path{macros/latex/contrib/ednotes}.

Soon, some weaknesses of ~lineno.sty~ showed up, mainly since
Christian's critical editions (using ~ednotes.sty~) needed lots
of ~\linelabel~s and footnotes. (These weaknesses are due to
weaknesses of \LaTeX's ~\marginpar~ mechanism that Stephan
used for ~\linelabel~.) So we changed some ~lineno.sty~
definitions in some extra files, which moreover offered new
features. We sent these files to Stephan, hoping he would take
the changes into ~lineno.sty~. However, he was too short of time.

Writing a TUGboat article on Ednotes in 2004, we hoped to
reduce the number of files in the Ednotes bundle and so asked
Stephan again. Now he generously offered maintenance to me, so
I could execute the changes on my own.

The improvements are as follows:
\begin{itemize}\item
[(i)]   Footnotes placement approaches intentions better
(footnotes formerly liked to pile up at late pages).
\item
[(ii)]  The number of ~\linelabel~s in one paragraph is no longer
limited to 18.
\item
[(iii)] ~\pagebreak~, ~\nopagebreak~, ~\vspace~, and the star
and optional versions of ~\\~ work as one would expect
(section_\ref{s:MVadj}).
\item
[(iv)]  A command is offered which chooses the first line number
to be printed in the margin
(subsection_\ref{ss:Mod}).
\item
[(v)]   (New v4.1) \LaTeX\ tabular environments (optionally)
get line numbers as well, and you can refer to them in the
usual automatic way. (It may be considered a shortcoming that,
precisely, \emph{rows} are numbered, not lines.---See
subsection_\ref{ss:Tab}.)
\item
[(vi)]  We are moving towards referring to math items
(subsection_\ref{ss:MathRef} and the hooks in
subsection_\ref{ss:LL}).
(/New v4.1)
\end{itemize}
(Thanks to Stephan for making this possible!)

Ednotes moreover profits from Stephan's offer with regard
to the documentation of our code which yielded these
improvements formerly. This documentation now becomes
printable, being part of the ~lineno.sty~ documentation.

Of course, Stephan's previous ~lineno.sty~ versions were a great
and ingenious work and exhibit greatest \TeX pertise. I never
could have done this. I learnt a lot in studying the code when
Christian pointed out strange output results and error
messages, and there are still large portions of ~lineno.sty~
which I don't understand (consider only pagewise numbering of
lines). Fortunately, Stephan has offered future help if
needed.---My code for attaching line numbers to \emph{tabular
environments} (as mentioned above, now still in
~edtable.sty~)
developed from macros which Stephan and Christian experimented
with in December 2002. Stephan built the basics.
(However, I then became too proud to follow his advice only to
use and modify ~longtable.sty~.)

There are some issues concerning use of counters on which I
don't agree with Stephan and where I would like to change the
code if ~lineno.sty~ is ``mine'' as Stephan offered. However,
Stephan is afraid of compatibility problems from which, in
particular, his wife could suffer in the near future. So he
demanded that I change as little as possible for my first
version. Instead of executing changes that I plan I just offer
my opinions at the single occasions. I hope to get in touch
this way with users who consider subtle features vital which I
consider strange.

On the other hand, the sections on improvements of the
implementation have been blown up very much and may be tiring
and litte understandable for mere \emph{users}. These users
may profit from the present presentation just by jumping to
sections_\ref{s:Opts} and_\ref{s:UserCmds}. There is a user's
guide ulineno.tex which may be even more helpful, but it has
not been updated for a while.

\subsection{%
Availability
\unskip}

In case you have found the present file otherwise than from
CTAN: A recent version and documentation of this package
should be available from CTAN folder
\path{macros/latex/contrib/lineno}.
Or mail to one of the addresses at top of file.

\subsection
Introductory code
\unskip}

This style option is written for \LaTeXe, November 1994 or later,
since we need the ~\protected@write~ macro.

(New v4.00)               And we use ~\newcommand*~ for
controlling length of user macro arguments, which has been
available since December 1994.
\begin{code}\begin{verbatim}
\NeedsTeXFormat{LaTeX2e}[1994/12/01]
\ProvidesPackage{lineno}
  [\filedate\space line numbers on paragraphs \fileversion]
\end{verbatim}
\end{code}
(/New v4.00)

\section{%
Put the line numbers to the lines
\unskip}

(New v4.00)                    This section contained the most
basic package code previously. For various purposes of
version_4\dots, much of these basics have been to be modified.
Much of my (UL's) reasoning on these modifications has been to
be reported. Sorry, the present section has been blown up
awfully thus and contains ramifications that may be difficult
to trace. We add some ~\subsection~ commands in order to cope
with the new situation. (/New v4.00)

\subsection
Basic code of \texttt{lineno.sty} \scs{output}
\unskip}\label{ss:output}

The line numbers have to be attached by the output
routine.  We simply set the ~\interlinepenalty~ to $-100000$.
The output routine will be called after each line in the
paragraph,  except the last,  where we trigger by ~\par~.
The ~\linenopenalty~ is small enough to compensate a bunch of
penalties (e.g., with ~\samepage~).

(New v3.04)            Longtable uses
~\penalty~$-30000$.  The lineno penalty range was
shrunk to $-188000 \dots -32000$.  (/New v3.04)
(New v4.00) New values are listed below (11111f.). (/New v4.00)
\begin{code}\begin{verbatim}
\newcount\linenopenalty\linenopenalty=-100000
\end{verbatim}
\end{code}
(UL)                              Hm. It is never needed below
that this is a counter. ~\def\linenopenalty{-100000\relax}~
would do. (I guess this consumes more memory, but it
is more important to save counters than to save memory.)
I was frightened by ~-\linenopenalty~ below, but indeed
\TeX\ interprets the string ~--100000~ as 100000.
Has any user or extension package writer ever called
~\linenopenalty=xxx~, or could I really change this?---The
counter is somewhat faster than the macro. Together with the
compatibility question this seems to support keeping the
counter. (???)
(/UL)
\begin{code}\begin{verbatim}
\mathchardef\linenopenaltypar=32000
\end{verbatim}
\end{code}
So let's make a hook to ~\output~,  the direct way. The \LaTeX\
macro ~\@reinserts~ puts the footnotes back on the page.

(New v3.01)                ~\@reinserts~ badly
screws up split footnotes.  The bottom part is
still on the recent contributions list, and the
top part will be put back there after the bottom
part. Thus, since lineno.sty does not play well
with ~\inserts~ anyway, we can safely experiment
with ~\holdinginserts~, without making things
much worse.

Or that's what I thought, but:  Just activating
~\holdinginserts~ while doing the ~\par~ will
not do the trick:  The ~\output~ routine may be
called for a real page break before all line
numbers are done, and how can we get control
over ~\holdinginserts~ at that point?

Let's try this:  When the ~\output~ routine is
run with ~\holdinginserts=3~ for a real page
break, then we reset ~\holdinginserts~ and
restart ~\output~.

Then, again, how do we keep the remaining
~\inserts~ while doing further line numbers?

If we find ~\holdinginserts~=$-3$ we activate it again
after doing ~\output~.             (/New v3.01)

(New v3.02)                    To work with
multicol.sty, the original output routine is now
called indirectly, instead of being replaced.
When multicol.sty changes ~\output~, it is a
toks register, not the real thing. (/New v3.02)

(New v4.00)               Two further complications are added.
\begin{itemize}\item
[(i)]  Problems with footnotes formerly resulted from
\LaTeX's ~\@reinserts~ in ~\@specialoutput~ which Stephan's
~\linelabel~ called via the ~\marginpar~ mechanism.
\item
[(ii)] \LaTeX\ commands using ~\vadjust~ formerly didn't work
as one would have hoped. The problem is as follows:
Printing the line number results from
a box that the output routine inserts at the place of the
~\interlinepenalty~. ~\vadjust~ items appear \emph{above} the
~\interlinepenalty~ (\TeX book p._105). So ~\pagebreak~, e.g.,
formerly sent the line number to the next page, while the
penalty from ~\nopagebreak~ could not tie the following line,
since it was screened off by the line number box.---Our trick
is putting the ~\vadjust~ items into a list macro from which
the output routine transfers them into the vertical list,
below the line number box.
\end{itemize}
In this case_(ii), like in case_(i), footnotes would suffer
if ~\holdinginserts~ were non-positive. Indeed, in both
cases_(i) and_(ii) we tackle the footnote problem by extending
that part of Stephan's output routine that is active when
~\holdinginserts~ is positive. This extension writes the line
number ~\newlabel~ to the .aux file (which was formerly done
under $~\holdinginserts~=-3$) and handles the ~\vadjust~
items.---To trigger ~\output~ and its ~\linelabel~ or, resp.,
~\vadjust~ part, the list of signal penalties started
immediately before is increased here (first for ~\linelabel~,
second for postponed ~\vadjust~ items):
\begin{code}\begin{verbatim}
\mathchardef\@Mllbcodepen=11111
\mathchardef\@Mppvacodepen=11112
\end{verbatim}
\end{code}
(/New v4.00) (New v4.2) David Kastrup urges to use a private
name instead of ~\the\output~ (LaTeX-L-list). Otherwise an
~\output~ routine loaded later and using ~\newtoks\output~
again may get lost entirely. So we change use of ~\@LN@output~,
using it for the former purpose. Reference to what appeared
with the name of ~\output~ here lasts for a few lines and then
is given away.
\begin{code}\begin{verbatim}
\let\@tempa\output
\newtoks\output
\let\@LN@output\output
\output=\expandafter{\the\@tempa}
\end{verbatim}
\end{code}
Now we add two cases to Stephan's output routine. (New v4.00)
\begin{code}\begin{verbatim}
\@tempa={%
\end{verbatim}
\end{code}
(/New 4.2)
\begin{code}\begin{verbatim}
            \LineNoTest
            \if@tempswa
\end{verbatim}
\end{code}
(New v4.00)
We insert recognition of waiting ~\linelabel~ items---
\begin{code}\begin{verbatim}
              \ifnum\outputpenalty=-\@Mllbcodepen
                \WriteLineNo
\end{verbatim}
\end{code}
---and of waiting ~\vadjust~ items:
\begin{code}\begin{verbatim}
              \else
                \ifnum\outputpenalty=-\@Mppvacodepen
                  \PassVadjustList
                \else
\end{verbatim}
\end{code}
(/New v4.00) (New v4.2) Outsource ``Standard'' output
---which occurs so rarely---to subsection_\ref{ss:LLO}:
\begin{code}\begin{verbatim}
                  \LineNoLaTeXOutput
\end{verbatim}
\end{code}
(/New v4.2) (New v4.00)
Two new ~\fi~s for the ~\linelabel~ and ~\vadjust~ tests---
\begin{code}\begin{verbatim}
                \fi
              \fi
\end{verbatim}
\end{code}
---and the remaining is
Stephan's code again:
(/New v4.00)
\begin{code}\begin{verbatim}
            \else
              \MakeLineNo
            \fi
            }
\end{verbatim}
\end{code}
(New v4.00)                                  Our new macros
~\WriteLineNo~ and ~\PassVadjustList~ will be dealt with in
sections_\ref{s:LNref} and_\ref{ss:PVadj}. (/New v4.00)

\subsection{%
\scs{LineNoTest}
\unskip}

The float mechanism inserts ~\interlinepenalty~s during
~\output~.  So carefully reset it before going on.  Else
we get doubled line numbers on every float placed in
horizontal mode, e.g, from ~\linelabel~.

Sorry, neither a ~\linelabel~ nor a ~\marginpar~ should
insert a penalty, else the following linenumber
could go to the next page. Nor should any other
float.  So let us suppress the ~\interlinepenalty~
altogether with the ~\@nobreak~ switch.

Since (ltspace.dtx, v1.2p)[1996/07/26], the ~\@nobreaktrue~ does
it's job globally.  We need to do it locally here.
\begin{code}\begin{verbatim}
\def\LineNoTest{%
  \let\@@par\@@@par
  \ifnum\interlinepenalty<-\linenopenaltypar
     \advance\interlinepenalty-\linenopenalty
     \@LN@nobreaktrue
     \fi
  \@tempswatrue
  \ifnum\outputpenalty>-\linenopenaltypar\else
     \ifnum\outputpenalty>-188000\relax
       \@tempswafalse
       \fi
     \fi
  }

\def\@LN@nobreaktrue{\let\if@nobreak\iftrue}
\end{verbatim}
\end{code}
(UL)                                      I thought here were
another case of the save stack problem explained in \TeX book,
p._301, namely through both local and global changing
~\if@nobreak~. However, ~\@LN@nobreak~ is called during
~\@LN@output~ only, while ~\@nobreaktrue~ is called by \LaTeX's
~\@startsection~ only. The latter never happens during
~\@LN@output~. So there is no local value of ~\if@nobreak~ on
save stack when ~\@nobreaktrue~ acts, since ~\the\@LN@output~
(where ~\@LN@output~ is a new name for the original ~\output~)
is executed within a group (\TeX book p._21).
(/UL)

\subsection{%
Other output routines (v4.2)
\unskip}\label{ss:LLO}

I had thought of dealing with bad interference of footnotes
(and ~\enlargethispage~) with (real) ~\marginpar~s and floats
\emph{here}. Yet this is done in
\[
~http://~\mbox{[CTAN]}
~/macros/latex/contrib/tamefloats/tameflts.sty~
\]
now, and I prefer striving for compatibility with the latter.
(See there for expanding on the problem.)
This requires returning the special absolute value of
~\holdinginserts~ that ~lineno.sty~ finds at the end of a newly
typeset paragraph---now done in subsection_\ref{ss:calls}
(~\linenumberpar~).
The former ~\LineNoHoldInsertsTest~ has been filled into here.
Note: when the following code is invoked, we have
~\if@tempswa~_ =_~\iftrue~.
WARNING: I am still not sure whether the present code is good
for cooperating with other packages that use ~\holdinginserts~.
\begin{code}\begin{verbatim}
\def\LineNoLaTeXOutput
  \ifnum \holdinginserts=\thr@@
    \global\holdinginserts-\thr@@
    \unvbox\@cclv
    \ifnum \outputpenalty=\@M \else \penalty\outputpenalty \fi
  \else
    \if@twocolumn \let\@makecol\@LN@makecol \fi
    \the\@LN@output
    \ifnum \holdinginserts=-\thr@@
      \global\holdinginserts\thr@@ \fi
  \fi
}
\end{verbatim}
\end{code}
\textit{More on dealing with output routines from other
packages:}
Since ~lineno.sty~'s output routine is called at least once
for each output line, I think it should be in \TeX's
original ~\output~, while output routines dealing with
building pages and with floats etc.\ should be filled into
registers addressed by ~\output~ after ~\newtoks\output~.
Therefore                                                  \begin{enumerate}
\item
~tameflts.sty~ should be loaded \emph{after} ~lineno.sty~;
\item
if a class changes ~\output~ (APS journal class revtex4,
e.g.), ~lineno.sty~ should be loaded by ~\RequirePackage~
[here presumably following some options in
brackets]~{lineno}~ \emph{preceding} ~\documentclass~.
\item
If you actually maintain such a class, please consider
loading ~lineno.sty~ on some draft option. The bunch of
lineno's package options may be a problem, but perhaps the
purpose of your class is offering only very few of lineno's
options anyway, maybe just one.
\end{enumerate}
The latter may also be needed with classes that don't follow
David Kastrup's rule on changing ~\output~.

\subsection{%
\scs{MakeLineNo}: Actually attach line number
\unskip}\label{ss:MLN}

We have to return all the page to the current page, and
add a box with the line number, without adding
breakpoints, glue or space.  The depth of our line number
should be equal to the previous depth of the page, in
case the page breaks here,  and the box has to be moved up
by that depth.

The ~\interlinepenalty~ comes after the ~\vadjust~ from a
~\linelabel~,  so we increment the line number \emph{after}
printing it. The macro ~\makeLineNumber~ produces the
text of the line number, see section \ref{appearance}.

(UL)                        I needed a while to understand
the sentence on incrementing. Correctly: writing the
~\newlabel~ to the .aux file is triggered by the signal
penalty that ~\end@float~ inserts via ~\vadjust~.
However, this could be changed by our new ~\PostponeVadjust~.
After ~\c@linenumber~ has been introduced as a \LaTeX\
counter, it might be preferable that it behaved like standard
\LaTeX\ counters which are incremented shortly before printing.
But this may be of little practical relevance in this case,
as ~\c@linenumber~ is driven in a very non-standard
way.---However still, this behaviour of ~\c@linenumber~
generates a problem with our ~edtable.sty~.
(/UL).

Finally we put in the natural ~\interlinepenalty~, except
after the last line.

(New v3.10) Frank Mittelbach points out that box255 may be
less deep than the last box inside, so he proposes to
measure the page depth with ~\boxmaxdepth=\maxdimen~.
(/New v3.10)

(UL, New v4.00)               We also resume the matter of
~\vadjust~ items that was started in section_\ref{ss:output}.

\TeX\ puts only nonzero interline
penalties into the vertical list (\TeX book p._105), while
~lineno.sty~ formerly replaced the signal interline penalty by
something closing with an explicit penalty of the value that
the interline penalty would have without ~lineno.sty~.
This is usually 0. Now, explicit vertical penalties can be
very nasty with respect to ~\nopagebreak~, e.g., a low (even
positive) ~\widowpenalty~ may force a widow where you
explicitly tried to forbid it by ~\nopagebreak~
(see explanation soon below).
The ~\nopagebreak~ we create here would never work if all
those zero penalties were present.---On
the other hand, we cannot just omit Stephan's zero penalties,
because \TeX\ puts a penalty of 10000 after what ~lineno.sty~
inserts (\TeX book p._125). This penalty must be overridden
to allow page breaks between ordinary lines. To revive
~\nopagebreak~, we therefore replace those zero (or low)
penalties by penalties that the user demanded by
~\nopagebreak~.---This mechanism is not perfect and does not
exactly restore the original \LaTeX\ working of ~\pagebreak~
and ~\nopagebreak~. Viz., if there are several vertical
penalties after a line which were produced by closely sitting
~\[no]pagebreak~s, without ~lineno.sty~ the lowest penalty would
be effective (cf._\TeX book exercise_14.10). Our mechanism, by
contrast, chooses the \emph{last} user-set penalty of the line
as the effective one. It would not be very difficult to come
more close to the original mechanism, but until someone urges
us we will cling to the present simple way. You may consider an
advantage of the difference between our mechanism and the
original one that the user here can actually override low
penalties by ~\nopagebreak~, which may be what a lay \LaTeX\
user would expect.
(/UL, /New v4.00)
\begin{code}\begin{verbatim}
\def\MakeLineNo{%
   \@LN@maybe@normalLineNumber
   \boxmaxdepth\maxdimen\setbox\z@\vbox{\unvbox\@cclv}%
   \@tempdima\dp\z@ \unvbox\z@
   \sbox\@tempboxa{\hb@xt@\z@{\makeLineNumber}}%
\end{verbatim}
\end{code}
(New v4.00) Previously,
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
followed. (Of course, there was no
comment mark; I put it there to make
reading the actual code easy.)

(New v4.22: improved) Why not just
\[~\global\advance\c@linenumber\@ne~?\]
~\stepcounter~ additionally resets ``subordinate''
counters, but which could these (usefully) be?
Again, may be column counters with ~edtable.sty~!?

But then, our ~edtable.sty~ and its ~longtable~ option
should use it as well. So use a shorthand supporting
uniformity. You can even use it as a hook for choosing
~\global\advance\c@linenumber\@ne~ instead of our choice.
(/New v4.22)
\begin{code}\begin{verbatim}
   \stepLineNumber
\end{verbatim}
\end{code}
(New v4.4)   Now
\begin{code}\begin{verbatim}
   \ht\@tempboxa\z@ \@LN@depthbox
\end{verbatim}
\end{code}
appends the box containing the line number without changing
~\prevdepth~---see end of section.
Now is the time for inserting the $\dots$ (/New v4.4)
~\vadjust~ items. We cannot do this much later, because
their right place is above the artificial interline
penalty which Stephan's code will soon insert
(cf._\TeX book p._105). The next command is just ~\relax~
if no ~\vadjust~ items have been accumulated for the
current line. Otherwise it is a list macro inserting
the ~\vadjust~ items and finally resetting itself.
(This is made in section_\ref{ss:PVadj} below.)
If the final item is a penalty, it is stored so it can
compete with other things about page breaking.
\begin{code}\begin{verbatim}
   \@LN@do@vadjusts
   \count@\lastpenalty
\end{verbatim}
\end{code}
At this place,
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
originally followed. We need something \emph{before} the
~\else~:
\begin{code}\begin{verbatim}
   \ifnum\outputpenalty=-\linenopenaltypar
     \ifnum\count@=\z@ \else
\end{verbatim}
\end{code}
So final ~\pagebreak[0]~ or ~\nopagebreak[0]~ has no
effect---but this will make a difference after headings only,
where nobody should place such a thing anyway.
\begin{code}\begin{verbatim}
       \xdef\@LN@parpgbrk
         \penalty\the\count@
         \global\let\noexpand\@LN@parpgbrk
                      \noexpand\@LN@screenoff@pen
\end{verbatim}
\end{code}
That penalty will replace former ~\kern\z@~ in
~\linenumberpar~, see subsection_\ref{ss:calls}.---A
few days earlier, I tried to send just a penalty value.
However, the ~\kern\z@~ in ~\linenumberpar~ is crucial,
as I then found out. See below.---The final penalty is
repeated, but this does no harm. (It would not be very
difficult to avoid the repeating, but it may even be
less efficient.) It may be repeated due to the previous
~\xdef~, but it may be repeated as well below in the
present macro where artificial interline penalty is to
be overridden.
\begin{code}\begin{verbatim}
     \fi
   \else
\end{verbatim}
\end{code}
(/New v4.00)
\begin{code}\begin{verbatim}
     \@tempcnta\outputpenalty
     \advance\@tempcnta -\linenopenalty
\end{verbatim}
\end{code}
(New v4.00)
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
followed previously. To give ~\nopagebreak~ a chance,
we do
\begin{code}\begin{verbatim}
     \penalty \ifnum\count@<\@tempcnta \@tempcnta \else \count@ \fi
\end{verbatim}
\end{code}
instead.---In ~linenox0.sty~, the ~\else~ thing once was omitted.
Sergei Mariev's complaint (thanks!) showed that it is vital
(see comment before ~\MakeLineNo~).
The remaining ~\fi~ from previous package version closes the
~\ifnum\outputpenalty~\dots
(/New v4.00)
\begin{code}\begin{verbatim}
   \fi
   }
\end{verbatim}
\end{code}
(New v4.00)
\begin{code}\begin{verbatim}
\newcommand\stepLineNumber{\stepcounter{linenumber}}
\end{verbatim}
\end{code}
For reason, see use above. (/New v4.00)

(New v4.4)   The depth preserving trick is drawn here from
~\MakeLineNo~ because it will be used again in
section_\ref{ss:calls}.
\begin{code}\begin{verbatim}
\def\@LN@depthbox
  \dp\@tempboxa=\@tempdima
  \nointerlineskip \kern-\@tempdima \box\@tempboxa}
\end{verbatim}
\end{code}
(/New v4.4)

\section{%
Control line numbering
\unskip}
\subsection{%
Inserting \scs{output} calls
\unskip}\label{ss:calls}
The line numbering is controlled via ~\par~.  \LaTeX\
saved the \TeX-primitive ~\par~ in ~\@@par~.  We push it
one level further out, and redefine ~\@@par~ to insert
the ~\interlinepenalty~ needed to trigger the
line numbering. And we need to allow pagebreaks after a
paragraph.

New (2.05beta): the prevgraf test.  A paragraph that ends with a
displayed equation, a ~\noindent\par~ or ~wrapfig.sty~ produce empty
paragraphs. These should not get a spurious line number via
~\linenopenaltypar~.
\begin{code}\begin{verbatim}
\let\@@@par\@@par
\newcount\linenoprevgraf
\end{verbatim}
\end{code}
(UL)                          And needs ~\linenoprevgraf~
to be a counter? Perhaps there may be a paragraph having
thousands of lines, so ~\mathchardef~ doesn't suffice (really??).
A macro ending on ~\relax~ might suffice, but would be
somewhat slow. I think I will use ~\mathchardef~ next time.
Or has any user used ~\linenoprevgraf~? (/UL)
\begin{code}\begin{verbatim}
\def\linenumberpar
  \ifvmode \@@@par \else
    \ifinner \@@@par \else
      \xdef\@LN@outer@holdins{\the\holdinginserts
      \advance \interlinepenalty \linenopenalty
      \linenoprevgraf \prevgraf
      \global \holdinginserts \thr@@
      \@@@par
      \ifnum\prevgraf>\linenoprevgraf
        \penalty-\linenopenaltypar
      \fi
\end{verbatim}
\end{code}
(New v4.00)
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
was here previously. What for?
According to \TeX book p._125, Stephan's
interline penalty is changed into 10000. At the end of a
paragraph, the ~\parskip~ would follow that penalty of 10000,
so there could be a page break neither at the
~\parskip~ nor at the ~\baselineskip~ (\TeX book p._110)---so
there could never be a page break between two paragraphs.
So something must screen off the 10000 penalty.
Indeed, the ~\kern~ is a place to break.
(Stephan once knew this: see `allow pagebreaks' above.)

Formerly, I tried to replace ~\kern\z@~ by
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
---but this allows a page break after heading. So:
\begin{code}\begin{verbatim}
      \@LN@parpgbrk
\end{verbatim}
\end{code}

These and similar changes were formerly done by ~linenox1.sty~.
(/New v4.00)

(New v4.4)
A ~\belowdisplayskip~ may precede the previous when the paragraph
ends on a display-math; or there may be a ~\topsep~ from a list, etc.
~\addvspace~ couldn't take account for it with ~\kern\z@~
here. v4.32 therefore moved the space down -- with at least two
bad consequences.
Moreover, David Josef Dev observes that ~\kern\z@~ may
inappropriately yield column depth 0pt.
For these reasons, we introduce ~\@LN@screenoff@pen~ below.
(/New v4.4)
\begin{code}\begin{verbatim}
      \global\holdinginserts\@LN@outer@holdins
      \advance\interlinepenalty -\linenopenalty
    \fi
  \fi}
\end{verbatim}
\end{code}
(New v4.00, v4.4) Initialize ~\@LN@parpgbrk~, accounting
for earlier space and for appropriate columndepth.
We use former ~\MakeLineNo~'s depth-preverving trick
~\@LN@depthbox~ again:
\begin{code}\begin{verbatim}
\def\@LN@screenoff@pen
  \ifdim\lastskip=\z@
    \@tempdima\prevdepth \setbox\@tempboxa\null
    \@LN@depthbox                           \fi}

\global\let\@LN@parpgbrk\@LN@screenoff@pen
\end{verbatim}
\end{code}
(/New v4.4, v4.00)
\subsection{%
Turning on/off
\unskip}\label{ss:OnOff}
The basic commands to enable and disable line numbers.
~\@par~ and ~\par~ are only touched, when they are ~\let~
to ~\@@@par~/~\linenumberpar~.  The line number may be
reset to 1 with the star-form, or set by an optional
argument ~[~<number>~]~.

(New v4.00)        We add ~\ifLineNumbers~ etc.\ since
a number of our new adjustments need to know whether
linenumbering is active. This just provides a kind of
shorthand for ~\ifx\@@par\linenumberpar~; moreover it is
more stable: who knows what may happen to ~\@@par~?---A
caveat: ~\ifLineNumbers~ may be wrong. E.g., it may be
~\iffalse~ where it acts, while a ~\linenumbers~ a few
lines below---in the same paragraph---brings about that
the line where the ~\ifLineNumbers~ appears gets a
marginal number.
(New v4.3)        Just noticed: Such tricks have been
disallowed with v4.11, see subsections_\ref{ss:LL}
and_\ref{ss:OnOff}.---Moreover, the switching between
meanings of ~\linelabel~ for a possible error message
as of v4.11 is removed. Speed is difficult to esteem
and also depends on applications. Just use the most
simple code you find.                      (/New v4.3)
\begin{code}\begin{verbatim}
\newif\ifLineNumbers \LineNumbersfalse
\end{verbatim}
\end{code}
(/New v4.00)
\begin{code}\begin{verbatim}
\def\linenumbers
     \LineNumberstrue
     \xdef\@LN@outer@holdins{\the\holdinginserts
\end{verbatim}
\end{code}
(New v4.3) The previous line is for ~{linenomath}~
in a first numbered paragraph.         (/New v4.3)
\begin{code}\begin{verbatim}
     \let\@@par\linenumberpar

     \ifx\@par\@@@par\let\@par\linenumberpar\fi
     \ifx\par\@@@par\let\par\linenumberpar\fi
     \@LN@maybe@moduloresume
     \@ifnextchar[{\resetlinenumber
                 {\@ifstar{\resetlinenumber}{}}%
     }

\def\nolinenumbers
  \LineNumbersfalse
  \let\@@par\@@@par

  \ifx\@par\linenumberpar\let\@par\@@@par\fi
  \ifx\par\linenumberpar\let\par\@@@par\fi
  }
\end{verbatim}
\end{code}
(New v4.00)               Moreover, it is useful to switch to
~\nolinenumbers~ in ~\@arrayparboxrestore~. We postpone this
to section_\ref{ss:ReDef} where we'll have an appending macro
for doing this.                                  (/New v4.00)

What happens with a display math?  Since ~\par~ is not executed,
when breaking the lines before a display, they will not get
line numbers.  Sorry, but I do not dare to change
~\interlinepenalty~ globally, nor do I want to redefine
the display math environments here.
\begin{displaymath}
display \ math
\end{displaymath}
See the subsection below, for a wrapper environment to make
it work.  But that requires to wrap each and every display
in your \LaTeX\ source
(see option ~displaymath~ in subsections_\ref{ss:v3opts}
and_\ref{ss:display} for some relief [UL]).

The next two commands are provided to turn on line
numbering in a specific mode. Please note the difference:
for pagewise numbering, ~\linenumbers~ comes first to
inhibit it from seeing optional arguments, since
re-/presetting the counter is useless.
\begin{code}\begin{verbatim}
\def\linenumbers\setpagewiselinenumbers{\linenumbers\setpagewiselinenumbers}
\def\setrunninglinenumbers\linenumbers{\setrunninglinenumbers\linenumbers}
\end{verbatim}
\end{code}
Finally, it is a \LaTeX\ style, so we provide for the use
of environments, including the suppression of the
following paragraph's indentation.

(UL)                                I am drawing the following
private thoughts of Stephan's to publicity so that others may
think about them---or to remind myself of them in an efficient
way.                                                     (/UL)
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
(UL)     However, I rather think that ~\linenumbers~ and
~\nolinenumbers~ should execute a ~\par~ already. (Then the
~\par~s in the following definitions should be removed.) (/UL)
\begin{code}\begin{verbatim}
\@namedef{linenumbers*}{\par\linenumbers*}
\@namedef{runninglinenumbers*}{\par\setrunninglinenumbers\linenumbers*}

\def\par\@endpetrue{\par\@endpetrue}
\let\endrunninglinenumbers\par\@endpetrue
\let\endpagewiselinenumbers\par\@endpetrue
\expandafter\let\csname endlinenumbers*\endcsname\par\@endpetrue
\expandafter\let\csname endrunninglinenumbers*\endcsname\par\@endpetrue
\let\endnolinenumbers\par\@endpetrue
\end{verbatim}
\end{code}

\subsection{%
Display math
\unskip}\label{ss:DM}

Now we tackle the problem to get display math working.
There are different options.
\begin{enumerate}\item[
1.]  Precede every display math with a ~\par~.
Not too good.
\item[
2.]  Change ~\interlinepenalty~ and associates globally.
Unstable.
\item[
3.]  Wrap each display math with a ~{linenomath}~
environment.
\end{enumerate}
We'll go for option 3.  See if it works:
\begin{linenomath}
\begin{equation}
display \ math
\end{equation}
\end{linenomath}
The star form ~{linenomath*}~ should also number the lines
of the display itself,
\begin{linenomath*}
\begin{eqnarray}
multi   && line \\
display && math \\
&
\begin{array}{c}
with \\
array
\end{array}
&
\end{eqnarray}
\end{linenomath*}
including multline displays.

First, here are two macros to turn
on linenumbering on paragraphs preceeding displays, with
numbering the lines of the display itself, or without.
The ~\ifx..~ tests if line numbering is turned on.  It
does not harm to add these wrappers in sections that are
not numbered.  Nor does it harm to wrap a display
twice, e.q, in case you have some ~{equation}~s wrapped
explicitely, and later you redefine ~\equation~ to do it
automatically.

(New v4.3)  To avoid the spurious line number above a
display in vmode, I insert ~\ifhmode~.       (/New v4.3)
\begin{code}\begin{verbatim}
\newcommand\linenomathNonumbers{%
  \ifLineNumbers
    \ifnum\interlinepenalty>-\linenopenaltypar
      \global\holdinginserts\thr@@
      \advance\interlinepenalty \linenopenalty
     \ifhmode
      \advance\predisplaypenalty \linenopenalty
     \fi
    \fi
  \fi
  \ignorespaces
  }

\newcommand\linenomathWithnumbers{%
  \ifLineNumbers
    \ifnum\interlinepenalty>-\linenopenaltypar
      \global\holdinginserts\thr@@
      \advance\interlinepenalty \linenopenalty
     \ifhmode
      \advance\predisplaypenalty \linenopenalty
     \fi
      \advance\postdisplaypenalty \linenopenalty
      \advance\interdisplaylinepenalty \linenopenalty
    \fi
  \fi
  \ignorespaces
  }
\end{verbatim}
\end{code}
The ~{linenomath}~ environment has two forms, with and
without a star.  The following two macros define the
environment, where the stared/non-stared form does/doesn't number the
lines of the display or vice versa.
\begin{code}\begin{verbatim}
\newcommand\linenumberdisplaymath{%
  \def\linenomath{\linenomathWithnumbers}%
  \@namedef{linenomath*}{\linenomathNonumbers}%
  }

\newcommand\nolinenumberdisplaymath{%
  \def\linenomath{\linenomathNonumbers}%
  \@namedef{linenomath*}{\linenomathWithnumbers}%
  }

\def\endlinenomath
  \ifLineNumbers
   \global\holdinginserts\@LN@outer@holdins
  \fi
   \global
   \@ignoretrue
}
\expandafter\let\csname endlinenomath*\endcsname\endlinenomath
\end{verbatim}
\end{code}
The default is not to number the lines of a display.  But
the package option ~mathlines~ may be used to switch
that behavior.
\begin{code}\begin{verbatim}
\nolinenumberdisplaymath
\end{verbatim}
\end{code}

\section{%
Line number references
\unskip}\label{s:LNref}
\subsection
Internals
\unskip}
The only way to get a label to a line number in a
paragraph is to ask the output routine to mark it.

(New v4.00) The following two paragraphs don't hold any
longer, see below. (/New v4.00)
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
A ~\newlabel~ is written to the aux-file.  The reference
is to ~\theLineNumber~, \emph{not} ~\thelinenumber~.
This allows to hook in, as done below for pagewise line
numbering.

(New v3.03) The ~\@LN@ExtraLabelItems~ are added for a hook
to keep packages like ~{hyperref}~ happy.      (/New v3.03)

(New v4.00)
We fire the ~\marginpar~ mechanism, so we leave \LaTeX's
~\@addmarginpar~ untouched.
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
OK, we keep Stephan's ~\@LN@ExtraLabelItems~:
(/New v4.00)
\begin{code}\begin{verbatim}
\let\@LN@ExtraLabelItems\@empty
\end{verbatim}
\end{code}
(New v4.00)
We imitate the ~\marginpar~ mechanism without using the
~\@freelist~ boxes. ~\linelabel~ will indeed place a signal
penalty (~\@Mllbcodepen~, new), and it will put a label into
some list macro ~\@LN@labellist~. A new part of the output
routine will take the labels from the list and will write
~\newlabel~s to the .aux file.

The following is a version of \LaTeX's ~\@xnext~.
\begin{code}\begin{verbatim}
\def\@LN@xnext#1\@lt#2\@@#3#4{\def#3{#1}\gdef#4{#2}}
\end{verbatim}
\end{code}
This takes an item ~#1~ from a list ~#4~ into ~#3~;
to be used as ~\expandafter\@LN@xnext#4\@@#3#4~.
Our lists use ~\@lt~ after each item for separating.
Indeed, there will be another list macro which can
appear as argument ~#4~, this will be used for moving
~\vadjust~ items (section_\ref{ss:PVadj}).
The list for ~\linelabel~s is the following:
\begin{code}\begin{verbatim}
\global\let\@LN@labellist\@empty
\end{verbatim}
\end{code}
The next is the new part of the output routine writing the
~\newlabel~ to the .aux file. Since it is no real page output,
the page is put back to top of the main vertical list.
\begin{code}\begin{verbatim}
\def\WriteLineNo
  \unvbox\@cclv
  \expandafter \@LN@xnext \@LN@labellist \@@
                          \@LN@label \@LN@labellist
  \protected@write\@auxout{}{\string\newlabel{\@LN@label
         {{\theLineNumber}{\thepage}\@LN@ExtraLabelItems}
}
\end{verbatim}
\end{code}
(/New v4.00)

\subsection{%
The \scs{linelabel} command
\unskip}\label{ss:LL}
To refer to a place in line ~\ref{~<foo>~}~ at page
~\pageref{~<foo>~}~ you place a ~\linelabel{~<foo>~}~ at
that place.

\linelabel{demo}
\marginpar{\tiny\raggedright
See if it works: This paragraph
starts on page \pageref{demo}, line
\ref{demo}.
\unskip}%
(New v4.11)
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
This trick is better not allowed---see subsections_\ref{ss:LL}
and_\ref{ss:OnOff}.
(/New v4.11)

~\linelabel~
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
puts a
~\penalty~ into a ~\vadjust~, which triggers the
pagebuilder after putting the current line to the main
vertical list.  A ~\write~ is placed on the main vertical
list, which prints a reference to the current value of
~\thelinenumber~ and ~\thepage~ at the time of the
~\shipout~.

A ~\linelabel~ is allowed only in outer horizontal mode.
In outer vertical mode we start a paragraph, and ignore
trailing spaces (by fooling ~\@esphack~).

(New v4.00) We aim at relaxing the previous condition.
We insert a hook ~\@LN@mathhook~ and a shorthand
~\@LN@postlabel~ to support the ~mathrefs~ option which
allows ~\linelabel~ in math mode.

The next paragraph is no longer valid.
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
(/New v4.00)

(New v4.11)
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
I forgot ~\linenumbers~ today, costed me hours or so.
\begin{code}\begin{verbatim}
\def\@LN@LLerror{\PackageError{lineno}
  \string\linelabel\space without \string\linenumbers}
  Just see documentation. (New feature v4.11)}\@gobble}
\end{verbatim}
\end{code}
(New v4.3)         Here some things have changed for v4.3.
The previous ~#1~ has been replaced by ~\@gobble~.
Ensuing, the ~\linelabel~ error message is re-implemented.
I find it difficult to compare efficiency of slight
alternatives---so choose an easy one. Explicit switching
in ~\linenumbers~ and ~\nolinenumbers~ is an additional
command that may better be avoided.
\begin{code}\begin{verbatim}
\newcommand\linelabel
  \ifLineNumbers \expandafter \@LN@linelabel
  \else          \expandafter \@LN@LLerror   \fi}

\gdef\@LN@linelabel#1
\end{verbatim}
\end{code}
~\gdef~ for hyperref ``symbolically''. (/New v4.11)
\begin{code}\begin{verbatim}
  \ifx\protect\@typeset@protect
\end{verbatim}
\end{code}
$\gets$ And a ~\linelabel~ should never be replicated in a
mark or a TOC entry.                           (/New v4.3)
\begin{code}\begin{verbatim}
   \ifvmode
       \ifinner \else
          \leavevmode \@bsphack \@savsk\p@
       \fi
   \else
       \@bsphack
   \fi
   \ifhmode
     \ifinner
       \@parmoderr
     \else
\end{verbatim}
\end{code}
(New v4.00)
\begin{code}\begin{verbatim}
       \@LN@postlabel{#1
\end{verbatim}
\end{code}
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
(/New v4.00)
\begin{code}\begin{verbatim}
       \@esphack
\end{verbatim}
\end{code}
(New v4.00)
The ~\@ignorefalse~ was appropriate before because the
~\@Esphack~ in ~\end@float~ set ~\@ignoretrue~. Cf._\LaTeX's
~\@xympar~. (/New v4.00)
\begin{code}\begin{verbatim}
     \fi
   \else
\end{verbatim}
\end{code}
(New v4.00)
\begin{code}\begin{verbatim}
     \@LN@mathhook{#1}%
\end{verbatim}
\end{code}
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
Instead of complaining, you may just do your job.
(/New v4.00)
\begin{code}\begin{verbatim}
   \fi
  \fi
   }
\end{verbatim}
\end{code}
(New v4.00)   The shorthand just does what happened
with ~linenox0.sty~ before ~ednmath0.sty~ (New v4.1:
now ~mathrefs~ option) appeared, and
the hook is initialized to serve the same purpose.
So errors come just where Stephan had built them in,
and this is just the \LaTeX\ ~\marginpar~ behaviour.
\begin{code}\begin{verbatim}
\def\@LN@postlabel#1{\g@addto@macro\@LN@labellist{#1\@lt}%
       \vadjust{\penalty-\@Mllbcodepen}}
\def\@LN@mathhook#1{\@parmoderr}
\end{verbatim}
\end{code}
(/New v4.00)

\modulolinenumbers[3]
\firstlinenumber{1}
\section{%
The appearance of the line numbers
\unskip}\label{appearance}
\subsection{%
Basic code
\unskip}

The line numbers are set as ~\tiny\sffamily\arabic{linenumber}~,
$10pt$ left of the text.  With options to place it
right of the text, or . . .

. . . here are the hooks:
\begin{code}\begin{verbatim}
\def\makeLineNumberLeft
  \hss\normalfont\tiny\sffamily\LineNumber\hskip\linenumbersep}

\def\makeLineNumberRight
  \normalfont\tiny\sffamily\hskip\linenumbersep\hskip\columnwidth
  \hb@xt@\linenumberwidth{\hss\LineNumber}\hss}

\def\normalfont\tiny\sffamily{\normalfont\tiny\sffamily}

\newdimen\linenumbersep
\newdimen\linenumberwidth

\linenumberwidth=10pt
\linenumbersep=10pt
\end{verbatim}
\end{code}
Margin switching requires ~pagewise~ numbering mode, but
choosing the left or right margin for the numbers always
works.
\begin{code}\begin{verbatim}
\def\switchlinenumbers{\@ifstar
    {\let\makeLineNumberOdd\makeLineNumberRight
     \let\makeLineNumberEven\makeLineNumberLeft}%
    {\let\makeLineNumberOdd\makeLineNumberLeft
     \let\makeLineNumberEven\makeLineNumberRight}%
    }

\def\setmakelinenumbers#1{\@ifstar
  {\let\makeLineNumberRunning#1%
   \let\makeLineNumberOdd#1%
   \let\makeLineNumberEven#1}%
  {\ifx\c@linenumber\c@runninglinenumber
      \let\makeLineNumberRunning#1%
   \else
      \let\makeLineNumberOdd#1%
      \let\makeLineNumberEven#1%
   \fi}%
  }

\def\setmakelinenumbers\makeLineNumberLeft{\setmakelinenumbers\makeLineNumberLeft}
\def\setmakelinenumbers\makeLineNumberRight{\setmakelinenumbers\makeLineNumberRight}

\setmakelinenumbers\makeLineNumberLeft*
\end{verbatim}
\end{code}
~\LineNumber~ is a hook which is used for the modulo stuff.
It is the command to use for the line number, when you
customize ~\makeLineNumber~.  Use ~\thelinenumber~ to
change the outfit of the digits.

We will implement two modes of operation:
\begin{itemize}
\item  numbers ~running~ through (parts of) the text
\item  ~pagewise~ numbers starting over with one on top of
each page.
\end{itemize}
Both modes have their own count register, but only one is
allocated as a \LaTeX\ counter, with the attached
facilities serving both.
\begin{code}\begin{verbatim}
\newcounter{linenumber}
\newcount\c@pagewiselinenumber
\let\c@runninglinenumber\c@linenumber
\end{verbatim}
\end{code}
Only the running mode counter may be reset, or preset,
for individual paragraphs.  The pagewise counter must
give a unique anonymous number for each line.

(New v4.3)                  ~\newcounter{linenumber}~
was the only ~\newcounter~ in the whole package, and
formerly I was near using ~\newcount~ instead. Yet
~\newcounter~ may be quite useful for ~\includeonly~.
It also supports resetting ``subcounters'', but what
could these be? Well, ~edtable~ might introduce a
subcounter for columns.
(Note that \LaTeX's setting commands would work with
~\newcount\c@linenumber~ already, apart from this.
And perhaps sometimes ~\refstepcounter{linenumber}~
wouldn't work---cf._my discussion of ~\stepcounter~ in
subsection_\ref{ss:MLN}, similarly ~\refstep...~ would
be quite useless.
Even the usual redefinitions of ~\thelinenumber~ would
work. It is nice, on the other hand, that
~\thelinenumber~ is predefined here. \LaTeX's
initialization of the value perhaps just serves making
clear \LaTeX\ counters should always be changed
globally.---Shortened and improved the discussion here.)
(/New v4.3)

(New v4.22)
~\c@linenumber~ usually is---globally---incremented by
~\stepcounter~ (at present), so resetting it locally would
raise the save stack problem of \TeX book p._301, moreover
it would be is useless, there is no hope of keeping the
values local (but see subsection_\ref{ss:ILN}). So I insert
~\global~:        (/New v4.22)
\begin{code}\begin{verbatim}
\newcommand*\resetlinenumber[1][\@ne]
  \global
  \c@runninglinenumber#1\relax}
\end{verbatim}
\end{code}
(New v4.00)
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
Added ~\relax~, being quite sure that this does no harm
and is quite important, as with ~\setcounter~ etc.
I consider this a bug fix (although perhaps no user has
ever had a problem with this).    (/New v4.00)

(v4.22: I had made much fuss about resetting subordinate
counters here---removed, somewhat postponed.)

\subsection{%
Running line numbers
\unskip}

Running mode is easy,  ~\LineNumber~ and ~\theLineNumber~
produce ~\thelinenumber~, which defaults to
~\arabic{linenumber}~, using the ~\c@runninglinenumber~
counter.  This is the default mode of operation.
\begin{code}\begin{verbatim}
\def\makeLineNumberRunning{\makeLineNumberRunning}

\def\setrunninglinenumbers{%
   \def\theLineNumber{\thelinenumber}%
   \let\c@linenumber\c@runninglinenumber
   \let\makeLineNumber\makeLineNumberRunning
   }

\setrunninglinenumbers\resetlinenumber
\end{verbatim}
\end{code}

\subsection{%
Pagewise line numbers
\unskip}\label{ss:PW}

Difficult, if you think about it.  The number has to be
printed when there is no means to know on which page it
will end up,  except through the aux-file.  My solution
is really expensive, but quite robust.

With version ~v2.00~ the hashsize requirements are
reduced, because we do not need one controlsequence for
each line any more.  But this costs some computation time
to find out on which page we are.

~\makeLineNumber~ gets a hook to log the line and page
number to the aux-file.  Another hook tries to find out
what the page offset is, and subtracts it from the counter
~\c@linenumber~.  Additionally, the switch
~\ifoddNumberedPage~ is set true for odd numbered pages,
false otherwise.
\begin{code}\begin{verbatim}
\def\setpagewiselinenumbers{%
   \let\theLineNumber\thePagewiseLineNumber
   \let\c@linenumber\c@pagewiselinenumber
   \let\makeLineNumber\makePagewiseLineNumber
   }

\def\makePagewiseLineNumber{\logtheLineNumber\getLineNumber
  \ifoddNumberedPage
     \makeLineNumberOdd
  \else
     \makeLineNumberEven
  \fi
  }
\end{verbatim}
\end{code}
Each numbered line gives a line to the aux file
\begin{verse}
~\@LN{~<line>~}{~<page>~}~
\end{verse}
very similar to the ~\newlabel~ business, except that we need
an arabic representation of the page number, not what
there might else be in ~\thepage~.
\begin{code}\begin{verbatim}
\def\logtheLineNumber{\protected@write\@auxout{}{%
\end{verbatim}
\end{code}
(New v4.00) (UL)
As Daniel Doherty observed, the earlier line
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
here may lead into an infinite loop when the user resets
the page number (think of ~\pagenumbering~, e.g.).
Stephan and I brief\/ly discussed the matter and decided
to introduce a ``physical''-page counter to which
~\logtheLineNumber~ refers. It was Stephan's idea to use
~\cl@page~ for reliably augmenting the ``physical''-page
counter. However, this relies on the output routine once
doing ~\stepcounter{page}~. Before Stephan's
suggestion, I had thought of appending the stepping to
\LaTeX's ~\@outputpage~.---So the macro definition ends
as follows.
\begin{code}\begin{verbatim}
   \string\@LN{\the\c@linenumber}
\end{verbatim}
\end{code}
(New v4.2)
The `truepage' counter must start with ~\c@~ so it works
with ~\include~, and the ~\@addtoreset~ below is needed
for the same purpose.
\begin{code}\begin{verbatim}
     \noexpand\the\c@LN@truepage}}}

\newcount\c@LN@truepage
\g@addto@macro\cl@page{\global\advance\c@LN@truepage\@ne}
\@addtoreset{LN@truepage}{@ckpt}
\end{verbatim}
\end{code}
(/New v4.2)                I had thought of offering more
features of a \LaTeX\ counter. However, the user should
better \emph{not} have access to this counter. ~\c@page~
should suffice as a pagewise master counter.---To be sure,
along the present lines the user \emph{can} manipulate
~\c@LN@truepage~ by ~\stepcounter{page}~. E.g., she might
do this in order to manually insert a photograph. Well,
seems not to harm.

The above usage of ~\g@addto@macro~ and ~\cl@page~ may be
not as stable as Stephan intended. His proposal used
~\xdef~ directly. But he used ~\cl@page~ as well, and who
knows \dots{} And as to ~\g@addto@macro~, I have introduced
it for list macros anyway.
(/UL) (/New v4.00)

From the aux-file we get one macro ~\LN@P~<page> for each
page with line numbers on it.  This macro calls four other
macros with one argument each.  These macros are
dynamically defined to do tests and actions, to find out
on which page the current line number is located.

We need sort of a pointer to the first page with line
numbers, initiallized to point to nothing:
\begin{code}\begin{verbatim}
\def\LastNumberedPage{first}
\def\LN@Pfirst{\nextLN\relax}
\end{verbatim}
\end{code}
The four dynamic macros are initiallized to reproduce
themselves in an ~\xdef~
\begin{code}\begin{verbatim}
\let\lastLN\relax
\let\firstLN\relax
\let\pageLN\relax
\let\nextLN\relax
\end{verbatim}
\end{code}
During the end-document run through the aux-files, we
disable ~\@LN~.  I may put in a check here later, to give
a rerun recommendation.
\begin{code}\begin{verbatim}
\AtEndDocument{\let\@LN\@gobbletwo}
\end{verbatim}
\end{code}
Now, this is the tricky part.  First of all, the whole
definition of ~\@LN~ is grouped, to avoid accumulation
on the save stack. Somehow ~\csname~<cs>~\endcsname~ pushes
an entry, which stays after an ~\xdef~ to that <cs>.

If ~\LN@P~<page> is undefined, initialize it with the
current page and line number, with the
\emph{pointer-to-the-next-page} pointing to nothing.  And
the macro for the previous page will be redefined to point
to the current one.

If the macro for the current page already exists, just
redefine the \emph{last-line-number} entry.

Finally, save the current page number, to get the pointer to the
following page later.
\begin{code}\begin{verbatim}
\def\@LN#1#2{{\expandafter\@@LN
                 \csname LN@P#2C\@LN@column\expandafter\endcsname
                 \csname LN@PO#2\endcsname
                 {#1}{#2}}}

\def\@@LN#1#2#3#4{\ifx#1\relax
    \ifx#2\relax\gdef#2{#3}\fi
    \expandafter\@@@LN\csname LN@P\LastNumberedPage\endcsname#
    \xdef#1{\lastLN{#3}\firstLN{#3
            \pageLN{#4}{\@LN@column}{#2}\nextLN\relax}%
  \else
    \def\lastLN##1{\noexpand\lastLN{#3}}%
    \xdef#1{#1}%
  \fi
  \xdef\LastNumberedPage{#4C\@LN@column}}
\end{verbatim}
\end{code}
The previous page macro gets its pointer to the
current one, replacing the ~\relax~ with the cs-token
~\LN@P~<page>.
\begin{code}\begin{verbatim}
\def\@@@LN#1#2{{\def\nextLN##1{\noexpand\nextLN\noexpand#2}%
                \xdef#1{#1}}}
\end{verbatim}
\end{code}
Now, to print a line number, we need to find the page,
where it resides.  This will most probably be the page where
the last one came from, or maybe the next page.  However, it can
be a completely different one.  We maintain a cache,
which is ~\let~ to the last page's macro.  But for now
it is initialized to expand ~\LN@first~, where the poiner
to the first numbered page has been stored in.
\begin{code}\begin{verbatim}
\def\LN@Pfirst{\LN@Pfirst}
\end{verbatim}
\end{code}
To find out on which page the current ~\c@linenumber~ is,
we define the four dynamic macros to do something usefull
and execute the current cache macro.  ~\lastLN~ is run
first, testing if the line number in question may be on a
later page.  If so, disable ~\firstLN~, and go on to the
next page via ~\nextLN~.
\begin{code}\begin{verbatim}
\def\testLastNumberedPage#1{\ifnum#1<\c@linenumber
      \let\firstLN\@gobble
  \fi}
\end{verbatim}
\end{code}
Else, if ~\firstLN~ finds out that we need an earlier
page,  we start over from the beginning. Else, ~\nextLN~
will be disabled, and ~\pageLN~ will run
~\gotNumberedPage~ with four arguments: the first line
number on this column, the page number, the column
number, and the first line on the page.
\begin{code}\begin{verbatim}
\def\testFirstNumberedPage#1{\ifnum#1>\c@linenumber
     \def\nextLN##1{\testNextNumberedPage\LN@Pfirst}%
  \else
      \let\nextLN\@gobble
      \def\pageLN{\gotNumberedPage{#1}}%
  \fi}
\end{verbatim}
\end{code}
We start with ~\pageLN~ disabled and ~\nextLN~ defined to
continue the search with the next page.
\begin{code}\begin{verbatim}
\long\def \@gobblethree #1#2#3{}

\def\testNumberedPage{%
  \let\lastLN\testLastNumberedPage
  \let\firstLN\testFirstNumberedPage
  \let\pageLN\@gobblethree
  \let\nextLN\testNextNumberedPage
  \LN@Pfirst
  }
\end{verbatim}
\end{code}
When we switch to another page, we first have to make
sure that it is there.  If we are done with the last
page, we probably need to run \TeX\ again, but for the
rest of this run, the cache macro will just return four
zeros. This saves a lot of time, for example if you have
half of an aux-file from an aborted run,  in the next run
the whole page-list would be searched in vain again and
again for the second half of the document.

If there is another page, we iterate the search.
\begin{code}\begin{verbatim}
\def\testNextNumberedPage#1{\ifx#1\relax
     \global\def\LN@Pfirst{\gotNumberedPage0000}%
     \PackageWarningNoLine{lineno}%
                    {Linenumber reference failed,
      \MessageBreak  rerun to get it right}%
   \else
     \global\let\LN@Pfirst#1%
   \fi
   \testNumberedPage
   }
\end{verbatim}
\end{code}
\linelabel{demo2}
\marginpar{\tiny\raggedright
Let's see if it finds the label
on page \pageref{demo},
line \ref{demo}, and back here
on page \pageref{demo2}, line
\ref{demo2}.
\unskip}%
To separate the official hooks from the internals there is
this equivalence, to hook in later for whatever purpose:
\begin{code}\begin{verbatim}
\let\getLineNumber\testNumberedPage
\end{verbatim}
\end{code}
So, now we got the page where the number is on.  We
establish if we are on an odd or even page, and calculate
the final line number to be printed.
\begin{code}\begin{verbatim}
\newif\ifoddNumberedPage
\newif\ifcolumnwiselinenumbers
\columnwiselinenumbersfalse

\def\gotNumberedPage#1#2#3#4{\oddNumberedPagefalse
  \ifodd \if@twocolumn #3\else #2\fi\relax\oddNumberedPagetrue\fi
  \advance\c@linenumber\@ne
  \ifcolumnwiselinenumbers
     \subtractlinenumberoffset{#1}%
  \else
     \subtractlinenumberoffset{#4}%
  \fi
  }
\end{verbatim}
\end{code}
You might want to run the pagewise mode with running line
numbers, or you might not.  It's your choice:
\begin{code}\begin{verbatim}
\def\runningpagewiselinenumbers{%
  \let\subtractlinenumberoffset\@gobble
  }

\def\realpagewiselinenumbers{%
  \def\subtractlinenumberoffset##1{\advance\c@linenumber-##1\relax}%
  }

\realpagewiselinenumbers
\end{verbatim}
\end{code}
For line number references, we need a protected call to
the whole procedure, with the requested line number stored
in the ~\c@linenumber~ counter.  This is what gets printed
to the aux-file to make a label:
\begin{code}\begin{verbatim}
\def\thePagewiseLineNumber{\protect
       \getpagewiselinenumber{\the\c@linenumber}}%
\end{verbatim}
\end{code}
And here is what happens when the label is refered to:
\begin{code}\begin{verbatim}
\def\getpagewiselinenumber#1{{%
  \c@linenumber #1\relax\testNumberedPage
  \thelinenumber
  }}
\end{verbatim}
\end{code}
A summary of all per line expenses:
\begin{description}\item
[CPU:]  The ~\output~ routine is called for each line,
and the page-search is done.
\item
[DISK:] One line of output to the aux-file for each
numbered line
\item
[MEM:]  One macro per page. Great improvement over v1.02,
which had one control sequence per line in
addition.  It blew the hash table after some five
thousand lines.
\end{description}

\subsection{%
Twocolumn mode (New v3.06)
\unskip}

Twocolumn mode requires another patch to the ~\output~
routine, in order to print a column tag to the .aux
file.
\begin{code}\begin{verbatim}
\AtBeginDocument

  \let\@LN@orig@makecol\@makecol}
\def\@LN@makecol{%
   \@LN@orig@makecol
   \setbox\@outputbox \vbox{%
      \boxmaxdepth \@maxdepth
      \protected@write\@auxout{}
          \string\@LN@col{\if@firstcolumn1\else2\fi}%
      }%
      \box\@outputbox

}

\def\@LN@col{\def\@LN@column}
\@LN@col{1}
\end{verbatim}
\end{code}

\subsection{%
Numbering modulo $m$, starting at $f$
\unskip}\label{ss:Mod}

Most users want to have only one in five lines numbered.
~\LineNumber~ is supposed to produce the outfit of the
line number attached to the line,  while ~\thelinenumber~
is used also for references, which should appear even if
they are not multiples of five.

(New v4.00)                   Moreover, some users want to
control which line number should be printed first. Support
of this is now introduced here---see ~\firstlinenumber~
below.---~numline.sty~ by Michael Jaegermann and
James Fortune offers controlling which \emph{final}
line numbers should not be printed. What is
it good for? We ignore this here until some user demands
it.---Peter Wilson's ~ledmac.sty~ offers much different
choices of line numbers to be printed, due to Wayne Sullivan.
(/New v4.00)

(New v4.22)   ~\c@linenumbermodulo~ is rendered a
fake counter, as discussed since v4.00. So it can
no longer be set by ~\setcounter~. ~\modulolinenumbers~
serves this purpose. Well, does anybody want to do
what worked with ~\addtocounter~? (Then please tell
me.)---At least, ~\value~ still works. For the same
purpose I rename the fake `firstlinenumber' counter
~\n@...~ to ~\c@...~.                  (/New v4.22)
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}

(New v4.00)                                                             \par
~\themodulolinenumber~ waits for being declared
~\LineNumber~ by ~\modulolinenumbers~. (This has
been so before, no change.) Here is how it
looked before:
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
(UL)                   This was somewhat slow. This arithmetic
happens at every line. This time I tend to declare an extra
line counter (as opposed to my usual recommendations to use
counters as rarely as possible) which is stepped every line.
It could be incremented in the same way as ~\c@LN@truepage~
is incremented via ~\cl@page~! This is another point in favour
of ~{linenumber}~ being a \LaTeX\ counter!
When this new counter equals ~\c@linenumbermodulo~, it is reset,
and ~\thelinenumber~ is executed.---It gets much slower by my
support of controlling the first line number below. I should
improve this.---On
the other hand, time expense means very little nowadays,
while the number of \TeX\ counters still is limited.

For the same purpose, moreover, attaching the line number
box could be intercepted earlier (in ~\MakeLineNo~),
without changing ~\LineNumber~. However, this may be
bad for the latter's announcement as a wizard interface
in section_\ref{s:UserCmds}.
(/UL)

Here is the new code. It is very near to my ~lnopatch.sty~
code which introduced the first line number feature
before.---I add starting with a ~\relax~ which is so often
recommended---without understanding this really. At least,
it will not harm.---Former group braces appear as
~\begingroup~/~\endgroup~ here.
\begin{code}\begin{verbatim}
\def\themodulolinenumber{\relax
  \ifnum\c@linenumber<\c@firstlinenumber \else
    \begingroup
      \@tempcnta\c@linenumber
      \advance\@tempcnta-\c@firstlinenumber
      \divide\@tempcnta\c@linenumbermodulo
      \multiply\@tempcnta\c@linenumbermodulo
      \advance\@tempcnta\c@firstlinenumber
      \ifnum\@tempcnta=\c@linenumber \thelinenumber \fi
    \endgroup
  \fi
}
\end{verbatim}
\end{code}
(/New v4.00)

The user command to set the modulo counter:
(New v4.31) \dots\ a star variant is introduced to implement
Hillel Chayim Yisraeli's idea to print the first line number
after an interruption of the edited text by some editor's
text, regardless of the modulo. If it is 1, it is printed only
with ~\firstlinenumber{1}~. I.e., you use ~\modulolinenumbers*~
for the new feature, without the star you get the simpler
behaviour that we have had so far. And you can switch back
from the refined behaviour to the simple one by using
~\modulolinenumbers~ without the star.---This enhancement
is accompanied by a new package option ~modulo*~ which just
executes ~\modulolinenumbers*~
(subsection_\ref{ss:v3opts}).---`With ~\firstlinenumber{1}~'
exactly means: `1' is printed if and only if the last
~\firstlinenumber~ before or in the paragraph that follows
the ``interruption'' has argument `1' (or something
\emph{expanding} to `1', or (to) something that \TeX\
``reads'' as 1, e.g.: a \TeX\ count register storing
1).---At present, this behaviour may be unsatisfactory with
pagewise line-numbering $\dots$ I'll make an experimental
extra package if someone complains \dots
\begin{code}\begin{verbatim}
\newcommand\modulolinenumbers
  \@ifstar
    {\def\@LN@maybe@moduloresume
       \global\let\@LN@maybe@normalLineNumber
                            \@LN@normalLineNumber
                                       \@LN@modulolinenos
    {\let\@LN@maybe@moduloresume\relax \@LN@modulolinenos}%
}

\global\let\@LN@maybe@normalLineNumber\relax
\let\@LN@maybe@moduloresume\relax
\gdef\@LN@normalLineNumber
  \ifnum\c@linenumber=\c@firstlinenumber \else
    \ifnum\c@linenumber>\@ne
      \def\LineNumber{\thelinenumber
    \fi
  \fi
\end{verbatim}
\end{code}
~\def~ instead of ~\let~ enables taking account of a
redefinition of ~\thelinenumber~ in a present numbering
environment (e.g.).
\begin{code}\begin{verbatim}
  \global\let\@LN@maybe@normalLineNumber\relax}
\end{verbatim}
\end{code}
Instead of changing ~\LineNumber~ directly by
~LN@moduloresume~, these tricks enable ~\modulolinenumbers*~
to act as locally as I can make it. I don't know how to
avoid that the output routine switches back to the normal
modulo behaviour by a global change. (An ~\aftergroup~ may
fail in admittedly improbable cases.)
\begin{code}\begin{verbatim}
\newcommand*\@LN@modulolinenos[1][\z@]{%
\end{verbatim}
\end{code}
The definition of this macro is that of the former
~\modulolinenumbers~.                 (/New v4.31)
\begin{code}\begin{verbatim}
  \let\LineNumber\themodulolinenumber
  \ifnum#1>\@ne
    \chardef
      \c@linenumbermodulo#1\relax
  \else\ifnum#1=\@ne
\end{verbatim}
\end{code}
\begin{old}\begin{verbatim}
\end{verbatim}
\end{old}
(New v4.00)         I am putting something here to enable
~\firstlinenumber~ with $~\c@linenumbermodulo~=1$.
With ~lnopatch.sty~, a trick was offered for this purpose.
It is now obsolete.

\begin{code}\begin{verbatim}
    \def\LineNumber{\@LN@ifgreat\thelinenumber
\end{verbatim}
\end{code}
(/New v4.00)
\begin{code}\begin{verbatim}
  \fi\fi
  }
\end{verbatim}
\end{code}
(New v4.00)                The default of ~\@LN@ifgreat~ is
\begin{code}\begin{verbatim}
\let\@LN@ifgreat\relax
\end{verbatim}
\end{code}
The previous changes as soon as ~\firstlinenumber~ is used:
\begin{code}\begin{verbatim}
\newcommand*\firstlinenumber[1]
  \chardef\c@firstlinenumber#1\relax
\end{verbatim}
\end{code}
No counter, little values allowed only---OK?---(UL)
The change is local---OK? The good thing is that
~\global\firstlinenumber{~<number>~}~ works. Moreover,
~\modulolinenumbers~ acts locally as well.    (/UL)

(New v4.31)
\begin{code}\begin{verbatim}
  \let\@LN@ifgreat\@LN@ifgreat@critical}

\def\@LN@ifgreat@critical{%
  \ifnum\c@linenumber<\c@firstlinenumber
    \expandafter \@gobble
  \fi
\end{verbatim}
\end{code}
(/New v4.31)

The default
value of ~\c@firstlinenumber~
is 0. This is best for what one would expect from modulo
printing.
\begin{code}\begin{verbatim}
\let\c@firstlinenumber=\z@
\end{verbatim}
\end{code}

For usage and effects of ~\modulolinenumbers~ and
~\firstlinenumbers~, please consult section_\ref{s:UserCmds}.
Two details on ~\firstlinenumbers~ here:
(i)_~\firstlinenumber~ acts on a paragraph if and only if
(a)_the paragraph is broken into lines ``in line-numbering
mode'' (after ~\linenumbers~, e.g.);
(b)_it is the last occurrence of a ~\firstlinenumbers~
before or in the paragraph.
(The practical applications of this that I can imagine
don't seem appealing to me.)
Cf._the explanation above of how ~\modulolinenumbers~ and
~\firstlinenumbers~ interact---for this and for (ii),
which is concerned with possible arguments for
~\firstlinenumbers~.

Note that the line numbers of the present section
demonstrate the two devices.         (/New v4.00)
\begin{code}\begin{verbatim}
\chardef\c@linenumbermodulo=5
\modulolinenumbers[1]
\end{verbatim}
\end{code}
(New v4.22)       The new implementation through ~\chardef~
decreases the functionality and raises certain compatibility
problems. I face this without fear. The maximum modulo value
is now ~255~. I expect that this suffices for usual applications.
However, some users have ``abused'' ~lineno.sty~ to get
~ednotes.sty~ features without line numbers, so have set the
modulo to a value beyond the total number of lines in their
edition. This ought to be replaced by
~\let\makeLineNumber\relax~.          (/New v4.22)

\section
Package options
\unskip}\label{s:Opts}

(New v4.1)
The last heading formerly was the heading of what is now
subsection_\ref{ss:v3opts}. The options declared there were
said to execute user commands only. This was wrong already
concerning ~displaymath~ and ~hyperref~. At least, however,
these options were no or almost no occasion to skip definitions
or allocations. This is different with the options that we now
insert.

\subsection{%
Extended referencing to line numbers. (v4.2)
\unskip}
This subsection explains and declares package option ~addpageno~.

If a line to whose number you refer by ~\ref~ is not on the
present page, it may be useful to add the number of the page
on which the line occurs---and perhaps it should not be added
otherwise. In general, you could use the Standard \LaTeX\
package varioref for this. However, the latter usually
produces verbose output like `on the preceding page'---
unless costumized---, while in critical editions, e.g., one
may prefer just adding the page number and some mark on the
left of the line number, irrespectively of how far the page is
apart etc. To support this, package option ~addpageno~
provides a command ~\vpagelineref~ to be used in place of
~\ref~. This produces, e.g., `34.15' when referring to line_15
on page_34 while the present page is not 34. You can customize
the outcome, see the package file ~vplref.sty~ where the code
and further details are. You may conceive of
~\vpagelineref~ as a certain customization of varioref's
~\vref~.

This implies that option ~addpageno~ requires the files
~vplref.sty~ and ~varioref.sty~. ~addpageno~ automatically
loads both of them. Yet you can also load ~varioref.sty~
on your own to use its package options.

Of course, you might better introduce a shorter command name
for ~\vpagelineref~ for your work, while we cannot predict
here what shorthand will fit your work. E.g.,
~\newcommand{\lref}{\vpagelineref}~.

If you really want to add the page number in \emph{any} case,
use, e.g., some ~\myref~ instead of ~\ref~, after
\[~newcommand*{\myref}{\pageref{#1}.\ref{#1}}~\]
or what you like. You don't need the ~addpageno~ option in
this case.

~addpageno~ is due to a suggestion by Sergei Mariev.
\begin{code}\begin{verbatim}
\DeclareOption{addpageno}
  \AtEndOfPackage{\RequirePackage{vplref}[2005/04/25]}}
\end{verbatim}
\end{code}
\subsection
\scs{linelabel} in math mode
\unskip}\label{ss:MathRef}

We have made some first steps towards allowing ~\linelabel~ in
math mode. Because our code for this is presently experimental,
we leave it to the user to decide for the experiment by calling
option ~mathrefs~. We are in a hurry now and thus leave the
code, explanations, and discussion in the separate package
~ednmath0.sty~. Maybe we later find the time to improve the
code and move the relevant content of ~ednmath0.sty~ to here.
The optimal situation would be to define ~\linelabel~ from
the start so it works in math mode, omitting the ~mathrefs~
option.

Actually, this package even provides adjustments for analogously
allowing ~ednotes.sty~ commands in math mode. Loading the package
is postponed to ~\AtBeginDocument~ when we know whether these
adjustments are needed.
\begin{code}\begin{verbatim}
\DeclareOption{mathrefs}{\AtBeginDocument
  {\RequirePackage{ednmath0}[2004/08/20]}}
\end{verbatim}
\end{code}

\subsection
Arrays, tabular environments (Revised v4.11)
\unskip}\label{ss:Tab}

This subsection explains and declares package options
~edtable~, ~longtable~, and ~nolongtablepatch~.

The standard \LaTeX\ tabular environments come as single
boxes, so the ~lineno.sty~ versions before v4.00 treated them as
(parts of) single lines, printing (at most) one line number
beside each and stepping the line number counter once only.
Moreover, ~\linelabel~s got lost. Of course, tables are
usually so high that you will want to treat each row like a
line. (Christian Tapp even desires that the lines of table
entries belonging to a single row are treated like ordinary
lines.) Footnotes get lost in such environments as well, which
was bad for ~ednotes.sty~.

We provide adjustments to count lines, print their numbers
etc.\ as desired at least for \emph{some} \LaTeX\ tabular
environments. (Like with other details, ``some'' is to some
extent explained in ~edtable.sty~.) We do this similarly as
with option ~mathrefs~ before.               We leave code
and explanations in the separate package ~edtable.sty~.
(For wizards: this package provides adjustments for
~ednotes.sty~ as well. However, in the present case we don't try
to avoid them unless ~ednotes.sty~ is loaded.)
Package option ~edtable~
defines---by loading ~edtable.sty~---an environment ~{edtable}~
which is able to change some \LaTeX\ tabular environments
with the desired effects. (v4.11: ~edtable.sty~ v1.3 counts
\LaTeX's ~{array}~ [etc.\@] as a ``tabular environment'' as
well.)

The ~{edtable}~ environment doesn't help with ~longtable.sty~,
however. To make up for this, ~{longtable}~ is adjusted in a
different way---and this happens only when another ~lineno.sty~
option ~longtable~ is called. In this case, option ~edtable~
needn't be called explicitly: option ~longtable~ works as if
~edtable~ had been called.

Now, we are convinced that vertical spacing around
~{longtable}~ works wrongly---see \LaTeX\ bugs database
tools/3180 and 3485, or see explanations in the package
~ltabptch.sty~ (which is to be obtained from CTAN folder
\path{macros/latex/ltabptch}). Our conviction is so strong
that the ~longtable~ option loads---after ~longtable.sty~---the
patch package ~ltabptch.sty~. If the user doesn't want this
(maybe preferring her own arrangement with the vertical
spacing), she can forbid it by calling ~nolongtablepatch~.

The following code just collects some choices, which are
then executed in section_\ref{ss:ExOpt}. We use an ~\if...~
without ~\newif~ since ~\if...true~ and ~\if...false~
would occur at most two times and only within the present
package. (~\AtEndOfClass{\RequirePackage{edtable}}~
could be used instead, I just overlooked this. Now I don't
change it because it allows to change the version requirement
at one place only.)
\begin{code}\begin{verbatim}
\let\if@LN@edtable\iffalse

\DeclareOption{edtable}{\let\if@LN@edtable\iftrue}

\DeclareOption{longtable}{\let\if@LN@edtable\iftrue
  \PassOptionsToPackage{longtable}{edtable}}

\DeclareOption{nolongtablepatch}
  \PassOptionsToPackage{nolongtablepatch}{edtable}}
\end{verbatim}
\end{code}
(/New v4.1)

\subsection
Switch among settings
\unskip}\label{ss:v3opts}

There is a bunch of package options that execute
user commands only.

Options ~left~ (~right~) put the line numbers on the left
(right) margin.  This works in all modes.  ~left~ is the
default.
\begin{code}\begin{verbatim}
\DeclareOption{left}{\setmakelinenumbers\makeLineNumberLeft*}

\DeclareOption{right}{\setmakelinenumbers\makeLineNumberRight*}
\end{verbatim}
\end{code}
Option ~switch~ (~switch*~) puts the line numbers on the
outer (inner) margin of the text.   This requires running
the pagewise mode,  but we turn off the page offset
subtraction, getting sort of running numbers again.  The
~pagewise~ option may restore true pagewise mode later.
\begin{code}\begin{verbatim}
\DeclareOption{switch}{\setpagewiselinenumbers
                       \switchlinenumbers
                       \runningpagewiselinenumbers}

\DeclareOption{switch*}{\setpagewiselinenumbers
                        \switchlinenumbers*%
                        \runningpagewiselinenumbers}
\end{verbatim}
\end{code}
In twocolumn mode, we can switch the line numbers to
the outer margin, and/or start with number 1 in each
column.  Margin switching is covered by the ~switch~
options.
\begin{code}\begin{verbatim}
\DeclareOption{columnwise}{\setpagewiselinenumbers
                           \columnwiselinenumberstrue
                           \realpagewiselinenumbers}
\end{verbatim}
\end{code}
The options ~pagewise~ and ~running~ select the major
linenumber mechanism.  ~running~ line numbers refer to a real
counter value, which can be reset for any paragraph,
even getting  multiple paragraphs on one page starting
with line number one.  ~pagewise~ line numbers get a
unique hidden number within the document,  but with the
opportunity to establish the page on which they finally
come to rest.  This allows the subtraction of the page
offset, getting the numbers starting with 1 on top of each
page, and margin switching in twoside formats becomes
possible.  The default mode is ~running~.

The order of declaration of the options is important here
~pagewise~ must come after ~switch~, to overide running
pagewise mode. ~running~ comes last, to reset the running
line number mode, e.g, after selecting margin switch mode
for ~pagewise~ running.  Once more, if you specify all
three of the options ~[switch,pagewise,running]~, the
result is almost nothing, but if you later say
~\linenumbers\setpagewiselinenumbers~,  you get margin switching, with
real pagewise line numbers.

\begin{code}\begin{verbatim}
\DeclareOption{pagewise}{\setpagewiselinenumbers
                         \realpagewiselinenumbers}

\DeclareOption{running}{\setrunninglinenumbers}
\end{verbatim}
\end{code}
The option ~modulo~ causes only those linenumbers to be
printed which are multiples of five.
\begin{code}\begin{verbatim}
\DeclareOption{modulo}{\modulolinenumbers\relax}
\end{verbatim}
\end{code}
Option ~modulo*~ modifies ~modulo~ in working like
~\modulolinenumbers*~---see section_\ref{s:UserCmds}.
\begin{code}\begin{verbatim}
\DeclareOption{modulo*}{\modulolinenumbers*\relax}
\end{verbatim}
\end{code}
The package option ~mathlines~ switches the behavior of
the ~{linenomath}~ environment with its star-form.
Without this option, the ~{linenomath}~ environment does
not number the lines of the display, while the star-form
does.  With this option, its just the opposite.

\begin{code}\begin{verbatim}
\DeclareOption{mathlines}{\linenumberdisplaymath}
\end{verbatim}
\end{code}
~displaymath~ now calls for wrappers of the standard
\LaTeX\ display math environment.  This was previously
done by ~mlineno.sty~.

(New v4.3) Option `displaymath' becomes default according
to Erik \mbox{Luijten}'s suggestion. I was finally convinced
of this as soon as I discovered how to avoid a spurious line
number above ~\begin{linenomath}~ (subsection_\ref{ss:DM}).
~\endlinenomath~ provides ~\ignorespaces~, so what could go
wrong now?
\begin{code}\begin{verbatim}
\DeclareOption{displaymath}{\PackageWarningNoLine{lineno}{%
                Option [displaymath] is obsolete -- default now!}}
\end{verbatim}
\end{code}
(/New v4.3)

\subsection{%
Compatibility with \texttt{hyperref}
\unskip}
The ~hyperref~ package, via ~nameref~, requires three more
groups in the second argment of a ~\newlabel~.  Well, why
shouldn't it get them?  (New v3.07) The presence of the
~nameref~ package is now detected automatically
~\AtBeginDocument~. (/New v3.07) (Fixed in v3.09)  We try
to be smart, and test ~\AtBeginDocument~ if the ~nameref~
package is loaded, but ~hyperref~ postpones the loading of
~nameref~ too, so this is all in vain.

(New v4.3)  But we can also test at the first ~\linelabel~.
Regarding the error-message for misplaced ~\linelabel~ from v4.11:
previously, ~\linenumbers~ rendered ~\linelabel~ the genuine
version of ~\linelabel~ from the start on. This doesn't work
now, since ~\@LN@linelabel~ may change its meaning after the
first ~\linenumbers~ and before a next one (if there is some).
(/New v4.3)
\begin{code}\begin{verbatim}
\DeclareOption{hyperref}{\PackageWarningNoLine{lineno}{%
                Option [hyperref] is obsolete.
  \MessageBreak The hyperref package is detected automatically.}}

\AtBeginDocument
  \@ifpackageloaded{nameref}{%
\end{verbatim}
\end{code}
(New v4.3)  ``Global'' is merely ``symbolic'' ~\AtBeginDoc...~.
If ~nameref~ is not detected here, the next ~\@LN@linelabel~
will do almost the same, then globally indeed.
\begin{code}\begin{verbatim}
    \gdef\@LN@ExtraLabelItems{{}{}{}
  }{%
    \global\let\@LN@@linelabel\@LN@linelabel
    \gdef\@LN@linelabel
\end{verbatim}
\end{code}
~\@ifpackageloaded~ is ``preamble only'', its---very
internal---preamble definition is replicated here:
\begin{code}\begin{verbatim}
     \expandafter
      \ifx\csname ver@nameref.sty\endcsname\relax \else
        \gdef\@LN@ExtraLabelItems{{}{}{}
      \fi
\end{verbatim}
\end{code}
Now aim at the ``usual'' behaviour:
\begin{code}\begin{verbatim}
      \global\let\@LN@linelabel\@LN@@linelabel
      \global\let\@LN@@linelabel\relax
      \@LN@linelabel

  }%
}
\end{verbatim}
\end{code}
(/New v4.3)

(New v4.1)
\subsection
A note on calling so many options
\unskip}

The number of package options may stimulate worrying about how to
\emph{enter} all the options that one would like to use---they may
not fit into one line. Fortunately, you can safely break code lines
after the commas separating the option names in the ~\usepackage~
command (no comment marks needed).

\subsection
Execute options
\unskip}\label{ss:ExOpt}

We stop declaring options and execute the ones that are
called by the user.       (/New v4.1)
\begin{code}\begin{verbatim}
\ProcessOptions
\end{verbatim}
\end{code}
(New v4.1)        Now we know whether ~edtable.sty~ is wanted
and (if it is) with which options it is to be called.
\begin{code}\begin{verbatim}
\if@LN@edtable \RequirePackage{edtable}[2005/03/07] \fi
\end{verbatim}
\end{code}
(/New v4.1)

\section{%
Former package extensions
\label{s:Xt}\unskip}

The extensions in this section were previously supplied
in separate ~.sty~ files.

\subsection{%
$display math$
\unskip}\label{ss:display}
(New v4.3)    From now on, you no longer need to type
the ~{linenomath}~ environment with the ~\[~, ~{equation}~,
and ~{eqnarray}~ environments---and you no longer need to
use the former package option ~displaymath~ for this feature.
(/New v4.3)

The standard \LaTeX\ display math environments are
wrapped in a ~{linenomath}~ environment.

(New 3.05)  The ~[fleqn]~ option of the standard
\LaTeX\ classes defines the display math
environments such that line numbers appear just
fine.  Thus, we need not do any tricks when
~[fleqn]~ is loaded, as indicated by presents of
the ~\mathindent~ register.           (/New 3.05)

(New 3.05a)  for ~{eqnarray}~s we rather keep the
old trick.                            (/New 3.05a)

(New 3.08) Wrap ~\[~ and ~\]~ into ~{linenomath}~,
instead of ~{displaymath}~.  Also save the definition
of ~\equation~, instead of replicating the current
\LaTeX\ definition.                    (/New 3.08)
\begin{code}\begin{verbatim}
 \@ifundefined{mathindent}{

  \let\LN@displaymath\[%
  \let\LN@enddisplaymath\]%
  \renewcommand\[{\begin{linenomath}\LN@displaymath}%
  \renewcommand\]{\LN@enddisplaymath\end{linenomath}}%
\end{verbatim}
\end{code}

\begin{code}\begin{verbatim}
  \let\LN@equation\equation
  \let\LN@endequation\endequation
  \renewenvironment{equation}%
     {\linenomath\LN@equation}%
     {\LN@endequation\endlinenomath}%

 }{

  \let\LN@eqnarray\eqnarray
  \let\LN@endeqnarray\endeqnarray
  \renewenvironment{eqnarray}%
     {\linenomath\LN@eqnarray}%
     {\LN@endeqnarray\endlinenomath}%
\end{verbatim}
\end{code}
(UL)        Indeed. The \LaTeX\ macros are saved for
unnumbered mode, which is detected by ~\linenomath~.
(/UL)

\subsection{%
Line numbers in internal vertical mode
\unskip}\label{ss:ILN}

The command ~\internallinenumbers~ adds line numbers in
internal vertical mode, but with limitations: we assume
fixed baseline skip.

(v4.22)       v3.10 provided a global (~\global\advance~)
as well as a local version (star-form, using
~\c@internallinenumber~). ~\resetlinenumbers~ acted
locally and was here used with the global version---save
stack danger, \TeX book p._301---in v4.00 I
disabled the global version therefore. Now I find that
it is better to keep a global version, and the now global
~\resetlinenumbers~ is perfect for this. The global version
allows continuing the ``internal'' numbers in the ensuing
``external'' text, and---unless reset by brackets
argument---continuing the above series of line numbers.
As with v3.10, the local version always starts with
line number one. A new ~\@LN@iglobal~ steps ~\global~ly
in the global version, otherwise it is ~\relax~.
(I also remove all my stupid discussions as of v4.00.
And I use ~\newcommand~.)     (v4.22)
\begin{code}\begin{verbatim}
\let\@LN@iglobal\global

\newcommand\internallinenumbers{\setrunninglinenumbers
     \let\@@par\internallinenumberpar
     \ifx\@par\@@@par\let\@par\internallinenumberpar\fi
     \ifx\par\@@@par\let\par\internallinenumberpar\fi
     \ifx\@par\linenumberpar\let\@par\internallinenumberpar\fi
     \ifx\par\linenumberpar\let\par\internallinenumberpar\fi
     \@ifnextchar[{\resetlinenumber
                 {\@ifstar{\let\c@linenumber\c@internallinenumber
                           \let\@LN@iglobal\relax
                           \c@linenumber\@ne}{}}%
     }

\let\endinternallinenumbers\par\@endpetrue
\@namedef{internallinenumbers*}{\internallinenumbers*}
\expandafter\let\csname endinternallinenumbers*\endcsname\par\@endpetrue

\newcount\c@internallinenumber
\newcount\c@internallinenumbers

\newcommand\internallinenumberpar
     \ifvmode\@@@par\else\ifinner\@@@par\else\@@@par
     \begingroup
        \c@internallinenumbers\prevgraf
        \setbox\@tempboxa\hbox{\vbox{\makeinternalLinenumbers}}%
        \dp\@tempboxa\prevdepth
        \ht\@tempboxa\z@
        \nobreak\vskip-\prevdepth
        \nointerlineskip\box\@tempboxa
     \endgroup
     \fi\fi
     }

\newcommand\makeinternalLinenumbers
   \ifnum\c@internallinenumbers>\z@
   \hb@xt@\z@{\makeLineNumber
   \@LN@iglobal
     \advance\c@linenumber\@ne
   \advance\c@internallinenumbers\m@ne
   \expandafter\makeinternalLinenumbers\fi
   }

\end{verbatim}
\end{code}

\subsection{%
Line number references with offset
\unskip}

This extension defines macros to refer to line
numbers with an offset, e.g., to refer to a line
which cannot be labeled directly (display math).
This was formerly knows as ~rlineno.sty~.

To refer to a pagewise line number with offset:
\begin{quote}
~\linerefp[~<OFFSET>~]{~<LABEL>~}~
\end{quote}
To refer to a running line number with offset:
\begin{quote}
~\linerefr[~<OFFSET>~]{~<LABEL>~}~
\end{quote}
To refer to a line number labeled in the same mode as currently
selected:
\begin{quote}
~\lineref[~<OFFSET>~]{~<LABEL>~}~
\end{quote}
\begin{code}\begin{verbatim}
\newcommand\lineref{%
  \ifx\c@linenumber\c@runninglinenumber
     \expandafter\linerefr
  \else
     \expandafter\linerefp
  \fi
}

\newcommand*\linerefp[2][\z@]{{%
   \let\@thelinenumber\thelinenumber
   \edef\thelinenumber{\advance\c@linenumber#1\relax
                       \noexpand\@thelinenumber}%
   \ref{#2}%
}}
\end{verbatim}
\end{code}
This goes deep into \LaTeX's internals.
\begin{code}\begin{verbatim}
\newcommand*\linerefr[2][\z@]{{%
   \def\@@linerefadd{\advance\c@linenumber#1}%
   \expandafter\@setref\csname r@#2\endcsname
   \@linerefadd{#2}%
}}

\newcommand*\@linerefadd[2]{\c@linenumber=#1\@@linerefadd\relax
                            \thelinenumber}
\end{verbatim}
\end{code}

\subsection{%
Numbered quotation environments
\unskip}

The ~{numquote}~ and ~{numquotation}~
environments are like ~{quote}~ and
~{quotation}~, except there will be line
numbers.

An optional argument gives the number to count
from.  A star ~*~ (inside or outside the closing
~}~) prevent the reset of the line numbers.
Default is to count from one.

(v4.22: A local version using ~\c@internallinenumber~
might be useful, see subsection_\ref{ss:ILN}.)
\begin{code}\begin{verbatim}
\newcommand\quotelinenumbers
   {\@ifstar\linenumbers{\@ifnextchar[\linenumbers{\linenumbers*}}}

\newdimen\quotelinenumbersep
\quotelinenumbersep=\linenumbersep
\let\quotelinenumberfont\normalfont\tiny\sffamily

\newcommand\numquotelist
   {\setmakelinenumbers\makeLineNumberLeft
    \linenumbersep\quotelinenumbersep
    \let\normalfont\tiny\sffamily\quotelinenumberfont
    \addtolength{\linenumbersep}{-\@totalleftmargin}%
    \quotelinenumbers
   }

\newenvironment{numquote}     {\quote\numquotelist}{\endquote}
\newenvironment{numquotation} {\quotation\numquotelist}{\endquotation}
\newenvironment{numquote*}    {\quote\numquotelist*}{\endquote}
\newenvironment{numquotation*}{\quotation\numquotelist*}{\endquotation}
\end{verbatim}
\end{code}

\subsection{%
Frame around a paragraph
\unskip}

The ~{bframe}~ environment draws a frame around
some text, across page breaks, if necessary.

This works only for plain text paragraphs,
without special height lines. All lines must be
~\baselineskip~ apart, no display math.
\begin{code}\begin{verbatim}
\newenvironment{bframe}
  {\par
   \@tempdima\textwidth
   \advance\@tempdima 2\bframesep
   \setbox\bframebox\hb@xt@\textwidth{%
      \hskip-\bframesep
      \vrule\@width\bframerule\@height\baselineskip\@depth\bframesep
      \advance\@tempdima-2\bframerule
      \hskip\@tempdima
      \vrule\@width\bframerule\@height\baselineskip\@depth\bframesep
      \hskip-\bframesep
   }%
   \hbox{\hskip-\bframesep
         \vrule\@width\@tempdima\@height\bframerule\@depth\z@}%
   \nointerlineskip
   \copy\bframebox
   \nobreak
   \kern-\baselineskip
   \setrunninglinenumbers\linenumbers
   \def\makeLineNumber{\copy\bframebox\hss}%
  }
  {\par
   \kern-\prevdepth
   \kern\bframesep
   \nointerlineskip
   \@tempdima\textwidth
   \advance\@tempdima 2\bframesep
   \hbox{\hskip-\bframesep
         \vrule\@width\@tempdima\@height\bframerule\@depth\z@}%
  }

\newdimen\bframerule
\bframerule=\fboxrule

\newdimen\bframesep
\bframesep=\fboxsep

\newbox\bframebox
\end{verbatim}
\end{code}

\section{%
Move \scs{vadjust} items (New v4.00)
\unskip}\label{s:MVadj}

This section completes reviving ~\pagebreak~, ~\nopagebreak~,
~\vspace~, and the star and optional form of ~\\~. This was
started in section_\ref{ss:output} and resumed in
section_\ref{ss:MLN} and subsection_\ref{ss:calls}.
The problem was explained in section_\ref{ss:output}:
~\vadjust~ items come out at a bad position, and the
\LaTeX\ commands named before work with ~\vadjust~ indeed.
Our solution was sketched there as well.

According to the caveat in subsection_\ref{ss:OnOff} concerning
~\ifLineNumbers~, the \LaTeX\ commands enumerated may go
wrong if you switch line numbering inside or at the end of
a paragraph.

\subsection{%
Redefining \scs{vadjust}
\unskip}\label{ss:PVadj}

~\vadjust~ will temporarily be changed into the following
command.
\begin{code}\begin{verbatim}
\def\PostponeVadjust#1
  \global\let\vadjust\@LN@@vadjust
\end{verbatim}
\end{code}
This undoes a ~\global\let\vadjust\PostponeVadjust~ which will
start each of the refined \LaTeX\ commands. The ~\global~s
are most probably superfluous. They might be useful should one
~\vadjust~ appear in a group starting after the change of
~\vadjust~ into ~\PostponeVadjust~.
(UL) Even the undoing may be superfluous, cf._discussion
in section_\ref{ss:ReDef} below.  (UL)
\begin{code}\begin{verbatim}
  \vadjust{\penalty-\@Mppvacodepen
  \g@addto@macro\@LN@vadjustlist{#1\@lt
}
\let\@LN@@vadjust\vadjust
\global\let\@LN@vadjustlist\@empty
\global\let\@LN@do@vadjusts\relax
\end{verbatim}
\end{code}
These ~\global~s are just to remind that
all the changes of the strings after ~\let~ should be
~\global~ (\TeX book p._301). ~\@LN@vadjustlist~ collects
the ~\vadjust~ items of a paragraph. ~\PassVadjustList~
tears one ~\vadjust~ item for the current line out of
~\@LN@vadjustlist~ and puts it into ~\@LN@do@vadjusts~.
The latter is encountered each line in ~\MakeLineNo~
(section_\ref{ss:MLN}), while those \LaTeX\ ~\vadjust~
commands will come rather rarely. So I decided that
~\@LN@do@vadjust~ is ~\relax~ until a ~\vadjust~ item
is waiting. In the latter case, ~\@LN@do@vadjusts~
is turned into a list macro which resets itself to
~\relax~ when the other contents have been placed in
the vertical list.---~\PassVadjustList~ is invoked by
the output routine (section_\ref{ss:output}), so the
~\box255~ must be put back.
\begin{code}\begin{verbatim}
\def\PassVadjustList
  \unvbox\@cclv
  \expandafter \@LN@xnext \@LN@vadjustlist \@@
                          \@tempa \@LN@vadjustlist
  \ifx\@LN@do@vadjusts\relax
    \gdef\@LN@do@vadjusts{\global\let\@LN@do@vadjusts\relax
  \fi
  \expandafter \g@addto@macro \expandafter \@LN@do@vadjusts
    \expandafter {\@tempa
}
\end{verbatim}
\end{code}

\subsection{%
Redefining the \LaTeX\ commands
\unskip}\label{ss:ReDef}

Now we change ~\pagebreak~ etc.\
so that they use ~\PostponeVadjust~ in place of ~\vadjust~.
We try to do this as independently as possible of the
implementation of the \LaTeX\ commands to be redefined.
Therefore, we don't just copy macro definition code from any
single implementation (say, latest \LaTeX) and insert our
changes, but attach a conditional
~\global\let\vadjust\PostponeVadjust~
to their left ends in a way which should work rather
independantly of their actual code.
However, ~\vadjust~ should be the primitive again after
execution of the command. So the ~\global\let...~ may be used
only if it's guaranteed that a ~\vadjust~ is near.---(UL)
Sure? In line numbering mode, probably each ~\vadjust~
coming from a \LaTeX\ command should be ~\PostponeVadjust~.
~\marginpar~s and floats seem to be the only cases which
are not explicitly dealt with in the present section.
This would be a way to avoid ~\@LN@nobreaktrue~!
Of course, the ~\vadjust~s that the present package uses
then must be replaced by ~\@LN@@vadjust~.---Maybe
next time.      (/UL)

The next command and something else will be added to the
\LaTeX\ commands we are concerned with here.
\begin{code}\begin{verbatim}
\DeclareRobustCommand\@LN@changevadjust
  \ifvmode\else\ifinner\else
    \global\let\vadjust\PostponeVadjust
  \fi\fi
}
\end{verbatim}
\end{code}
(UL) What about math mode? Math display? Warn? (/UL)

~\@tempa~ will now become a two place macro which adds first
argument (single token), enclosed by ~\ifLineNumbers~\,\dots
~\fi~ to the left of second argument. As long as we need it,
we can't use the star form of ~\DeclareRobustCommand~ or
the like, because AMS-\LaTeX\ uses ~\@tempa~ for ~\@ifstar~.
(New v4.41) And for the same reason, that ~\CheckCommand*~
had to be raised! (/New v4.41)
\begin{code}\begin{verbatim}
\CheckCommand*\@parboxrestore{\@arrayparboxrestore\let\\\@normalcr}

\def\@tempa#1#2
  \expandafter \def \expandafter#2\expandafter{\expandafter
    \ifLineNumbers\expandafter#1\expandafter\fi#2
}
\end{verbatim}
\end{code}
(UL)              This ~\ifLineNumber~ can be fooled by
~\linenumbers~ ahead etc. It might be better to place
a signal penalty in any case and let the output routine
decide what to do.
(/UL)

We use the occasion to switch off linenumbers where they
don't work anyway and where we don't want them,
especially in footnotes:
\begin{code}\begin{verbatim}
\@tempa\nolinenumbers\@arrayparboxrestore
\end{verbatim}
\end{code}
We hope this suffices $\dots$ let's check one thing
at least: [(New v4.41) see ~\CheckCommand~ above (/New v4.41)]

Now for the main theme of the section.
The next lines assume that ~\vspace~, ~\pagebreak~, and
~\nopagebreak~ use ~\vadjust~ whenever they occur outside
vertical mode; moreover, that they don't directly read
an argument. Indeed ~\pagebreak~ and ~\nopagebreak~ first
call something which tests for a left bracket ahead,
while ~\vspace~ first tests for a star.
\begin{code}\begin{verbatim}
\@tempa\@LN@changevadjust\vspace
\@tempa\@LN@changevadjust\pagebreak
\@tempa\@LN@changevadjust\nopagebreak
\end{verbatim}
\end{code}
~\\~, however, uses ~\vadjust~ only in star or optional form.
We relax independency of implementation in assuming
that ~\@normalcr~ is the fragile version of ~\\~
(and we use ~\@ifstar~!).
(Using a copy of ~\\~ would be safer, but an ugly repetition
of ~\protect~.)
\begin{code}\begin{verbatim}
\DeclareRobustCommand\\
  \ifLineNumbers
    \expandafter \@LN@cr
  \else
    \expandafter \@normalcr
  \fi
}
\def\@LN@cr
  \@ifstar{\@LN@changevadjust\@normalcr*
          {\@ifnextchar[{\@LN@changevadjust\@normalcr}\@normalcr
}
\end{verbatim}
\end{code}
Moreover we hope that ~\newline~ never leads to a ~\vadjust~,
although names of some commands invoked by ~\\~ contain
~newline~. At last, this seems to have been OK since 1989 or
even earlier.

\modulolinenumbers[1]
\firstlinenumber{0}
Let's have a few tests.\vspace*{.5\baselineskip}
Testing ~\pagebreak~ and ~\nopagebreak~ would be too expensive
here, but---oops!---we have just experienced a successful
~\vspace*{.5\baselineskip}~. A
~\\*[.5\baselineskip]~\\*[.5\baselineskip] may look even more
drastical, but this time we are happy about it. Note that the
line numbers have moved with the lines. Without our changes,
one line number\vadjust{\kern.5\baselineskip} would have
``anticipated'' the move of the next line, just as you can
observe it now.
(/New v4.00)

\switchlinenumbers

\subsection
Reminder on obsoleteness
\unskip}

(New v4.1)    We have completed inclusion of the earlier
extension packages ~linenox0.sty~, ~linenox1.sty~, and
~lnopatch.sty~. If one of them is loaded, though,
we produce an error message before something weird happens.
We avoid ~\newif~ because the switchings occur so rarely.
\begin{code}\begin{verbatim}
\AtBeginDocument
  \let\if@LN@obsolete\iffalse
  \@ifpackageloaded{linenox0}{\let\if@LN@obsolete\iftrue}\relax
  \@ifpackageloaded{linenox1}{\let\if@LN@obsolete\iftrue}\relax
  \@ifpackageloaded{lnopatch}{\let\if@LN@obsolete\iftrue}\relax
  \if@LN@obsolete
    \PackageError{lineno}{Obsolete extension package(s)}
    With lineno.sty version 4.00 or later,\MessageBreak
    linenox0/linenox1/lnopatch.sty must no longer be loaded.
  \fi
}
\end{verbatim}
\end{code}

\modulolinenumbers[1]
\section{%
The final touch
\unskip}

There is one deadcycle for each line number.
\begin{code}\begin{verbatim}
\advance\maxdeadcycles 100

\endinput
\end{verbatim}
\end{code}

\section{%
The user commands
\unskip}\label{s:UserCmds}

The user commands to turn on and off line numbering
are
\begin{description}\item
[|\linenumbers]                                                       \ \par
Turn on line numbering in the current mode.

\item
[|\linenumbers*]                                              \ \par$\qquad$
and reset the line number to 1.
\def\NL{<number>]}\item
[|\linenumbers[\NL]                                           \ \par$\qquad$
and start with <number>.
\item
[|\nolinenumbers]                                                     \ \par
Turn off line numbering.
\item
[|\setrunninglinenumbers\linenumbers*[\NL]                                           \ \par
Turn on ~running~ line numbers, with the same optional
arguments as ~\linenumbers~.  The numbers are running
through the text over pagebreaks.  When you turn
numbering off and on again, the numbers will continue,
except, of cause, if you ask to reset or preset the
counter.
\item
[|\linenumbers\setpagewiselinenumbers]                                               \ \par
Turn on ~pagewise~ line numbers.  The lines on each
page are numbered beginning with one at the first
~pagewise~ numbered line.
\item
[|\resetlinenumber[\NL]                                               \ \par
Reset ~[~Set~]~ the line number to 1
~[~<number>~]~.
\item
[|\setrunninglinenumbers]                                             \ \par
Switch to ~running~ line number mode. Do \emph{not}
turn it on or off.
\item
[|\setpagewiselinenumbers]                                            \ \par
Switch to ~pagewise~ line number mode. Do \emph{not}
turn it on or off.
\item
[|\switchlinenumbers*]                                                \ \par
Causes margin switching in pagewise modes. With the
star,  put the line numbers on the inner margin.
\item
[|\setmakelinenumbers\makeLineNumberLeft*]                                                  \ \par
\item
[|\setmakelinenumbers\makeLineNumberRight*]                                                 \ \par
Set the line numbers in the left/right margin. With the
star this works for both modes of operation, without
the star only for the currently selected mode.
\item
[|\runningpagewiselinenumbers]                                        \ \par
When using the pagewise line number mode,  do not
subtract the page offset.  This results in running
line numbers again,  but with the possibility to switch
margins.  Be careful when doing line number
referencing,  this mode status must be the same while
setting the paragraph and during references.
\item
[|\realpagewiselinenumbers]                                           \ \par
Reverses the effect of ~\runningpagewiselinenumbers~.
\item
[|\modulolinenumbers[\NL]                                             \ \par
Give a number only to lines which are multiples of
~[~<number>~]~.  If <number> is not specified, the
current value in the counter ~linenumbermodulo~ is
retained.  <number>=1 turns this off without changing
~linenumbermodulo~.  The counter is initialized to 5.
\item
[|\modulolinenumbers*[\NL]                                            \ \par
Like ~\modulolinenumbers~, the only difference being
that the first line number after a ~\linenumbers~
(or ~\setrunninglinenumbers\linenumbers~, ~\linenumbers\setpagewiselinenumbers~,
~\quotelinenumbers~) is printed regardless of the
modulo---yet `1' is printed only after (or \dots)
~\firstlinenumber{1}~.
This also applies to the first line of a
~{linenumbers}~ or respective environment.
See subsection_\ref{ss:Mod} for another explanation.
The behaviour may be unsatisfactory with pagewise
line-numbering.
\item
[|\firstlinenumber]                                                   \ \par
~\firstlinenumber{~<filino>~}~ brings about that
(after it) line numbers less than <filino> do
\emph{not} appear in the margin. Moreover, with
~\modulolinenumbers[~<number>~]~, just the line
numbers which are <filino> plus a multiple of
<number> are printed.---If you had
~\firstlinenumber{~<pos>~}~ with some $\mbox{<pos>}>0$
and want to switch to printing multiples of, e.g.,
4, you best do ~\modulolinenumbers[4]~ and
~\firstlinenumber{0}~. (See subsection_\ref{ss:Mod}
for technical details.)
\item
[|\linenumberdisplaymath]                                             \ \par
Number the lines of a display math in a ~{linenomath}~
environment, but do not in a ~{linenomath*}~
environment.  This is used by the package option
~[mathlines]~.
\item
[|\nolinenumberdisplaymath]                                           \ \par
Do not Number the lines of a display math in a
~{linenomath}~ environment, but do in a
~{linenomath*}~ environment.  This is the default.
\item
[|\linelabel]                                                         \ \par
Set a ~\linelabel{~<foo>~}~ to the line number where
this commands is in.  Refer to it with the \LaTeX\
referencing commands ~\ref{~<foo>~}~ and
~\pageref{~<foo>~}~.
\end{description}
The commands can be used globally, locally within groups
or as environments.  It is important to know that they
take action only when the ~\par~ is executed.  The
~\end{~<mode>~linenumbers}~ commands provide a ~\par~.
Examples:
\begin{verse}
~{\linenumbers~  <text> ~\par}~                                         \\
\ \\
~\begin{linenumbers}~                                                   \\
<text>                                                              \\
~\end{linenumbers}~                                                     \\
\ \\
<paragraph> ~{\linenumbers\par}~                                        \\
\ \\
~\linenumbers~                                                          \\
<text> ~\par~                                                         \\
~\nolinenumbers~                                                        \\
\ \\
~\linenumbers~                                                          \\
<paragraph> ~{\nolinenumbers\par}~                                      \\
\end{verse}
(New v4.00)
However, the examples containing <paragraph> show what you
should \emph{not} do, at least if you use ~\pagebreak~,
~\nopagebreak~, ~\vspace~, ~\\*~ or
~\\[~<space>~]~---cf._section_\ref{s:MVadj}.

The same care should be applied to the ``wizard'' devices
~\ifLineNumbers~ (subsection_\ref{ss:OnOff}) and
~\PostponeVadjust~ (section_\ref{ss:PVadj}).
(/New v4.00)

(New v4.11) Oh, and the commands and environments of
section_{s:Xt} are missing. Sorry, I am in a hurry now.
May be next time
---And the  environments ~{linenomath}~ and ~{linenomath*}~should
get an own paragraph. In short, each math display, equation,
or ~{eqnarray}~ should be ``wrapped'' in one of ~{linenomath}~
and ~{linenomath*}~.

\subsection{%
Customization hooks
\unskip}

There are several hooks to customize the appearance of the
line numbers, and some low level hooks for special
effects.
\begin{description}\item
[|\thelinenumber]                                                     \ \par
This macro should give the representation of the line
number in the \LaTeX-counter ~linenumber~.  The
default is provided by \LaTeX:                              \par$\qquad$
~\arabic{linenumber}~
\item
[|\makeLineNumberLeft]                                                \ \par
This macro is used to attach a line number to the left
of the text page.  This macro should fill an ~\hbox to 0pt~
which will be placed at the left margin of the
page, with the reference point aligned to the line to
which it should give a number.  Please use the macro
~\LineNumber~ to refer to the line number.

The default definition is                                   \par$\qquad$
~\hss\normalfont\tiny\sffamily\LineNumber\hskip\linenumbersep~
\item
[|\makeLineNumberRight]                                               \ \par
Like ~\makeLineNumberLeft~, but for line numbers on
the right margin.

The default definition is                                   \par$\qquad$
~\normalfont\tiny\sffamily\hskip\linenumbersep\hskip\textwidth~    \par$\qquad$
~\hbox to\linenumberwidth{\hss\LineNumber}\hss~
\item
[|\normalfont\tiny\sffamily]                                                    \ \par
This macro is initialized to                                \par$\qquad$
~\normalfont\tiny\sffamily~
\item
[|\linenumbersep]                                                     \ \par
This dimension register sets the separation of the
linenumber to the text. Default value is ~10pt~.
\item
[|\linenumberwidth]                                                   \ \par
This dimension register sets the width of the line
number box on the right margin.  The distance of the
right edge of the text to the right edge of the line
number is ~\linenumbersep~ + ~\linenumberwidth~. The
default value is ~10pt~.
\item
[|\theLineNumber] (for wizards)                                       \ \par
This macro is called for printing a ~\newlabel~ entry
to the aux-file.  Its definition depends on the mode.
For running line numbers it's just ~\thelinenumber~,
while in pagewise mode, the page offset subtraction
is done in here.
\item
[|\makeLineNumber] (for wizards)                                      \ \par
This macro produces the line numbers.  The definition
depends on the mode.  In the running line numbers
mode it just expands ~\makeLineNumberLeft~.
\item
[|\LineNumber] (for wizards)                                          \ \par
This macro is called by ~\makeLineNumber~ to typeset
the line number.  This hook is changed by the modulo
mechanism
and by ~\firstlinenumber~.
\end{description}
\end{document

\section{\label{sec:level1}Introduction}

\begin{ncabstract}
Rare-earth nickelates form an intriguing series of correlated perovskite oxides. Apart from LaNiO$_\mathbf{3}$, they exhibit on cooling a sharp metal-insulator electronic phase transition, a concurrent structural phase transition and a magnetic phase transition toward an unusual antiferromagnetic spin order. Appealing for various applications, full exploitation of these compounds is still hampered by the lack of global understanding of the interplay between their electronic, structural and magnetic properties.  Here, we show from first-principles calculations that the metal-insulator transition of nickelates arises from the softening of an oxygen breathing distortion, structurally triggered by oxygen-octahedra rotation motions. The origin of such a rare triggered mechanism is traced back in their electronic and magnetic properties, providing a united picture. We further develop a Landau model accounting for the evolution of the metal-insulator transition in terms of the $\boldsymbol{{R}}$ cations and rationalising how to tune this transition by acting on oxygen rotation motions.\end{ncabstract}

First synthetized in 1971~\cite{Demazeau1971}, rare-earth nickelates ($R$NiO$_3$, with $R =$ rare earth) are appealing for various  applications~\cite{Shi2013,Zhou2016} and the possibility to tune their properties in epitaxial films and heterostructures~\cite{Middey2016} has recently fuelled an even larger interest~\cite{Forst2015,Kim2016,Grisolia2016}.
$R$NiO$_3$ compounds belong to the family of perovskite oxides with a reference $Pm\bar{3}m$ cubic structure (Fig. 1a), nevertheless not directly observed.  Apart for LaNiO$_3$, which always keeps a metallic $R\bar{3}c$ phase and will not be further discussed here, all $R$NiO$_3$ adopt at reasonably high temperature a metallic $Pbnm$ orthorhombic phase~\cite{Catalan2008}. This phase, rather ubiquitous~\cite{Benedek2013} amongst perovskites with small Goldschmidt tolerance factor~\cite{Catalan2008},
$t$, corresponds to a distortion of the cubic structure arising from the appearance of (i) combined anti-phase rotations of the oxygen octahedra
along the $x$ and $y$ directions, $R_{xy}$ (Fig. 1b), with the same amplitude $Q_{R}$  and (ii) in-phase rotations of the oxygen octahedra along
$z$, $M_z$ (Fig. 1c), with amplitude $Q_{M}$.

\begin{figure}
\begin{center}
\resizebox{7.5cm}{!}{\includegraphics{Figure-1}}
\end{center}
\caption{ {\bf Reference cubic perovskite structure and most relevant atomic distortions.} ({\bf a}) Sketch of the reference $Pm\bar{3}m$ cubic perovskite cell of $R$NiO$_3$ compound with $R$ at the corner,  Ni at the centre and O atoms at the middle of the faces, forming corner-shared octahedra surrounding the B atoms. Starting from this reference, three main atomic distortions drive the system successively to the $Pbnm$ and then $P2_1/n$ phases : ({\bf b}) anti-phase rotations of oxygen octahedra of same amplitudes about $x$ and $y$ axis ($R_{xy}$), ({\bf c}) in-phase rotations of oxygen octahedra about $z$ axis ($M_{z}$), ({\bf d}) breathing of the oxygen octahedra ($B_{OC}$). The energy wells associated to the freezing of individual distortion of increasing amplitude in the cubic phase are shown for different $R$ cations, associated to distinct tolerance factor $t$, and either a ferromagnetic (full line) or E'-type antiferromagnetic (dashed line, only for $R=$Y) spin arrangement :  YNiO$_3$ ($t =0.920$,  blue), GdNiO$_3$ ($t =0.938$,  orange) and SmNiO$_3$ ($t =0.947$,  green). The atomic distortions are normalised to their amplitude in the  $P2_1/n$ AFM-E' ground state of YNiO$_3$. Calculations are done for each compound in a cubic phase that has the same volume as the ground state.}
 \label{fig-1}
\end{figure}

In this phase, all Ni atoms are equivalent and formally in a Jahn-Teller active $d^7$ (likely $t_{2g}^6e_g^1$ low spin) configuration. Surprisingly,
although compatible with the $Pbnm$ symmetry, cooperative Jahn-Teller distortions do not appear. Instead, at a temperature $T_{MI}$ which
strongly evolves with the $R$ cation (i.e with $t$)~\cite{Medarde1997}, $R$NiO$_3$ compounds exhibit an electronic metal-insulator transition
(MIT), which was shown to be concurrent with a structural transition from $Pbnm$ to monoclinic $P2_1/n$ symmetry \cite{Alonso1999}.  This symmetry lowering is accompanied
with the appearance of a breathing distortion of the oxygen octahedra, $B_{OC}$ (Fig. 1d), which alternatively expand and contract with amplitude $Q_B$, according to a rock-salt pattern. This gives rise to two types of Ni sites with long and short Ni--O bonds respectively.

At low temperature (100-200K), $R$NiO$_3$ compounds finally show a magnetic phase transition toward an unusual E'-type antiferromagnetic (AFM) spin
order identified by a Bragg vector $\mathbf{q}=(1/4,1/4,1/4)$ in pseudocubic notation~\cite{Garcia-munoz1994,Alonso1999,Lee2011}. For large cations ($R =$ Nd and Pr),  the Neel
temperature $T_N =  T_{MI}$ and the system goes directly from paramagnetic metal (PM-M) to  AFM insulator (AFM-I). For smaller $R$ cations, $T_N$ is much lower than $T_{MI}$;
the two phase transitions are decoupled and the system goes through an intermediate paramagnetic insulating phase (PM-I).

The origin of the MIT has been widely debated in the literature \cite{Torrance1992, Mizokawa2000,Raebiger2008,Park2012,Ruppen2015,Varignon2016}. It was sometimes interpreted as a
charge disproportionation at Ni sites~\cite{Mazin2007}~: $2 (d^7) \rightarrow d^8+d^6$. However, the importance of Ni 3d -- O 2p hybridization -- i.e., transfer of electrons from O to Ni and formation of oxygen holes (\underline{L}) keeping Ni in a $d^8$ configuration (i.e., $d^{8-n} \approx d^8\underline{L}^n$) -- was evoked early on~\cite{Mizokawa2000}. Nowadays, the MIT is  usually viewed as a charge ordering of the type $2 (d^8\underline{L}^1) \rightarrow (d^8)+(d^8 \underline{L}^2)$~\cite{Park2012,Johnston2014,Bisogni2016}. In this scenario, $B_{OC}$ appears important to stabilise the charge ordering and open the gap. As suggested in Ref. \cite{De_la_cruz2002} and confirmed from statistical correlation techniques~\cite{Balachandran2013}, $R_{xy}$ and $M_z$ are also expected to play an active role.  However, a complete picture linking electronic, structural and magnetic properties is yet to emerge.

Unlike recent theoretical studies which were focusing specifically on the electronic properties~\cite{Park2012,Johnston2014,Ruppen2015,Varignon2016},
we investigate here self-consistently the electronic and structural degrees of freedom of $R$NiO$_3$ compounds from density functional theory calculations
(DFT, see Methods). Specific care was given to the validation of our approach, which turns out to provide an unprecedented agreement with experimental
data. Focusing on YNiO$_3$, we show (see Supplementary S1) that not only the atomic structure but also the AFM-E' ground state, the estimated $T_N$ and the
electronic bandgap of the insulating phase are very accurately reproduced, making therefore our approach a method of choice to shed light on the interlink between
these different features.

We start from the reference $Pm\bar{3}m$ cubic structure. Inspection of the phonon dispersion curves (see Supplementary S2) reveals dominant structural
instabilities at R ($\omega_R =$ 310i cm$^{-1}$)  and M ($\omega_M$ = 278i cm$^{-1}$) points of the Brillouin zone (BZ), which are associated respectively to
the $R_{xy}$ and $M_{z}$ distortions responsible for the $Pbnm$ phase. These imaginary frequencies $\omega_i$ are linked to a negative energy
curvature $\alpha_i$ at the origin ($\alpha_i \propto \omega_i^2<0$) and
to a typical double-well (DW) shape of the energy when freezing $R_{xy}$ and $M_{z}$ distortions of increasing amplitude within the cubic structure, as
illustrated in Fig. 1. These wells are nearly independent of the spin order but strongly evolve with the $R$ cation : they become shallower when $R$ size
increases, consistently with a reduction of the related distortion amplitudes in the $Pbnm$ phase.

In contrast, the $B_{OC}$ motion, corresponding to another phonon at R, is stable and extremely stiff (in fact the stiffest mode with $\omega_B=$ 700 cm$^{-1}$),
in line with the single well (SW) shape illustrated in Fig. 1.
Decreasing $R$-cation size tends to stabilise slightly further $B_{OC}$, in apparent contradiction with the observed increase of $T_{MI}$. As illustrated for
YNiO$_3$,  switching from ferromagnetic (FM) to AFM-E'  spin order reduces slightly the curvature but does not reverse it; instead it shifts the SW to lower
energy~\cite{Lee2011},  yielding  a finite $Q_B$ at the minimum. Although $B_{OC}$ tends to make the system insulating, this amplitude (25\% of
ground-state's value)  is however not large enough to open a gap (more than 75\% would be required). This shows that $B_{OC}$ and the magnetic order
only cannot explain the MIT by themselves.

\begin{figure*}
\centering

\resizebox{12cm}{!}{\includegraphics{Figure-2}}
\caption{ {\bf Triggered mechanism and nickelate phase diagram} ({\bf a}) Evolution of the energy $E$ in terms of the amplitude of the breathing distortion ($Q_{B}$) for fixed amplitudes of oxygen rotations ($Q_R = Q_M$ from 0\% to 110\%) in the FM cubic phase of YNiO$_3$ (same volume as the ground state). It highlights the softening of the energy well associated to $B_{OC}$, triggered by the oxygen rotations $R_{xy}$ and $M_z$. Inset : Linear evolution of the energy curvature at the origin, $\tilde{\alpha}_B$ along $Q_B$, in terms of the square of the amplitude of the individual distortions $Q_R$ (orange) and $Q_M$ (blue). ({\bf b}) Phase diagram of $R$NiO$_3$ compounds in terms of their tolerance factor $t$ and the temperature $T$. It includes 3 phases : a metallic $Pbnm$ paramagnetic phase (PM-M, yellow area), an insulating $P2_1/n$ paramagnetic phase (PM-I, green area) and an insulating $P2_1/n$ E'-type AFM phase (AFM-I, magenta area). The yellow line and dots show the experimental evolution of $T_{MI}$ with the tolerance factor $t$. The blue line and squares is the prediction of the simple Landau model fitted on the first-principles data (FM order). The dashed blue line is the fit of the Landau expression of $T_{MI}(t)$ on experimental data. The blue star is the magnetic phase transition predicted for YNiO$_3$ from first-principles. The blue arrows indicate the correction to be applied on $T_{MI}$ for large cations  when properly incorporating the change of magnetic order. }
  \label{fig-1}
\end{figure*}

Our central result is presented in Fig. 2 where we report the evolution of the $B_{OC}$ energy well of YNiO$_3$ at various fixed amplitudes of oxygen rotation
motions. It highlights that, although initially stable (SW), $B_{OC}$ is progressively destabilized (DW) by the appearance of  $R_{xy}$ and $M_z$. As illustrated
in the inset, $\alpha_B$ is renormalized into $\tilde{\alpha}_B$  which evolves linearly with $Q_R^2$ and $Q_M^2$.  The slope associated to $Q_R$ is twice as
large as that related to $Q_M$, attesting that each of the three individual rotations similarly affects  $B_{OC}$.  This behavior arises from the presence in the energy
expansion of cooperative ($\lambda <0$) bi-quadratic coupling terms between $B_{OC}$ and oxygen rotations ($E \approx \lambda_{Bi} Q_{B}^2 Q_i^2$, $i = R, M$)
which, being the lowest-order couplings allowed by symmetry, should give rise to the appearance of $B_{OC}$ through a "triggered" phase transition according to
Holakovsky~\cite{Holakovsky1973}. The same behavior is observed independently of the magnetic order (see Supplementary S3). From now we focus on representative FM results while coming back to the role of magnetism later.

To further assess the relevance of such a triggered mechanism in nickelates, we built a Landau model including $R_{xy}$, $M_z$ and $B_{OC}$ degrees of
freedom~\cite{Balachandran2013}, restricting to lowest coupling terms and assuming temperature dependence of the oxygen rotations only~:
\begin{eqnarray}
  E &=& \gamma_R (T - T_{0R})  Q_{R}^2 + \beta_R Q_{R}^4 + \lambda_{BR} Q_{B}^2 Q_{R}^2  \nonumber \\
  &+&\gamma_M (T - T_{0M})  Q_{M}^2 + \beta_M Q_{M}^4 + \lambda_{BM} Q_{B}^2 Q_{M}^2  \nonumber \\
  &+& \alpha_B  Q_{B}^2 + \beta_B Q_{B}^4  + \lambda_{MR} Q_{M}^2 Q_{R}^2.
\end{eqnarray}
Within this model, $R_{xy}$ and $M_z$ appear at $T_{0R}$ and $T_{0M}$.  On cooling, they progressively develop within the $Pbnm$ phase and renormalize
the energy curvature $\alpha_B$ of $B_{OC}$ as made clear when grouping the $Q_B^2$ terms  in Eq. (1):
\begin{eqnarray}
  \tilde{\alpha}_B  &=& \alpha_B + \lambda_{BM} Q_{M}^2 + \lambda_{BR} Q_{R}^2
\end{eqnarray}
When reaching a critical amplitude at which $\tilde{\alpha}_B=0$, they trigger the appearance of $B_{OC}$ and produce concurrent structural and
metal-insulator phase transitions. The phase transition appears to be second order within this model, which is however too simple to be conclusive
on this point (see Supplementary S3).

All parameters and their evolution with $R$ were directly fitted from first-principles; only Curie temperatures were uniformly scaled to reproduce the
experimental $T_{MI}$ of YNiO$_3$ (see Supplementary S3). The phase diagram of nickelates as predicted within this model is reported in Fig. 2.
This figure demonstrates that the cooperative coupling of $B_{OC}$ with  $R_{xy}$ and $M_z$ is a key mechanism that, by itself, accounts
for the experimentally observed evolution of $T_{MI}$ with the tolerance factor.

Hence, the MIT in nickelates turns out to be a concrete example of triggered phase transition\cite{Flerov1995,Iwata2007}, a kind of transition never identified before
in simple perovskites. Indeed, although bi-quadratic interactions are generic in this class of compounds, different distortions usually compete and
exclude each other \cite{Benedek2013}. The cooperative coupling of $B_{OC}$ with oxygen rotations pointed out here is therefore an unusual
and intriguing feature, whose origin is now traced back in the electronic band structure.

In the cubic phase, as expected from the formal Ni $3d^7$ ($t_{2g}^6e_g^1$) occupancy, the Fermi energy $E_f$ crosses levels of dominant
Ni $3d$-$e_g$ character (i.e. anti-bonding Ni $3d$- O $2p$ states); such levels form an isolated and rather dispersive set of two $e_g$ bands, shifted above the $t_{2g}$
levels by the crystal field (Fig. 3). Forcing into this cubic structure a $B_{OC}$ distortion, associated to a phonon at $\mathbf{q}_R = (1/2, 1/2, 1/2)$,  can open a gap at $\mathbf{q}_c = (1/4, 1/4, 1/4)$ within the $e_g$ bands but well above $E_f$ and without any direct impact on  the metallic character and the occupied states. Nevertheless,
the oxygen rotation motions substantially affect the $e_g$ bands (Fig. 3),  reducing their bandwidth and yielding a progressive down shift of the $e_g$ levels at $\mathbf{q}_c$.
As the rotations gradually increase and the bandwidth decreases, $B_{OC}$ more substantially pushes down the electronic states around $E_f$, providing a progressive gain of electronic energy which, in turn, results in the softening of $\omega_B$. The critical rotation amplitude
at which $B_{OC}$ becomes unstable ($\tilde{\alpha}=0$) is precisely that at which the $e_g$ levels at $\mathbf{q}_c$ cross $E_f$. At these amplitudes, the electronic system itself becomes unstable; the appearance of $B_{OC}$ is favored and opens a gap precisely at $E_f$, making the system insulating.  As such, the MIT can therefore be interpreted as a Peierls instability but one that is not initially present and has been triggered by oxygen rotations.

For compounds with small $R$ cations, $Q_{R}$ and $Q_M$ are large and able to produce the MIT at relatively high temperatures, well above $T_N$. For large cations
($R =$ Nd, Pr), oxygen rotations are reduced and, from our Landau model (built on FM results), no more sufficient to trigger the MIT (Figure 2b).
However, as previously mentioned, the AFM-E' spin order is compatible by symmetry with $B_{OC}$ and induces its appearance as an improper order (linear shift of
$B_{OC}$ SW, Fig. 1d). Hence, although not opening a gap in the cubic phase, the onset of the AFM-E' order in the $Pbnm$ phase of NdNiO$_3$ and PrNiO$_3$ promotes the occurrence of the MIT almost triggered by the rotations. In these compounds, we have therefore $T_{MI} =T_N$; the transition is more abrupt and first-order \cite{Catalan2008}. Such active role of magnetism for large cations is supported by the experimental results and discussion in  Ref. \cite{Vobornik1999}. It is also confirmed by our first-principles calculations on NdNiO$_3$, showing that the predicted $T_{MI}$ is rescaled when including the change of magnetic order: while the system prefers to stay in the $Pbnm$ metallic phase when imposing a FM order, it switches to the $P2_1/n$ phase when adopting a AFM-E' order. The cooperative effect of the magnetic order remains true for small cations but without any impact on $T_{MI}$ ($> T_N$).

In conclusion, the concurrent electronic and structural transitions at $T_{MI}$ in $R$NiO$_3$ compounds take the form of a Peierls instability which, primarily, is
structurally triggered by the oxygen rotation motions $R_{xy}$ and $M_z$ and, eventually, is further assisted by the appearance of the E'-type AFM magnetic ordering.
Our Landau model, and its possible extension to incorporate explicitly strain degrees of freedom neglected here for simplicity,  provides a simple and useful
quantitative tool to estimate and interpret how $T_{MI}$ can be tuned toward the monitoring of  oxygen rotation motions $R_{xy}$ and $M_z$ when making solid-solutions \cite{Medarde1997}, applying pressure \cite{Catalan2008} or playing with the epitaxial strain and the orientation of the substrate in thin films \cite{Catalano2015}.  Our findings are relevant to other families of perovskites like A$^{2+}$Fe$^{4+}$O$_3$ compounds~\cite{Akao2003}. For instance, they  can explain why CaFeO$_3$, which exhibits oxygen rotations, undergoes a MIT while SrFeO$_3$ and BaFeO$_3$, which stay cubic, remain metallic. In addition, the same physics is also inherent to manganites like LaMnO$_3$, suggesting a close competition between charge and orbital orderings in this family compounds. However, the situation is slightly different in bismutate like BaBiO$_3$, in which $B_{OC}$ is intrinsically unstable in the cubic phase \cite{Lichtenstein1991}.

\begin{figure}
\resizebox{7.5cm}{!}{\includegraphics{Figure-3}}
  \caption{{\bf Electronic properties} a. Electronic dispersion curves of YNiO$_3$ along different high symmetry line of the Brillouin zone of the $Pm\bar{3}m$ phase (FM case, majority spins):
  $\Gamma = (0,0,0)$, $X = (1/2,0,0)$, $M = (1/2,1/2,0)$ and $R = (1/2,1/2,1/2)$. The Ni 3d $e_g$ bands are highlighted in green. The Fermi energy corresponds to the horizontal blue line.
  The point $q_c = (1/4, 1/4, 1/4)$ is located by vertical dashed blue lines. (b) Evolution of the electronic dispersion curves around the Fermi energy $E_f$ (FM order, majority spins) when
  freezing into the $Pm\bar{3}m$ phase increasing amplitudes of oxygen rotations  ($Q_R = Q_M$ from 0\% to 90\%, lines) and eventually adding the breathing distortion ($Q_B = 100$\%,
  dashed lines). The graph connects high-symmetry points (coordinates in pseudocubic notations) in the Brillouin zone of the $Pbnm$ or $P2_1/n$ 20-atom cell, in which bands have been
  folded respect to (a). }
  \label{fig:3}
\end{figure}

\section{\label{sec:level10}Methods}

First-principles calculations were performed in the framework of Density Functional Theory (DFT) \cite{Hohenberg1964,Kohn1965}
using a Projected Augmented Wave (PAW) approach \cite{Blochl1994} as implemented within the ABINIT package \cite{Gonze2009,Gonze2002,Gonze2005,Torrent2008}.
The calculations relied on the Generalized Gradient Approximation using the PBEsol \cite{Perdew2008}  exchange-correlation
functional. We worked within a collinear spin approximation. We included a Hubbard correction U = 1.5 eV \cite{Liechtenstein1995} on the $3d$ orbitals of
Ni atoms. A special care as been devoted to the determination of the appropriate U parameter (see Supplementary, Section S1).

We made use of JTH atomic potentials \cite{Jollet2014}.  For the wave-functions, we used an energy cutoff of 24 Ha  (38 Ha for the second
grid in the PAW spheres), which guarantees a convergence better than 1 meV on the total energy. The Brillouin-zone was sampled with $k$-point meshes equivalent
to a $12 \times 12 \times 12$ grid in the 5-atoms unit cell. During structural relaxations, thresholds of $10^{-5}$ Ha/bohr on the maximum force and of $10^{-7}$
Ha/bohr$^3$ on the maximum stress have been considered.

The Goldschmidt tolerance factor, \cite{Goldschmidt1926}, $t = d_{R-O} / \sqrt{2} d_{Ni-O}$, of $R$NiO$_3$ compounds were determined using Nicole Benedek's tool \cite{Benedek-tol} relying
on a bond valence model \cite{Lufaso2001} to calculate $d_{R-O}$ and $d_{Ni-O}$, respectively the ideal $R$--O and Ni--O bond lengths in the cubic perovskite structure.

Symmetry-adapted mode analysis have been performed with AMPLIMODE \cite{Orobengoa2009,Perez-Mato2010}. The modes are normalized to their amplitude in the $P2_1/n$ AFM-E' ground state. This normalization is such that in cubic phase (volume of the ground state) $Q_R = 100\%$ corresponds to rotation angles  $\phi_x = \phi_y =$ 11.33$^o$ (Ni-O-Ni angle of 157.33$^o$) , $Q_R = 100\%$ corresponds to a rotation angle $\phi_z =$ 12.12$^o$ (Ni-O-Ni angle of 155.75$^o$)
and $Q_B = 100\% $ corresponds to oxygen displacements $d_O = 0.0358 \AA$.

The Landau model parameters have been fitted for  YNiO$_3$, GdNiO$_3$ and SmNiO$_3$ on first-principles data using in each case a FM cubic phase (volume of the ground state) and interpolated for the other compounds.  $T_{MI}$ was determined analytically (see Supplementary, Section S3).

\section{\label{sec:level10}Supplementary Information}
Supplementary Information is available in the online version of the paper.

\section{\label{sec:level10}Acknowledgements}
The authors thank Y.~Zhang, E.~Bousquet, F.~Ricci, M.~Verstraete, J.-Y. Raty, S. Catalano and J. Varignon for fruitful discussions.
This work was supported by FRS-FNRS project HiT4FiT and ARC project AIMED. J.I. acknowledges support form FNR
Luxembourg Grant P12/4853155 "COFERMAT". Calculations have
been performed  on the C\'eci facilities funded by F.R.S-FNRS (Grant No 2.5020.1) and Tier-1 supercomputer
of the F\'ed\'eration Wallonie-Bruxelles funded by the Walloon Region (Grant No 1117545). They also took
advantage of HPC resources from the French Research and Technology Computing Center (CCRT) and from
the PRACE project Megapasta.