TransWikia.com

Specifying a "fallback" for undefined references in ref and cref (plain LaTeX and cleverref)

TeX - LaTeX Asked by Michael Kohlhase on June 29, 2021

I am using some of my LaTeX files in multiple documents. And thus in some documents my references will be defined and in others not. I would like to have a way to make ref degrade gracefully.

Thus (many years back) I made a package sref.sty that allowed references of the form

as shown sref[pre=in,fallback=above]{thm.foo}.'

pdflatex formats this to "as shown in Theorem 3.2.1." if a label{thm.foo} was in the document and to "as shown above." else.

BUT the qualified references "Theorem 3.2.1" is (much better) covered in the cleveref package, and I am thinking of re-implementing sref.sty using cleveref.sty. Or alternatively making an extension to cleveref.sty with the functionality above. Or I may be unaware of an existing implementation of what I need that could be used directly.

Any feedback would be appreciated.

One Answer

As a naive approach maybe you can use sref but 'outsource' the non-fallback referencing to cleveref. Something like:

documentclass{article}
usepackage[colorlinks]{hyperref}
usepackage{cleveref}
usepackage{sref}

makeatletter
renewcommandsref@hlink[5][]{%
  edef@fallback{#3}%
  @ifundefined{r@#2}{%
    ifx@fallback@empty% warn about undefined links and show a substitute
      protectG@refundefinedtruePackageWarning{sref}{reference #2 undefined}%
      cref{#2}%
    else%
      protectG@refundefinedtruePackageWarning{sref}{using fallback for undefined reference #2}%
      @fallback%
    fi
  }{%
    #4 cref{#2}%
  }%
}%
makeatother

begin{document}
section{A section}
label{sec}

begin{figure}
centeringfbox{A figure}
caption{with caption}
label{fig}
end{figure}

begin{table}
fbox{A table}
centeringcaption{with caption}
label{tab}
end{table}

As shown sref[pre=in,fallback=nowhere]{fig}, see alsosref{tab}sref[pre=in]{sec}.
As shown sref[pre=in,fallback=nowhere]{fig2}, see alsosref{tab}sref[pre=in]{sec}.

end{document}

enter image description here

Answered by Marijn on June 29, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP