# Variable chapter references

I'm looking to typeset certain references à la varioref thus so: if I reference chapter 3 from within chapter 2, I'd like the output to look like "...in the next chapter---" rather than "...in chapter 3 on page XXX...", similarly for sections, parts, etc.

Does anyone know of such a package or how I may go about tweaking varioref to suit my needs?

-

Here's an option you can try that uses the smartref package. We start off by called \addtoreflist{chapter} which defines the macro

\sgetchapterval{<macro>}{<lab>}


which stores the value of the chapter counter associated with label <lab> in <macro>. Then, using some \ifthenelse statements (provided by xifthen), we condition on whether the chapter reference is for the previous or the next chapter. If otherwise, we default to a varioref reference using \vref.

\documentclass{book}
\usepackage{smartref}% http://ctan.org/pkg/smartref
\usepackage{varioref}% http://ctan.org/pkg/varioref
\usepackage{xifthen}% http://ctan.org/pkg/xifthen

\newcommand{\chapref}[1]{%
\sgetchapterval{\themychap}{#1}% Save chapter counter from reference in \themychap
\setcounter{mychap}{\value{chapter}}%
\ifthenelse{\equal{\mychap}{\themychap}}%
{the next chapter}%
\ifthenelse{\equal{\mychap}{\themychap}}%
{the previous chapter}%
{Chapter~\vref{#1}}%
}%
}%
\begin{document}
\chapter{First chapter} \label{chap:first}
See Chapter~\vref{chap:second} and Chapter~\vref{chap:last}. See \chapref{chap:second} or \chapref{chap:last}.
\chapter{Second chapter} \label{chap:second}
\chapter{Last chapter} \label{chap:last}
See Chapter~\vref{chap:second} and Chapter~\vref{chap:first}. See \chapref{chap:second} or \chapref{chap:first}.
\end{document}


I'm sure you could fine-tune this to your liking.

-
Hmmm... my PDFLaTeX is spiking 100% CPU when trying to compile your example into my manuscript... when killing it I get some Missing \endcsname inserted errors :S –  mpr Oct 23 '11 at 19:38
I don't have that problem with smartref 2002/02/28 v1.9 and varioref 2011/10/02 v1.4z. –  Werner Oct 23 '11 at 20:00
possibly an outdated hyperref... I'm running TeXLive on Ubuntu... they're very anal about what gets to the distro :S –  mpr Oct 23 '11 at 20:02
My MWE does not use hyperref, since non of the included packages use it. –  Werner Oct 23 '11 at 21:22
I'm very sorry, I should have said so in the question... hyperref is to be loaded and supported (ie. the "next chapter" and "previous chapter" should be links rather than just text). I've been doing some testing on your code and found that it threw a lot of warnings if loading smartref before hyperref, inverting the loading order seemed to fix it, but now the code does not work (it always says "previous chapter"). Again, I'm sorry, should I edit the question to reflect this fact or should I just close it and start a new one? –  mpr Oct 24 '11 at 12:09