2

I'd like to define an \aboveorbelow command which can be used as follows:

\documentclass{article}
\begin{document}
\section{Animals}
\label{sec:animals}
\section{Another section}
The quick brown fox (from \ref{sec:animals} \aboveorbelow{sec:animals})
jumped over the lazy dog.

The quick brown fox (from \ref{sec:plants} \aboveorbelow{sec:plants})
jumped over the lazy dog.
\section{Plants}
\label{sec:plants}
\end{document}

and will produce "above" if the label with identifier equal to the argument appears earlier in the document than the invocation of \aboveorbelow, "below" if it appears later, and something else if it's missing.

How would I do that while properly recognizing intra-page references?


In the related question:

Referencing to "above" or "below"?

Two solutions require require specific extra-labeling (e.g. with a \here or \locationcommand); another uses the varioref package, but will apparently fail for labels on the same page as the reference. I would rather use existing labels without having to create new ones, and preferably without having to patch the label command with etoolbox or anything like that.

  • @DavidCarlisle: I've been using \autoref rather than \ref for so long I tend to forget it's a hyperref command. Edited. – einpoklum Mar 8 '18 at 21:42
  • if you had provided a test file (still not done) there would be nothing to remember as then you can easily check that the file runs. – David Carlisle Mar 8 '18 at 22:39
  • @DavidCarlisle: (sigh) ok, ok. – einpoklum Mar 8 '18 at 22:51
  • thanks, it really does help (not for this question for me by now, but in general) – David Carlisle Mar 8 '18 at 23:21
4

enter image description here

\documentclass{article}

\newcounter{zzz}

\makeatletter
\def\aboveorbelow#1{%
\stepcounter{zzz}%
\edef\zztmp{\xdef\string\zzz\Roman{zzz}}
\write\@auxout\expandafter{\zztmp{\string\@ifundefined{r@#1}{below}{above}}}%
\csname zzz\Roman{zzz}\endcsname}
\makeatother
\begin{document}

\section{Animals}
\label{sec:animals}
% etc. etc.
\section{Another section}
The quick brown fox (from \ref{sec:animals} \aboveorbelow{sec:animals})
jumped over the lazy dog.

The quick brown fox (from \ref{sec:plants} \aboveorbelow{sec:plants})
jumped over the lazy dog.

\section{Plants}
\label{sec:plants}
\end{document}
  • So, I understand putting an "if undefined" in the aux file. But - why do we need to use a counter for this? – einpoklum Mar 8 '18 at 21:41
  • @einpoklum look in the aux file you need to make a unique command defined to above or below for each use, the counter just arranges that. – David Carlisle Mar 8 '18 at 22:39

Your Answer

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

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