## #StackBounty: #hyperref #tcolorbox #cleveref #thmtools Some cleveref links disappear with tcolorboxenvironment for theorem-like enviro…

### Bounty: 50

In a `memoir` document class book-length document with some 2MB body content and 140K of premable, each distributed over numerous separate files, I use `cleveref` along with `hyperref` and the `tcolorboxenvironment` to create a colored version of each theorem-like environment (e.g., theorem, proposition, lemma) defined by `thmtools`.

All the `cref` links work fine except two: after full processing, the links are missing in the document. In more detail:

• after the initial `pdflatex` run, one of those two label entries never appears in the `.aux` file, although the second label one does appear;
• after a run of `biber` (or `bibtex`) and the 2nd run of `pdflatex`, the second label has now disappeared!

If I do not color the theorems, avoiding `tcolorboxenvironment`, then all links are OK! So the problem does seem to have something to do with `tcolorbox`.

This seems very strange. Unfortunately, I have been unable to reproduce the problem if I reduce the body content just to the two sections containing the theorem-like environments whose labels are used in those links.

For the actual, book-length document, after the initial `pdflatex` run, the `.aux` file includes the following two groups of consecutive lines:

• in the first group, it is the entry for the label `thm-one-pt-cptn` that disappears after the 2nd `pdflatex` run;
• in the second group, an entry for the label `lem:path-prod` ought to appear just before the lines containing `{definition}` but does not.

Here is the extract from the `.aux`:

``````@writefile{loe}{defcounter {refsection}{0}relax }@writefile{loe}{contentsline {theorem}{ifthmt@listswap Theorem~4.66else numberline {4.66}Theoremfi thmtformatoptarg {Alexandroff one-point compactification}}{482}{theorem.4.66}protected@file@percent }
newlabel{thm-one-pt-cptn}{{M@TitleReference {4.66}{One-point compactification}}{482}{Alexandroff one-point compactification}{theorem.4.66}{}}
newlabel{thm-one-pt-cptn@cref}{{[theorem][66][4]4.66}{[1][482][]482}}
@writefile{lla}{defcounter {refsection}{0}relax }@writefile{lla}{contentsline {chapter}{numberline {crtrefnumber{thm-one-pt-cptn}}thm-one-pt-cptn}{482}{theorem.4.66}protected@file@percent }
:
:
:
@writefile{loe}{defcounter {refsection}{0}relax }@writefile{loe}{contentsline {definition}{ifthmt@listswap Definition~5.51else numberline {5.51}Definitionfi }{526}{definition.5.51}protected@file@percent }
newlabel{def:path-prod}{{M@TitleReference {5.51}{Paths}}{526}{}{definition.5.51}{}}
newlabel{def:path-prod@cref}{{[definition][51][]5.51}{[1][526][]526}}
@writefile{lla}{defcounter {refsection}{0}relax }@writefile{lla}{contentsline {chapter}{numberline {crtrefnumber{def:path-prod}}def:path-prod}{526}
``````

The source below gives the flavor of what I’m doing — even though this small example does compile without error.

Question: What might be wrong that just the two particular theorems’ links are affected?

I’m happy to share the source of my book-length project with anybody who might help me track down this strange problem.

``````documentclass{memoir}

% UTILITIES
usepackage{ifthen}
usepackage{xpatch}

% FONTS
usepackage[T2A,T1]{fontenc}
usepackage{amsmath}
usepackage{mathtools}
usepackage{amsthm}

usepackage[french,ngerman,polish,russian,english]{babel}

usepackage[theoremfont]{newtxtext}
usepackage[vvarbb]{newtxmath}
%% Allow : in labels even with babel-french
% Piet van Oostrum
% https://tex.stackexchange.com/a/511212/13492
edefmyoldcatcode{thecatcode`:}
letmyoriglabellabel
deflabel{catcode`:=11 mynewlabel}
defmynewlabel#1{myoriglabel{#1}catcode`:=myoldcatcode}

usepackage{graphicx}
usepackage[most]{tcolorbox}
usepackage{tikz-cd}

usepackage{thmtools}

% SWITCHES
newboolean{colortitles}        % color text in section, etc., titles
newboolean{washthms}       % apply background to theorem-like environs
setboolean{colortitles}{true}
setboolean{washthms}{true}

% COLORS
definecolor{splitcompblue}{RGB}{33,103,165}
colorlet{mythmback}{splitcompblue!5!white}
colorlet{mytitlecolor}{splitcompblue!85!black}
newcommand{thmlikefont}{sffamilybfseries}
ifthenelse{boolean{colortitles}}%
{renewcommand{thmlikefont}{color{mytitlecolor}sffamilybfseries}}%
{}

usepackage[colorlinks, linkcolor=blue,linktocpage=true,linktoc=all]{hyperref}
AtBeginDocument{addtocontents{toc}{protecthypersetup{hidelinks}}}

% CROSS-REFERENCING
usepackage[nameinlink,noabbrev,capitalize]{cleveref}
usepackage{crossreftools}
% Fix to crossreftools
% https://tex.stackexchange.com/a/512175/13492
makeatletter
renewcommand{@@crtextr@ct@ref}[2]{%
expandafter@@@crtextr@ct@refexpandafter{detokenize{#2}}{#1}%
}
newcommand{@@@crtextr@ct@ref}[2]{%
expandafterifxcsname r@#1endcsnamerelax
crt@refundefined%
else
expandafterexpandaftercsname crt@ref@splitter@#2endcsnamecsname r@#1endcsname%
fi
}
makeatother

% TOCS
newififSHORT
newififLONG
%
newcommand{longtocname}{Detailed Contents}
newcommand{shorttocname}{Short Contents}
%
% credit for Ulrike Fischer for this idea, we need to have the
% conditionals defined **inside** the toc
DeclareRobustCommandactivateif{%
letshowShortifSHORT
letshowLongifLONG
letstopShortfi
letstopLongfi
}
% next use patching to add a wrapper around the addcontentsline
% that tableofcontents generates. Since this is inside a group we
% don't having one patch messing up the other
newcommandshortTOC[1][2]{
begingroup
setcounter{tocdepth}{#1}
defcontentsname{shorttocname}%
ifthenelse{boolean{colortitles}}%
{renewcommand{cftchapterfont}{color{mytitlecolor}bfseriessffamily}}%
{renewcommand{cftchapterfont}{bfseriessffamily}}%
xpatchcmd{mem@tableofcontents}%
{addcontentsline{toc}{chapter}{contentsname}}{%
addtocontents{toc}{protectshowShort}%
addcontentsline{toc}{chapter}{contentsname}
addtocontents{toc}{protectstopShort}%
}{typeout{ok}}{typeout{failed}}
LONGtrue
tableofcontents
endgroup
}
newcommandlongTOC[1][3]{
begingroup
setcounter{tocdepth}{#1}
defcontentsname{longtocname}%
ifthenelse{boolean{colortitles}}%
{renewcommand{cftchapterfont}{color{mytitlecolor}bfseriessffamily}%
renewcommand{cftsectionfont}{color{mytitlecolor}bfseriessffamily}%
}%
{renewcommand{cftchapterfont}{bfseriessffamily}%
renewcommand{cftsectionfont}{bfseriessffamily}%
}
xpatchcmd{mem@tableofcontents}%
{%
addcontentsline{toc}{chapter}{contentsname}}{%
addtocontents{toc}{protectshowLong}%
addcontentsline{toc}{chapter}{contentsname}
addtocontents{toc}{protectstopLong}%
}%
{typeout{ok}}{typeout{failed}}
SHORTtrue
tableofcontents
endgroup
}
% automatically add the activation to the toc
AtBeginDocument{
addtocontents{toc}{activateif}
}

% THEOREMS
crefname{theorem}{Theorem}{Theorems}
Crefname{theorem}{Theorem}{Theorems}

swapnumbers

makeatletter
%
declaretheoremstyle[
headfont=thmlikefont,
headpunct={thmlikefont.},
postheadspace=0.5em,
notefont=thmlikefont,
headformat=NAMENUMBERletthmt@space@emptyNOTE,
bodyfont=mdseriesslshape,
spaceabove=12pt,spacebelow=12pt,
hidealllines=true,
backgroundcolor={mythmback},
innerleftmargin=8pt,innerrightmargin=8pt,
postheadhook={%
ifx@emptythmt@shortoptarg
renewcommandaddcontentsline[3]{}
fi}
]{thmstyle}
%
makeatother

theoremstyle{thmstyle}
declaretheorem[name=Theorem,numberwithin=chapter]{theorem}

newcommand{dowashthms}{%
%
tcolorboxenvironment{theorem}{
breakable,
colback=mythmback,
frame hidden,colframe=mythmback,
sharp corners,
left=2pt,right=2pt,top=2pt,bottom=2pt,
before skip=12pt,after skip=12pt}
}

% For index
providecommandgobbleone[1]{}
newcommand{idxmark}[1]{{letgobbleonerelaxmarkboth{sffamilybfseries#1}{sffamilybfseries#1}}#1}
ifthenelse{boolean{washthms}}{dowashthms}{}

makeindex

begin{document}

frontmatter

longTOC[2]
cleardoublepage
shortTOC[1]

mainmatter
chapter{Theory}

section{Triangles}

begin{theorem}[Pythagorean Theorem]
label{thm:pythagoras}
index{Pythagorean Theorem}
index{right triangle}

The square on the hypotenuse of a right triangle equals the sums of the squares upon the other two sides.

end{theorem}

section{Numbers}

begin{theorem}
label{thm:main}
index{main theorem}
index{arithmetic}

\$1+1=2\$.

end{theorem}

noindent From cref{thm:main} it follows that \$2+2=4\$. What does cref{thm:pythagoras} have to do with that?
index{arithmetic}

backmatter
printindex

end{document}
``````

Added 2020-10-17: All the packages actual document uses

Perhaps there’s an issue of package load order with my actual document (although if there is, I still don’t understand why the missing links occur only with two particular instances of theorem-like environments but not with others of exactly the same kind!). So gathered here are all the packages I use in the actual document, which distributes them over a number of separate `.sty` files that are input in the preamble.

``````% FROM main document:
usepackage{iftex}
usepackage{ifthen}
usepackage[l2tabu,orthodox]{nag}

%%%%% FROM mypackages.sty:

RequirePackage{xstring}    % used for IfStrEqCase
RequirePackage{suffix} % used for * cmds, e.g., func*, restrict*
RequirePackage{calc}
RequirePackage{etoolbox}
RequirePackage{xpatch} % used to mod Proof style (in mathdefs.sty}
RequirePackage{adjustbox}  % for scalebox used to define reverse
RequirePackage{scalerel}   % for scalerel

%% STYLING
RequirePackage{moresize}
RequirePackage[strict=true]{csquotes}
RequirePackage{multicol}
RequirePackage{textcase} % used for theorem name key values
RequirePackage{mfirstuc} % used for mod to ll@theorem for listof theorems
RequirePackage[biblatex=true]{embrac} % for upright brackets

%% ENVIRONMENTS
RequirePackage{enumitem}

% TABLES
RequirePackage{longtable}
RequirePackage{makecell}

% TESTING
usepackage[math]{blindtext}

%%%%% FROM myfonts.sty:

% FONTS & LANGUAGES
usepackage[T2A,T1]{fontenc}
usepackage{amsmath}    % avoid dddot clash
usepackage{mathtools}  % avoid unicode-math clash
usepackage{amsthm} % avoid openbox clash

ifTUTeX
usepackage{fontspec}
usepackage{polyglossia}
usepackage{unicode-math}
setdefaultlanguage[variant=american]{english}
setotherlanguages{french,german,polish,russian}
setmainfont{TeX Gyre Termes}[Scale=1.0]
defaultfontfeatures{Scale=MatchLowercase, Ligatures=TeX}
setmathfont{TeX Gyre Termes Math}
newfontfamily{cyrillicfont}{PT Serif}
newcommand{textsi}[1]{textsc{#1}}
newfontfamily{xcheckmarkfont}{LibertinusSerif-Regular.otf}
else
usepackage[russian,french,ngerman,polish,english]{babel}
babeltags{russian=russian,french=french,german=ngerman,polish=polish}
usepackage{substitutefont}   % to allow non-default Cyrillic
substitutefont{T2A}{rmdefault}{Tempora-TLF} % for Cyrillic
usepackage[theoremfont]{newtxtext}
usepackage{textcomp}
usepackage[varqu,varl]{inconsolata} % typewriter
usepackage[vvarbb]{newtxmath}
% ... end font choice
DeclareMathAlphabet{mathbfsf}{encodingdefault}{sfdefault}{bx}{n}
%% Allow : in labels even with babel-french
% Piet van Oostrum
% https://tex.stackexchange.com/a/511212/13492
edefmyoldcatcode{thecatcode`:}
letmyoriglabellabel
deflabel{catcode`:=11 mynewlabel}
defmynewlabel#1{myoriglabel{#1}catcode`:=myoldcatcode}
%
usepackage{pifont}% http://ctan.org/pkg/pifont
newcommand{cmark}{ding{51}}%
newcommand{xmark}{ding{55}}%
usepackage{cmap}             % for searchable, copyable unicode mapping
pdfmapfile{=pdftex.map}
fi

RequirePackage{microtype}

%%%%% FROM mymath.sty:

RequirePackage{xfrac}
RequirePackage{nicefrac}   % def sfrac
% mismath defines N, Z, Q, R, CC with mathbf
RequirePackage{mismath}
RequirePackage[%
frac,rfrac,multskip,greekcaps,greeklower,
root,                 % root dangerous conflicts!
]{mathfixs}
RequirePackage{derivative}
% tools to form certain not's:
ifTUTeX
newcommand{overlaynot}[2]{%
sboxz@{\$m@th#1notaccent{}\$}%
sboxtw@{\$m@th#1#2\$}%
dimen@=dimexpr(httw@-htz@)/2relax
vphantom{raisebox{dimen@}{copyz@}}%
ooalign{hidewidthraisebox{dimen@}{boxz@}hidewidthcrboxtw@}
}
else
usepackage{centernot}
fi
RequirePackage{mywidebar}

%%%%% FROM mygraphics.sty:

RequirePackage{graphicx}
graphicspath{{graphics/}} % set graphics path
% tikz and tcolorbox load xcolor
%RequirePackage[names,dvipsnames,named]{xcolor}
RequirePackage[most]{tcolorbox}
RequirePackage{pict2e} % for bigplus, bigtimes defined in mymath.sty:
RequirePackage{tikz-cd} % modify arrows in mygraphics.sty and/or lucidaarrows.sty

%%%%% FROM links.sty:

%% BIBLIOGRAPHY
RequirePackage[
%backend=bibtex,
backend=biber,
bibstyle=mybooknumeric,
citestyle=numeric,
dashed=true,
defernumbers=true,
urldate=iso,date=iso,seconds=true]%
{biblatex}

%% NOTATION INDEX
RequirePackage[refpage,norefeq,intoc,english,cfg]{nomencl}

%%  CROSS-REFERENCING
RequirePackage{xurl}   % new: break URL anywhere

RequirePackage[type={CC},modifier={by-nc-nd},version={4.0},lang={english}]{doclicense}%

RequirePackage{hyperxmp} % to add metadata info into pdf
usepackage[pdfa]{hyperref}

usepackage[user,hyperref]{zref}
RequirePackage{aliascnt}
RequirePackage[nameinlink,noabbrev,capitalize]{cleveref}
RequirePackage{crossreftools}

%%%%% FROM mythms.sty:
RequirePackage{empheq}

%% THEOREM-LIKE ENVIRONMENTS
RequirePackage{thmtools}

%%%% FROM mylists.sty:

%% ANNOTATIONS
ifthenelse{boolean{usefixme}}{%
RequirePackage[draft]{fixme}%
fxsetup{layout=margin,author=Fix}%
fxusetheme{color}%
}{}
``````

Get this bounty!!!

## #StackBounty: #hyperref #tcolorbox #cleveref #thmtools Some cleveref links disappear with tcolorboxenvironment for theorem-like enviro…

### Bounty: 50

In a `memoir` document class book-length document with some 2MB body content and 140K of premable, each distributed over numerous separate files, I use `cleveref` along with `hyperref` and the `tcolorboxenvironment` to create a colored version of each theorem-like environment (e.g., theorem, proposition, lemma) defined by `thmtools`.

All the `cref` links work fine except two: after full processing, the links are missing in the document. In more detail:

• after the initial `pdflatex` run, one of those two label entries never appears in the `.aux` file, although the second label one does appear;
• after a run of `biber` (or `bibtex`) and the 2nd run of `pdflatex`, the second label has now disappeared!

If I do not color the theorems, avoiding `tcolorboxenvironment`, then all links are OK! So the problem does seem to have something to do with `tcolorbox`.

This seems very strange. Unfortunately, I have been unable to reproduce the problem if I reduce the body content just to the two sections containing the theorem-like environments whose labels are used in those links.

For the actual, book-length document, after the initial `pdflatex` run, the `.aux` file includes the following two groups of consecutive lines:

• in the first group, it is the entry for the label `thm-one-pt-cptn` that disappears after the 2nd `pdflatex` run;
• in the second group, an entry for the label `lem:path-prod` ought to appear just before the lines containing `{definition}` but does not.

Here is the extract from the `.aux`:

``````@writefile{loe}{defcounter {refsection}{0}relax }@writefile{loe}{contentsline {theorem}{ifthmt@listswap Theorem~4.66else numberline {4.66}Theoremfi thmtformatoptarg {Alexandroff one-point compactification}}{482}{theorem.4.66}protected@file@percent }
newlabel{thm-one-pt-cptn}{{M@TitleReference {4.66}{One-point compactification}}{482}{Alexandroff one-point compactification}{theorem.4.66}{}}
newlabel{thm-one-pt-cptn@cref}{{[theorem][66][4]4.66}{[1][482][]482}}
@writefile{lla}{defcounter {refsection}{0}relax }@writefile{lla}{contentsline {chapter}{numberline {crtrefnumber{thm-one-pt-cptn}}thm-one-pt-cptn}{482}{theorem.4.66}protected@file@percent }
:
:
:
@writefile{loe}{defcounter {refsection}{0}relax }@writefile{loe}{contentsline {definition}{ifthmt@listswap Definition~5.51else numberline {5.51}Definitionfi }{526}{definition.5.51}protected@file@percent }
newlabel{def:path-prod}{{M@TitleReference {5.51}{Paths}}{526}{}{definition.5.51}{}}
newlabel{def:path-prod@cref}{{[definition][51][]5.51}{[1][526][]526}}
@writefile{lla}{defcounter {refsection}{0}relax }@writefile{lla}{contentsline {chapter}{numberline {crtrefnumber{def:path-prod}}def:path-prod}{526}
``````

The source below gives the flavor of what I’m doing — even though this small example does compile without error.

Question: What might be wrong that just the two particular theorems’ links are affected?

I’m happy to share the source of my book-length project with anybody who might help me track down this strange problem.

``````documentclass{memoir}

% UTILITIES
usepackage{ifthen}
usepackage{xpatch}

% FONTS
usepackage[T2A,T1]{fontenc}
usepackage{amsmath}
usepackage{mathtools}
usepackage{amsthm}

usepackage[french,ngerman,polish,russian,english]{babel}

usepackage[theoremfont]{newtxtext}
usepackage[vvarbb]{newtxmath}
%% Allow : in labels even with babel-french
% Piet van Oostrum
% https://tex.stackexchange.com/a/511212/13492
edefmyoldcatcode{thecatcode`:}
letmyoriglabellabel
deflabel{catcode`:=11 mynewlabel}
defmynewlabel#1{myoriglabel{#1}catcode`:=myoldcatcode}

usepackage{graphicx}
usepackage[most]{tcolorbox}
usepackage{tikz-cd}

usepackage{thmtools}

% SWITCHES
newboolean{colortitles}        % color text in section, etc., titles
newboolean{washthms}       % apply background to theorem-like environs
setboolean{colortitles}{true}
setboolean{washthms}{true}

% COLORS
definecolor{splitcompblue}{RGB}{33,103,165}
colorlet{mythmback}{splitcompblue!5!white}
colorlet{mytitlecolor}{splitcompblue!85!black}
newcommand{thmlikefont}{sffamilybfseries}
ifthenelse{boolean{colortitles}}%
{renewcommand{thmlikefont}{color{mytitlecolor}sffamilybfseries}}%
{}

usepackage[colorlinks, linkcolor=blue,linktocpage=true,linktoc=all]{hyperref}
AtBeginDocument{addtocontents{toc}{protecthypersetup{hidelinks}}}

% CROSS-REFERENCING
usepackage[nameinlink,noabbrev,capitalize]{cleveref}
usepackage{crossreftools}
% Fix to crossreftools
% https://tex.stackexchange.com/a/512175/13492
makeatletter
renewcommand{@@crtextr@ct@ref}[2]{%
expandafter@@@crtextr@ct@refexpandafter{detokenize{#2}}{#1}%
}
newcommand{@@@crtextr@ct@ref}[2]{%
expandafterifxcsname r@#1endcsnamerelax
crt@refundefined%
else
expandafterexpandaftercsname crt@ref@splitter@#2endcsnamecsname r@#1endcsname%
fi
}
makeatother

% TOCS
newififSHORT
newififLONG
%
newcommand{longtocname}{Detailed Contents}
newcommand{shorttocname}{Short Contents}
%
% credit for Ulrike Fischer for this idea, we need to have the
% conditionals defined **inside** the toc
DeclareRobustCommandactivateif{%
letshowShortifSHORT
letshowLongifLONG
letstopShortfi
letstopLongfi
}
% next use patching to add a wrapper around the addcontentsline
% that tableofcontents generates. Since this is inside a group we
% don't having one patch messing up the other
newcommandshortTOC[1][2]{
begingroup
setcounter{tocdepth}{#1}
defcontentsname{shorttocname}%
ifthenelse{boolean{colortitles}}%
{renewcommand{cftchapterfont}{color{mytitlecolor}bfseriessffamily}}%
{renewcommand{cftchapterfont}{bfseriessffamily}}%
xpatchcmd{mem@tableofcontents}%
{addcontentsline{toc}{chapter}{contentsname}}{%
addtocontents{toc}{protectshowShort}%
addcontentsline{toc}{chapter}{contentsname}
addtocontents{toc}{protectstopShort}%
}{typeout{ok}}{typeout{failed}}
LONGtrue
tableofcontents
endgroup
}
newcommandlongTOC[1][3]{
begingroup
setcounter{tocdepth}{#1}
defcontentsname{longtocname}%
ifthenelse{boolean{colortitles}}%
{renewcommand{cftchapterfont}{color{mytitlecolor}bfseriessffamily}%
renewcommand{cftsectionfont}{color{mytitlecolor}bfseriessffamily}%
}%
{renewcommand{cftchapterfont}{bfseriessffamily}%
renewcommand{cftsectionfont}{bfseriessffamily}%
}
xpatchcmd{mem@tableofcontents}%
{%
addcontentsline{toc}{chapter}{contentsname}}{%
addtocontents{toc}{protectshowLong}%
addcontentsline{toc}{chapter}{contentsname}
addtocontents{toc}{protectstopLong}%
}%
{typeout{ok}}{typeout{failed}}
SHORTtrue
tableofcontents
endgroup
}
% automatically add the activation to the toc
AtBeginDocument{
addtocontents{toc}{activateif}
}

% THEOREMS
crefname{theorem}{Theorem}{Theorems}
Crefname{theorem}{Theorem}{Theorems}

swapnumbers

makeatletter
%
declaretheoremstyle[
headfont=thmlikefont,
headpunct={thmlikefont.},
postheadspace=0.5em,
notefont=thmlikefont,
headformat=NAMENUMBERletthmt@space@emptyNOTE,
bodyfont=mdseriesslshape,
spaceabove=12pt,spacebelow=12pt,
hidealllines=true,
backgroundcolor={mythmback},
innerleftmargin=8pt,innerrightmargin=8pt,
postheadhook={%
ifx@emptythmt@shortoptarg
renewcommandaddcontentsline[3]{}
fi}
]{thmstyle}
%
makeatother

theoremstyle{thmstyle}
declaretheorem[name=Theorem,numberwithin=chapter]{theorem}

newcommand{dowashthms}{%
%
tcolorboxenvironment{theorem}{
breakable,
colback=mythmback,
frame hidden,colframe=mythmback,
sharp corners,
left=2pt,right=2pt,top=2pt,bottom=2pt,
before skip=12pt,after skip=12pt}
}

% For index
providecommandgobbleone[1]{}
newcommand{idxmark}[1]{{letgobbleonerelaxmarkboth{sffamilybfseries#1}{sffamilybfseries#1}}#1}
ifthenelse{boolean{washthms}}{dowashthms}{}

makeindex

begin{document}

frontmatter

longTOC[2]
cleardoublepage
shortTOC[1]

mainmatter
chapter{Theory}

section{Triangles}

begin{theorem}[Pythagorean Theorem]
label{thm:pythagoras}
index{Pythagorean Theorem}
index{right triangle}

The square on the hypotenuse of a right triangle equals the sums of the squares upon the other two sides.

end{theorem}

section{Numbers}

begin{theorem}
label{thm:main}
index{main theorem}
index{arithmetic}

\$1+1=2\$.

end{theorem}

noindent From cref{thm:main} it follows that \$2+2=4\$. What does cref{thm:pythagoras} have to do with that?
index{arithmetic}

backmatter
printindex

end{document}
``````

Added 2020-10-17: All the packages actual document uses

Perhaps there’s an issue of package load order with my actual document (although if there is, I still don’t understand why the missing links occur only with two particular instances of theorem-like environments but not with others of exactly the same kind!). So gathered here are all the packages I use in the actual document, which distributes them over a number of separate `.sty` files that are input in the preamble.

``````% FROM main document:
usepackage{iftex}
usepackage{ifthen}
usepackage[l2tabu,orthodox]{nag}

%%%%% FROM mypackages.sty:

RequirePackage{xstring}    % used for IfStrEqCase
RequirePackage{suffix} % used for * cmds, e.g., func*, restrict*
RequirePackage{calc}
RequirePackage{etoolbox}
RequirePackage{xpatch} % used to mod Proof style (in mathdefs.sty}
RequirePackage{adjustbox}  % for scalebox used to define reverse
RequirePackage{scalerel}   % for scalerel

%% STYLING
RequirePackage{moresize}
RequirePackage[strict=true]{csquotes}
RequirePackage{multicol}
RequirePackage{textcase} % used for theorem name key values
RequirePackage{mfirstuc} % used for mod to ll@theorem for listof theorems
RequirePackage[biblatex=true]{embrac} % for upright brackets

%% ENVIRONMENTS
RequirePackage{enumitem}

% TABLES
RequirePackage{longtable}
RequirePackage{makecell}

% TESTING
usepackage[math]{blindtext}

%%%%% FROM myfonts.sty:

% FONTS & LANGUAGES
usepackage[T2A,T1]{fontenc}
usepackage{amsmath}    % avoid dddot clash
usepackage{mathtools}  % avoid unicode-math clash
usepackage{amsthm} % avoid openbox clash

ifTUTeX
usepackage{fontspec}
usepackage{polyglossia}
usepackage{unicode-math}
setdefaultlanguage[variant=american]{english}
setotherlanguages{french,german,polish,russian}
setmainfont{TeX Gyre Termes}[Scale=1.0]
defaultfontfeatures{Scale=MatchLowercase, Ligatures=TeX}
setmathfont{TeX Gyre Termes Math}
newfontfamily{cyrillicfont}{PT Serif}
newcommand{textsi}[1]{textsc{#1}}
newfontfamily{xcheckmarkfont}{LibertinusSerif-Regular.otf}
else
usepackage[russian,french,ngerman,polish,english]{babel}
babeltags{russian=russian,french=french,german=ngerman,polish=polish}
usepackage{substitutefont}   % to allow non-default Cyrillic
substitutefont{T2A}{rmdefault}{Tempora-TLF} % for Cyrillic
usepackage[theoremfont]{newtxtext}
usepackage{textcomp}
usepackage[varqu,varl]{inconsolata} % typewriter
usepackage[vvarbb]{newtxmath}
% ... end font choice
DeclareMathAlphabet{mathbfsf}{encodingdefault}{sfdefault}{bx}{n}
%% Allow : in labels even with babel-french
% Piet van Oostrum
% https://tex.stackexchange.com/a/511212/13492
edefmyoldcatcode{thecatcode`:}
letmyoriglabellabel
deflabel{catcode`:=11 mynewlabel}
defmynewlabel#1{myoriglabel{#1}catcode`:=myoldcatcode}
%
usepackage{pifont}% http://ctan.org/pkg/pifont
newcommand{cmark}{ding{51}}%
newcommand{xmark}{ding{55}}%
usepackage{cmap}             % for searchable, copyable unicode mapping
pdfmapfile{=pdftex.map}
fi

RequirePackage{microtype}

%%%%% FROM mymath.sty:

RequirePackage{xfrac}
RequirePackage{nicefrac}   % def sfrac
% mismath defines N, Z, Q, R, CC with mathbf
RequirePackage{mismath}
RequirePackage[%
frac,rfrac,multskip,greekcaps,greeklower,
root,                 % root dangerous conflicts!
]{mathfixs}
RequirePackage{derivative}
% tools to form certain not's:
ifTUTeX
newcommand{overlaynot}[2]{%
sboxz@{\$m@th#1notaccent{}\$}%
sboxtw@{\$m@th#1#2\$}%
dimen@=dimexpr(httw@-htz@)/2relax
vphantom{raisebox{dimen@}{copyz@}}%
ooalign{hidewidthraisebox{dimen@}{boxz@}hidewidthcrboxtw@}
}
else
usepackage{centernot}
fi
RequirePackage{mywidebar}

%%%%% FROM mygraphics.sty:

RequirePackage{graphicx}
graphicspath{{graphics/}} % set graphics path
% tikz and tcolorbox load xcolor
%RequirePackage[names,dvipsnames,named]{xcolor}
RequirePackage[most]{tcolorbox}
RequirePackage{pict2e} % for bigplus, bigtimes defined in mymath.sty:
RequirePackage{tikz-cd} % modify arrows in mygraphics.sty and/or lucidaarrows.sty

%%%%% FROM links.sty:

%% BIBLIOGRAPHY
RequirePackage[
%backend=bibtex,
backend=biber,
bibstyle=mybooknumeric,
citestyle=numeric,
dashed=true,
defernumbers=true,
urldate=iso,date=iso,seconds=true]%
{biblatex}

%% NOTATION INDEX
RequirePackage[refpage,norefeq,intoc,english,cfg]{nomencl}

%%  CROSS-REFERENCING
RequirePackage{xurl}   % new: break URL anywhere

RequirePackage[type={CC},modifier={by-nc-nd},version={4.0},lang={english}]{doclicense}%

RequirePackage{hyperxmp} % to add metadata info into pdf
usepackage[pdfa]{hyperref}

usepackage[user,hyperref]{zref}
RequirePackage{aliascnt}
RequirePackage[nameinlink,noabbrev,capitalize]{cleveref}
RequirePackage{crossreftools}

%%%%% FROM mythms.sty:
RequirePackage{empheq}

%% THEOREM-LIKE ENVIRONMENTS
RequirePackage{thmtools}

%%%% FROM mylists.sty:

%% ANNOTATIONS
ifthenelse{boolean{usefixme}}{%
RequirePackage[draft]{fixme}%
fxsetup{layout=margin,author=Fix}%
fxusetheme{color}%
}{}
``````

Get this bounty!!!

## #StackBounty: #hyperref #tcolorbox #cleveref #thmtools Some cleveref links disappear with tcolorboxenvironment for theorem-like enviro…

### Bounty: 50

In a `memoir` document class book-length document with some 2MB body content and 140K of premable, each distributed over numerous separate files, I use `cleveref` along with `hyperref` and the `tcolorboxenvironment` to create a colored version of each theorem-like environment (e.g., theorem, proposition, lemma) defined by `thmtools`.

All the `cref` links work fine except two: after full processing, the links are missing in the document. In more detail:

• after the initial `pdflatex` run, one of those two label entries never appears in the `.aux` file, although the second label one does appear;
• after a run of `biber` (or `bibtex`) and the 2nd run of `pdflatex`, the second label has now disappeared!

If I do not color the theorems, avoiding `tcolorboxenvironment`, then all links are OK! So the problem does seem to have something to do with `tcolorbox`.

This seems very strange. Unfortunately, I have been unable to reproduce the problem if I reduce the body content just to the two sections containing the theorem-like environments whose labels are used in those links.

For the actual, book-length document, after the initial `pdflatex` run, the `.aux` file includes the following two groups of consecutive lines:

• in the first group, it is the entry for the label `thm-one-pt-cptn` that disappears after the 2nd `pdflatex` run;
• in the second group, an entry for the label `lem:path-prod` ought to appear just before the lines containing `{definition}` but does not.

Here is the extract from the `.aux`:

``````@writefile{loe}{defcounter {refsection}{0}relax }@writefile{loe}{contentsline {theorem}{ifthmt@listswap Theorem~4.66else numberline {4.66}Theoremfi thmtformatoptarg {Alexandroff one-point compactification}}{482}{theorem.4.66}protected@file@percent }
newlabel{thm-one-pt-cptn}{{M@TitleReference {4.66}{One-point compactification}}{482}{Alexandroff one-point compactification}{theorem.4.66}{}}
newlabel{thm-one-pt-cptn@cref}{{[theorem][66][4]4.66}{[1][482][]482}}
@writefile{lla}{defcounter {refsection}{0}relax }@writefile{lla}{contentsline {chapter}{numberline {crtrefnumber{thm-one-pt-cptn}}thm-one-pt-cptn}{482}{theorem.4.66}protected@file@percent }
:
:
:
@writefile{loe}{defcounter {refsection}{0}relax }@writefile{loe}{contentsline {definition}{ifthmt@listswap Definition~5.51else numberline {5.51}Definitionfi }{526}{definition.5.51}protected@file@percent }
newlabel{def:path-prod}{{M@TitleReference {5.51}{Paths}}{526}{}{definition.5.51}{}}
newlabel{def:path-prod@cref}{{[definition][51][]5.51}{[1][526][]526}}
@writefile{lla}{defcounter {refsection}{0}relax }@writefile{lla}{contentsline {chapter}{numberline {crtrefnumber{def:path-prod}}def:path-prod}{526}
``````

The source below gives the flavor of what I’m doing — even though this small example does compile without error.

Question: What might be wrong that just the two particular theorems’ links are affected?

I’m happy to share the source of my book-length project with anybody who might help me track down this strange problem.

``````documentclass{memoir}

% UTILITIES
usepackage{ifthen}
usepackage{xpatch}

% FONTS
usepackage[T2A,T1]{fontenc}
usepackage{amsmath}
usepackage{mathtools}
usepackage{amsthm}

usepackage[french,ngerman,polish,russian,english]{babel}

usepackage[theoremfont]{newtxtext}
usepackage[vvarbb]{newtxmath}
%% Allow : in labels even with babel-french
% Piet van Oostrum
% https://tex.stackexchange.com/a/511212/13492
edefmyoldcatcode{thecatcode`:}
letmyoriglabellabel
deflabel{catcode`:=11 mynewlabel}
defmynewlabel#1{myoriglabel{#1}catcode`:=myoldcatcode}

usepackage{graphicx}
usepackage[most]{tcolorbox}
usepackage{tikz-cd}

usepackage{thmtools}

% SWITCHES
newboolean{colortitles}        % color text in section, etc., titles
newboolean{washthms}       % apply background to theorem-like environs
setboolean{colortitles}{true}
setboolean{washthms}{true}

% COLORS
definecolor{splitcompblue}{RGB}{33,103,165}
colorlet{mythmback}{splitcompblue!5!white}
colorlet{mytitlecolor}{splitcompblue!85!black}
newcommand{thmlikefont}{sffamilybfseries}
ifthenelse{boolean{colortitles}}%
{renewcommand{thmlikefont}{color{mytitlecolor}sffamilybfseries}}%
{}

usepackage[colorlinks, linkcolor=blue,linktocpage=true,linktoc=all]{hyperref}
AtBeginDocument{addtocontents{toc}{protecthypersetup{hidelinks}}}

% CROSS-REFERENCING
usepackage[nameinlink,noabbrev,capitalize]{cleveref}
usepackage{crossreftools}
% Fix to crossreftools
% https://tex.stackexchange.com/a/512175/13492
makeatletter
renewcommand{@@crtextr@ct@ref}[2]{%
expandafter@@@crtextr@ct@refexpandafter{detokenize{#2}}{#1}%
}
newcommand{@@@crtextr@ct@ref}[2]{%
expandafterifxcsname r@#1endcsnamerelax
crt@refundefined%
else
expandafterexpandaftercsname crt@ref@splitter@#2endcsnamecsname r@#1endcsname%
fi
}
makeatother

% TOCS
newififSHORT
newififLONG
%
newcommand{longtocname}{Detailed Contents}
newcommand{shorttocname}{Short Contents}
%
% credit for Ulrike Fischer for this idea, we need to have the
% conditionals defined **inside** the toc
DeclareRobustCommandactivateif{%
letshowShortifSHORT
letshowLongifLONG
letstopShortfi
letstopLongfi
}
% next use patching to add a wrapper around the addcontentsline
% that tableofcontents generates. Since this is inside a group we
% don't having one patch messing up the other
newcommandshortTOC[1][2]{
begingroup
setcounter{tocdepth}{#1}
defcontentsname{shorttocname}%
ifthenelse{boolean{colortitles}}%
{renewcommand{cftchapterfont}{color{mytitlecolor}bfseriessffamily}}%
{renewcommand{cftchapterfont}{bfseriessffamily}}%
xpatchcmd{mem@tableofcontents}%
{addcontentsline{toc}{chapter}{contentsname}}{%
addtocontents{toc}{protectshowShort}%
addcontentsline{toc}{chapter}{contentsname}
addtocontents{toc}{protectstopShort}%
}{typeout{ok}}{typeout{failed}}
LONGtrue
tableofcontents
endgroup
}
newcommandlongTOC[1][3]{
begingroup
setcounter{tocdepth}{#1}
defcontentsname{longtocname}%
ifthenelse{boolean{colortitles}}%
{renewcommand{cftchapterfont}{color{mytitlecolor}bfseriessffamily}%
renewcommand{cftsectionfont}{color{mytitlecolor}bfseriessffamily}%
}%
{renewcommand{cftchapterfont}{bfseriessffamily}%
renewcommand{cftsectionfont}{bfseriessffamily}%
}
xpatchcmd{mem@tableofcontents}%
{%
addcontentsline{toc}{chapter}{contentsname}}{%
addtocontents{toc}{protectshowLong}%
addcontentsline{toc}{chapter}{contentsname}
addtocontents{toc}{protectstopLong}%
}%
{typeout{ok}}{typeout{failed}}
SHORTtrue
tableofcontents
endgroup
}
% automatically add the activation to the toc
AtBeginDocument{
addtocontents{toc}{activateif}
}

% THEOREMS
crefname{theorem}{Theorem}{Theorems}
Crefname{theorem}{Theorem}{Theorems}

swapnumbers

makeatletter
%
declaretheoremstyle[
headfont=thmlikefont,
headpunct={thmlikefont.},
postheadspace=0.5em,
notefont=thmlikefont,
headformat=NAMENUMBERletthmt@space@emptyNOTE,
bodyfont=mdseriesslshape,
spaceabove=12pt,spacebelow=12pt,
hidealllines=true,
backgroundcolor={mythmback},
innerleftmargin=8pt,innerrightmargin=8pt,
postheadhook={%
ifx@emptythmt@shortoptarg
renewcommandaddcontentsline[3]{}
fi}
]{thmstyle}
%
makeatother

theoremstyle{thmstyle}
declaretheorem[name=Theorem,numberwithin=chapter]{theorem}

newcommand{dowashthms}{%
%
tcolorboxenvironment{theorem}{
breakable,
colback=mythmback,
frame hidden,colframe=mythmback,
sharp corners,
left=2pt,right=2pt,top=2pt,bottom=2pt,
before skip=12pt,after skip=12pt}
}

% For index
providecommandgobbleone[1]{}
newcommand{idxmark}[1]{{letgobbleonerelaxmarkboth{sffamilybfseries#1}{sffamilybfseries#1}}#1}
ifthenelse{boolean{washthms}}{dowashthms}{}

makeindex

begin{document}

frontmatter

longTOC[2]
cleardoublepage
shortTOC[1]

mainmatter
chapter{Theory}

section{Triangles}

begin{theorem}[Pythagorean Theorem]
label{thm:pythagoras}
index{Pythagorean Theorem}
index{right triangle}

The square on the hypotenuse of a right triangle equals the sums of the squares upon the other two sides.

end{theorem}

section{Numbers}

begin{theorem}
label{thm:main}
index{main theorem}
index{arithmetic}

\$1+1=2\$.

end{theorem}

noindent From cref{thm:main} it follows that \$2+2=4\$. What does cref{thm:pythagoras} have to do with that?
index{arithmetic}

backmatter
printindex

end{document}
``````

Added 2020-10-17: All the packages actual document uses

Perhaps there’s an issue of package load order with my actual document (although if there is, I still don’t understand why the missing links occur only with two particular instances of theorem-like environments but not with others of exactly the same kind!). So gathered here are all the packages I use in the actual document, which distributes them over a number of separate `.sty` files that are input in the preamble.

``````% FROM main document:
usepackage{iftex}
usepackage{ifthen}
usepackage[l2tabu,orthodox]{nag}

%%%%% FROM mypackages.sty:

RequirePackage{xstring}    % used for IfStrEqCase
RequirePackage{suffix} % used for * cmds, e.g., func*, restrict*
RequirePackage{calc}
RequirePackage{etoolbox}
RequirePackage{xpatch} % used to mod Proof style (in mathdefs.sty}
RequirePackage{adjustbox}  % for scalebox used to define reverse
RequirePackage{scalerel}   % for scalerel

%% STYLING
RequirePackage{moresize}
RequirePackage[strict=true]{csquotes}
RequirePackage{multicol}
RequirePackage{textcase} % used for theorem name key values
RequirePackage{mfirstuc} % used for mod to ll@theorem for listof theorems
RequirePackage[biblatex=true]{embrac} % for upright brackets

%% ENVIRONMENTS
RequirePackage{enumitem}

% TABLES
RequirePackage{longtable}
RequirePackage{makecell}

% TESTING
usepackage[math]{blindtext}

%%%%% FROM myfonts.sty:

% FONTS & LANGUAGES
usepackage[T2A,T1]{fontenc}
usepackage{amsmath}    % avoid dddot clash
usepackage{mathtools}  % avoid unicode-math clash
usepackage{amsthm} % avoid openbox clash

ifTUTeX
usepackage{fontspec}
usepackage{polyglossia}
usepackage{unicode-math}
setdefaultlanguage[variant=american]{english}
setotherlanguages{french,german,polish,russian}
setmainfont{TeX Gyre Termes}[Scale=1.0]
defaultfontfeatures{Scale=MatchLowercase, Ligatures=TeX}
setmathfont{TeX Gyre Termes Math}
newfontfamily{cyrillicfont}{PT Serif}
newcommand{textsi}[1]{textsc{#1}}
newfontfamily{xcheckmarkfont}{LibertinusSerif-Regular.otf}
else
usepackage[russian,french,ngerman,polish,english]{babel}
babeltags{russian=russian,french=french,german=ngerman,polish=polish}
usepackage{substitutefont}   % to allow non-default Cyrillic
substitutefont{T2A}{rmdefault}{Tempora-TLF} % for Cyrillic
usepackage[theoremfont]{newtxtext}
usepackage{textcomp}
usepackage[varqu,varl]{inconsolata} % typewriter
usepackage[vvarbb]{newtxmath}
% ... end font choice
DeclareMathAlphabet{mathbfsf}{encodingdefault}{sfdefault}{bx}{n}
%% Allow : in labels even with babel-french
% Piet van Oostrum
% https://tex.stackexchange.com/a/511212/13492
edefmyoldcatcode{thecatcode`:}
letmyoriglabellabel
deflabel{catcode`:=11 mynewlabel}
defmynewlabel#1{myoriglabel{#1}catcode`:=myoldcatcode}
%
usepackage{pifont}% http://ctan.org/pkg/pifont
newcommand{cmark}{ding{51}}%
newcommand{xmark}{ding{55}}%
usepackage{cmap}             % for searchable, copyable unicode mapping
pdfmapfile{=pdftex.map}
fi

RequirePackage{microtype}

%%%%% FROM mymath.sty:

RequirePackage{xfrac}
RequirePackage{nicefrac}   % def sfrac
% mismath defines N, Z, Q, R, CC with mathbf
RequirePackage{mismath}
RequirePackage[%
frac,rfrac,multskip,greekcaps,greeklower,
root,                 % root dangerous conflicts!
]{mathfixs}
RequirePackage{derivative}
% tools to form certain not's:
ifTUTeX
newcommand{overlaynot}[2]{%
sboxz@{\$m@th#1notaccent{}\$}%
sboxtw@{\$m@th#1#2\$}%
dimen@=dimexpr(httw@-htz@)/2relax
vphantom{raisebox{dimen@}{copyz@}}%
ooalign{hidewidthraisebox{dimen@}{boxz@}hidewidthcrboxtw@}
}
else
usepackage{centernot}
fi
RequirePackage{mywidebar}

%%%%% FROM mygraphics.sty:

RequirePackage{graphicx}
graphicspath{{graphics/}} % set graphics path
% tikz and tcolorbox load xcolor
%RequirePackage[names,dvipsnames,named]{xcolor}
RequirePackage[most]{tcolorbox}
RequirePackage{pict2e} % for bigplus, bigtimes defined in mymath.sty:
RequirePackage{tikz-cd} % modify arrows in mygraphics.sty and/or lucidaarrows.sty

%%%%% FROM links.sty:

%% BIBLIOGRAPHY
RequirePackage[
%backend=bibtex,
backend=biber,
bibstyle=mybooknumeric,
citestyle=numeric,
dashed=true,
defernumbers=true,
urldate=iso,date=iso,seconds=true]%
{biblatex}

%% NOTATION INDEX
RequirePackage[refpage,norefeq,intoc,english,cfg]{nomencl}

%%  CROSS-REFERENCING
RequirePackage{xurl}   % new: break URL anywhere

RequirePackage[type={CC},modifier={by-nc-nd},version={4.0},lang={english}]{doclicense}%

RequirePackage{hyperxmp} % to add metadata info into pdf
usepackage[pdfa]{hyperref}

usepackage[user,hyperref]{zref}
RequirePackage{aliascnt}
RequirePackage[nameinlink,noabbrev,capitalize]{cleveref}
RequirePackage{crossreftools}

%%%%% FROM mythms.sty:
RequirePackage{empheq}

%% THEOREM-LIKE ENVIRONMENTS
RequirePackage{thmtools}

%%%% FROM mylists.sty:

%% ANNOTATIONS
ifthenelse{boolean{usefixme}}{%
RequirePackage[draft]{fixme}%
fxsetup{layout=margin,author=Fix}%
fxusetheme{color}%
}{}
``````

Get this bounty!!!

## #StackBounty: #hyperref #lists #exercises Using the Exercise package, how do we get the title of an answer group to match that of the e…

### Bounty: 100

``````%--------------------------------------------------------------------------------------------------------- %
documentclass[english]{book}
%--------------------------------------------------------------------------------------------------------- %
%
usepackage[fleqn]{amsmath} %
usepackage[explicit]{titlesec} %
usepackage{titletoc} %
usepackage{fancyhdr} %
usepackage{fancyref} %
usepackage{babel} %
usepackage{tikz} % tikz - essential
usepackage{newtxtext} %
usepackage{libertine} %
usepackage{setspace} %
usepackage{colortbl} % changed to just colortbl
usepackage{stackengine} %
usepackage[paperwidth=170mm,paperheight=240mm,textwidth=132mm,lmargin=12.5mm,rmargin=12.5mm,bindingoffset=12.5mm,noheadfoot,nomarginpar,showframe,showcrop]{geometry}
usepackage[a4,frame,cam,center]{crop} %
usepackage{stackengine} %
usepackage{graphicx} %
usepackage[skins,theorems,most]{tcolorbox} %
usepackage{ifpdf} %
usepackage{exercise} %
usepackage{ifthen}newboolean{firstanswerofthechapter} %
usepackage{hyperref} %

definecolor{ThemeColor}{rgb}{0.50,0.04,0.04} % ThemeColor DarkRed
definecolor{DarkBlue}{rgb}{0.00,0.08,0.45} % #000086
definecolor{DarkOrange}{rgb}{0.55,0.22,0.05} % #FB9902
definecolor{DarkRed}{rgb}{0.45,0.06,0.06} % #880000
definecolor{LightOrange}{rgb}{1.00,0.87,0.64} % #FB9902
definecolor{LightYellow}{rgb}{1.00,1.00,0.85}

tcbset{myinnerbox/.style={no shadow, shrink tight, arc=1.5pt, extrude by=2.0mm,
colframe=black, boxrule=0.7pt, frame style={opacity=0.25},
interior style={opacity=0.5}, colback=black!5!white}}

%
% ------------------------------------- Exercise preliminaries ------------------------------------------- %
%

makeatletter
let @subQuestionHeader@original=@subQuestionHeader
newcommand{@subQuestionHeader@noItem}{ %
hspace{0pt} % between (a) and (b)
begingroup
@getsubQuestionInfo
subQuestionHeaderDifficulty
subQuestionNBhspace{0.4pt} % adjust space from the ) bracket
endgroup
begingroup
@getsubQuestionInfo
subQuestionHeaderTitle
endgroup % affects subquestion on new line
ignorespaces
}

newcommand{subQuestionOnSameLine}{ %
let @subQuestionHeader=@subQuestionHeader@noItem
subQuestion
}
newcommand{subQuestionOnNewLine}{ %
let @subQuestionHeader=@subQuestionHeader@original {} % \[-9pt]
subQuestion
}
makeatother

makeatletter
defendExerciseEnv{termineliste{1}@EndExeBoxvspace{6pt}%
vskipExerciseSkipAfter}

gdefendAnswerEnv{termineliste{1}@EndExeBoxvspace{8pt}termineliste{0}vskipAnswerSkipAfter}
makeatother

renewcommand{AtBeginExercise}{vspace{-6pt}}
%
% ----------------------------------------------- Define counters ------------------------------------ %
%
numberwithin{Exercise}{chapter} % ! not counterwithin
numberwithin{Answer}{chapter}
newcounter{problem}[Exercise] %

renewcommand{ExerciseName}{Exercise}
renewcommand{QuestionNB}{tcbhighmath[size=fbox,colframe=DarkRed,colback=blue!12!white]{arabic{Question}}hspace{3.2pt}}
renewcommand{QuestionHeaderTitle}{emph{(QuestionTitle)} }
renewcommand{subQuestionNB}{alph{subQuestion}hspace{0.7pt})hspace{1.3pt}}
renewcommand{ExerciseHeaderTitle}{hspace{2.4pt}-hspace{1.6pt}-hspace{1.6pt}-;ExerciseTitle}
renewcommand{QuestionHeaderDifficulty}{theQuestionDifficulty }

% Setting up the EXERCISES header (conditional)...
renewcommand{ExerciseHeader}
{ifthenelse{boolean{firstanswerofthechapter}} % line 1
%
{newpagenoindenthspace{1.5pt}vspace*{4pt} % line 2

% AAAAAAAAAAAA
{libertineSBfontsize{12}{14}selectfont{text{Exercises based on the content of text{chapterhspace{2.4pt}thechapter}}}} % END OF MAJOR TITLE line 5

vspace{9pt} % BBBBBBBBBBBB
noindentdefstackalignment{l}stackunder[4.5pt]{colorbox{LightOrange} % line 6
{libertineSBfontsize{11.5}{15}selectfont{textcolor{ThemeColor}{Exercise~ExerciseHeaderNB}}}ExerciseHeaderTitlenewlinesmallskip}
{textcolor{DarkOrange}{rule{linewidth}{1.2pt}}}} % ELSE line 7
%
{noindentdefstackalignment{l}stackunder[4.5pt]{colorbox{LightOrange} % line 8
%
{libertineSBfontsize{11.5}{15}selectfont{textcolor{ThemeColor} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
{Exercise~ExerciseHeaderNB}}}ExerciseHeaderTitlenewlinenewlinesmallskip} % line 9
{textcolor{DarkOrange}{rule{linewidth}{1.2pt}}}}} % line 10

% Setting up the ANSWERS header (conditional)...
renewcommand{AnswerHeader}
{ifthenelse{boolean{firstanswerofthechapter}} % this is correct
%
{newpagenoindenthspace{1.5pt}vspace*{4pt}
% AAAAAAAAAAAA
{libertineSBfontsize{11}{14}selectfont{Answershspace{1.2pt}/hspace{0.1pt}solutions to exercises based on text{chapterhspace{2.4pt}thechapter}}}  % END OF MAJOR TITLE line 5

vspace{9pt} % BBBBBBBBBB
noindentdefstackalignment{l}stackunder[4.5pt]
{colorbox{LightOrange} % continue
{libertineSBfontsize{11}{14}selectfont{textcolor{ThemeColor}
{Answers to exercise~ExerciseHeaderNBhspace{3.4pt}on hspace{0.6pt}phspace{1.5pt}pageref{AnswerRef}
ExerciseHeaderTitle},}}} %
{textcolor{DarkOrange}{rule{linewidth}{1.2pt}}}vspace{3pt}} % ELSE line 7
%
%
{noindentdefstackalignment{l}stackunder[4.5pt]{colorbox{LightOrange} % line 8
%
{libertineSBfontsize{11}{14}selectfont{textcolor{ThemeColor} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
{Answers to exercise~ExerciseHeaderNBhspace{3.4pt}on hspace{0.6pt}phspace{1.5pt}pageref{AnswerRef}
ExerciseHeaderTitle},}}} %
{textcolor{DarkOrange}{rule{linewidth}{1.2pt}}}vspace{3pt}}}

begin{document}

setstretch{1.20}
chapter{} % Chapter 1

setboolean{firstanswerofthechapter}{true}
begin{Exercise}[title={title of FIRST exercise},label=chap_01_exer_01] % EX 1_1
Question{Question 1}
Question{Question 2}
end{Exercise}

setboolean{firstanswerofthechapter}{false}
begin{Exercise}[title={title of SECOND exercise},label=chap_01_exer_02] % EX 1_2
Question{Question 1}
Question{Question 2}
end{Exercise}

begin{Exercise}[title={title of THIRD exercise},label=chap_01_exer_03] % EX 1_3

Question{Question 1}
Question{Qustion 2}
end{Exercise}

setboolean{firstanswerofthechapter}{true}
begin{Answer}[ref={chap_01_exer_01}]
Question{Answer to question 1}
Question{Answer to question 2}
end{Answer}

vspace{6pt}
noindent {color{DarkBlue}fontsize{11}{12}selectfont{The wordinghspace{0.6pt}: ``,title of THIRD exercise,'' is what I wish to change - it should be the

noindent same as the title description in the corresponding questionhspace{0.7pt}.

vspace{4pt}
noindent It suggests the use of a construction using a ``,hash \$1\$,'' - but I do not understand that.}}

vspace{15pt}
setboolean{firstanswerofthechapter}{false}
begin{Answer}[ref={chap_01_exer_02}]
Question{Answer to question 1}
Question{Answer to question 2}
end{Answer}

begin{Answer}[ref={chap_01_exer_03}]
Question{Answer to question 1}

Question{Answer to question 2}
end{Answer}

end{document}
``````

Get this bounty!!!

## #StackBounty: #biblatex #hyperref #cross-referencing #cleveref #back-referencing How to backreference floating environments like listin…

### Bounty: 100

I do want to put some source code entries and some figures/images in my appendix for more details see this question), and thus I would find it very useful to have a backlink there (just like you can have in the bibliography or acronym TOC with `acro` or so), because the part where it is referenced is very far away from where it is printed (i.e. in the appendix).

In short, this question basically assumes the "opposite" of the question „Keeping tables/figures close to where they are mentioned”, i.e. my images/listings are far away from where they are mentioned and thus I’d like a backref for them, so people can find the explanation for a code snippet or image I cite when they just look at the appendix.

I have used `hyperref`‘s commands for referencing the figure or listing created via minted, so e.g. `autoref`, `nameref` or `fullref`.

Thus, is it possible somehow to add a backreference (backref/backlink) to the caption – or keeping my other idea in mind of using headlines instead of captions there somewhere else in the text?

I e.g. want a caption like this:

Source code snippet showing how A makes B. (mentioned on pages 5, 7-8.)

The exact style, i.e. whether it is compact and skips pages or what intro it uses ("mentioned on pages" could also juist be replaced by "pp." or another abbrevation that is likely already defined in some biblatex or acro macro) so, does not matter, but I e.g. like the style `acro` uses.)

Note: For obvious reasons that backref should possibly exclude a link in a TOC like `listoflistings` or `listoffigures`.

Get this bounty!!!

## #StackBounty: #xetex #hyperref #kerning #makeindex #glossaries-extra Proper kerning in case the symbol with a subscript is a glossary t…

### Bounty: 500

Continuing How to get glossary terms to properly typeset subscripts/superscripts?, let’s consider the following input:

``````documentclass{book}
usepackage{fontspec}
usepackage[ngerman]{babel}
usepackage{mathtools}mathtoolsset{mathic=true} %%% See http://tex.stackexchange.com/a/3496/
usepackage{amssymb}
usepackage{unicode-math}
setmainfont[Ligatures=TeX]{TeX Gyre Termes}
setsansfont{TeX Gyre Heros}[Scale=0.88]
setmonofont{TeX Gyre Cursor}
setmathfont[Ligatures=TeX]{TeX Gyre Termes Math}
setmathfont[Ligatures=TeX,range={setminus}]{Asana Math}
setmathfont[Ligatures=TeX,Extension=.otf,range={"2A3E},BoldFont=XITSMath-Bold]{XITSMath-Regular}%%% The fat semicolon
usepackage[unicode,hidelinks]{hyperref}
usepackage[makeindex,toc,nogroupskip,nomain]{glossaries-extra} %%% glossaries-extra internally loads glossaries, and glossaries according to its documentation should be loaded after hyperref.
%%% The next hack improves how hyperref jives with svindd.ist, see https://tex.stackexchange.com/a/429446
makeatletter
def@commahyperpage#1{@@commahyperpage#1,,,\}
def@@commahyperpage#1,,#2,#3\{%
ifx\#2\%
HyInd@pagelink{#1}%
else
HyInd@pagelink{#1},,HyInd@pagelink{#2}%
fi
}
makeatother
setglossarystyle{long3col}renewcommand{glspagelistwidth}{10em}
GlsSetQuote{+} %%% Hack to work with makeindex
usepackage[babel=true,verbose=errors]{microtype}
newcommand{NNZ}{gls{not:nonnegativeNat}}% ℕ_{}
newcommand{NNP}{gls{not:positiveNat}}
newcommand{finiteWordsSet}[1]{#1^{gls{not:finiteWordsSymbol}}} %%% Sequences
newglossary[nlg]{notation}{not}{ntn}{Symbolverzeichnis}
makeglossaries
newglossaryentry{not:positiveNat}{type=notation, name={(ℕ_{mkern-2mu>0})}, text={ℕ_{mkern-1mu>0}}, sort={Nplus}, description={Die Menge positiver ganzer Zahlen.}}
newglossaryentry{not:nonnegativeNat}{type=notation, name={(ℕ_{mkern-2muge 0})}, text={ℕ_{mkern-1muge 0}}, sort={N0}, description={Die Menge nichtnegativer ganzer Zahlen.}}
newglossaryentry{not:finiteWordsSymbol}{type=notation, name={(cdot^*)}, text={*}, sort={*finiteWordsSymbol}, description={Gegeben eine beliebige Menge (Z), bezeichnen wir mit (Z^*) die Menge aller endlichen Wörter (also, endlichen Sequenzen) über (Z).}}
begin{document}
What we typeset is:
[finiteWordsSet{NNZ} finiteWordsSet{NNP}]
(finiteWordsSet{NNZ} finiteWordsSet{NNP})

bigskip

However, the visual appearence leaves much to be desired. The star should better be closer to the double-struck capital N and a little bit higher, such as in
[ℕ^{raisebox{.1ex}{\$scriptstyle *\$}}_{mkern-2mu>0} ℕ_{mkern-2muge 0}^{raisebox{.1ex}{\$scriptstyle *\$}}]
(ℕ_{mkern-2mu>0}^{raisebox{.1ex}{\$scriptstyle *\$}} ℕ_{mkern-2muge 0}^{raisebox{.1ex}{\$scriptstyle *\$}})\
and all the symbols should be still properly linked to the glossary.
printglossary
end{document}
``````

Compiling with `xelatex file && makeindex -g -s file.ist -t file.nlg -o file.not file.ntn && xelatex file` gives us this:

How to adapt the code in such a way that the macro calls `finiteWordsSet{NNZ}` and `finiteWordsSet{NNP}` produce a visually pleasant output without losing the links to the glossary and perform as before for the other actual arguments? If that’s too difficult, I’d even appreciate single macros `finiteWordsOverNaturalsZ` and `finiteWordsOverNaturalsP` that would produce the visually pleasant representation of the notation for sequences of naturals with/without zero?

Get this bounty!!!

## #StackBounty: #hyperref #urls #latex3 #catcodes Accepting special characters in arguments passing them further

### Bounty: 50

I would like to define a macro very similar to `url`, that accepts more or less arbitrary strings (including hashes/`#`) and passes them to other commands (i.e., `href`, `url`, `nolinkurl`). I have tried to apply some other solutions (e.g., changing catcodes locally etc.), but failed. I would also like my new macro to be passable to other macros like `footnote`.

The following non-working MWE shows an implementation, taking arbitrary strings as inputs, converts them to escaped tex-compatible strings (by use of `tl_to_str:n` as an xparse command processor), and passes them along without errors. However, this completely breaks the meaning of the macros, which just output the escaped text (I don’t really understand why).

Ideally, the macro would even detect hashes and escape them when passing the respective argument to `href`, because that’s required (but not for the original `url`).

``````documentclass{article}
PassOptionsToPackage{hyphens}{url}
usepackage[hidelinks]{hyperref}

usepackage{xparse}
usepackage{letltxmacro}

ExplSyntaxOn
LetLtxMacrooldurlurl
RenewDocumentCommandurl{>{tl_to_str:n}m>{tl_to_str:n}g}{%
IfNoValueTF{#2}{%
oldurl{#1}%
}{%
href{#1}{#2}%
}%
}
ExplSyntaxOff

setlength{parindent}{0pt}
begin{document}

smallskip
noindentrule{linewidth}{1ex}

smallskip
urlhfillhspace{0.6linewidth}url{https://www.yahoo.com/break/#me}

smallskip
2url#1hfillhspace{0.6linewidth}url{https://www.yahoo.com/break-me/#please}{www.yahoo.com/break/me/please}

smallskip
2url#2hfillhspace{0.6linewidth}url{https://www.yahoo.com/break-me/please}{www.yahoo.com/break/me/#please}

smallskip
2url#3hfillhspace{0.6linewidth}url{https://www.yahoo.com/break-me/#please}{www.yahoo.com/break-me/#please}

noindentrule{linewidth}{1ex}

footnote: footnote{url{https://www.yahoo.com/break-me/#please}{www.yahoo.com/break-me/#please}}
end{document}
``````

Get this bounty!!!

## #StackBounty: #hyperref #chemnum chemnum: bringing custom labels to PDF bookmarks

### Bounty: 50

This question was already asked on GitHub. The author of the great chemnum package initially proposed that one can define custom labels for chemical compounds. This is very useful when referencing compounds with only slightly differing substituents.

A MWE looks like this:

``````% arara: pdflatex

documentclass{article}
usepackage{chemnum}
usepackage{chemformula}
usepackage{hyperref}

ExplSyntaxOn
NewDocumentCommand setcmpdlabel {mm}
{ chemnum_compound_set_property:nnn {#1} {counter-representation} {#2} }
ExplSyntaxOff

cmpd*{Me2bdc}
setcmpdlabel{Me2bdc}{ch{Me2L^1}}
cmpd*{H2bdc}
setcmpdlabel{H2bdc}{ch{H2L^1}}

begin{document}

section{About texorpdfstring{cmpd{Me2bdc}}{cmpdplain{Me2bdc}}}
Lorem ipsum.

section{About texorpdfstring{cmpd{H2bdc}}{cmpdplain{H2bdc}}}
Lorem ipsum.

end{document}
``````

and will produce the following PDF output:

Within the section titles, the compounds Me2L1 and H2L1 (which are internally assigned by chemnum to `<ID>` 1 and 2, respectively) are represented as desired. However, the PDF bookmarks (left column) show the values of `<ID>` instead of Me2L1 (H2L1). How can I bring the user-defined values to PDF bookmarks? `cmpdproperty{H2bdc}{counter-representation}` will also not print the value of `counter-representation`.

I’m aware that the inclusion of subscripts/superscripts within PDF bookmarks may need conversion to appropriate Unicode chars and maybe somebody has an idea on how to achieve this. It may be preferable to define a PDF bookmark representation for every user-defined compound, I guess?

Thanks for your help!

Get this bounty!!!

## #StackBounty: #tikz-pgf #hyperref #amsthm #lastpage Why does `usepackage{cleveref}` fix the conflict between (new) hyperref, amsthm, a…

### Bounty: 50

This is not a duplicate of this question.

Why does adding `usepackage{cleveref}` solve the conflict between `lastpage`, `hyperref`, and `amsthm` during externalization?

The known answer proposes `tikzifexternalizing` to conditionally load the packages when not externalizing, however, i cannot do this, since the packages are loaded by a class that i am required to use.
Obviously, the solution can do everything but to change the `untouchable` class.
It is the MDPI class template but i reduced it to the `untouchable` class in the minimal example as follows:

``````begin{filecontents}{untouchable.cls}
LoadClass{article}
% This is a model of a class file that requires the packages
% that impedes the pgf-tikz externalization.
% I tested this example on Texlive 2016, 2018 and 2020.
% It works on 2016.
% It fails on 2018 and 2020 but you can make it work if
% only one of the three following lines is commented out.
% Remember to remove existing untouchable.cls!
RequirePackage{amsthm}
RequirePackage{lastpage}
RequirePackage{hyperref}
% It works with 2018 and 2020 when i downgrade to the
% hyperref from 2016, by moving it into the ~/texmf.
end{filecontents}

documentclass{untouchable}

% The workaround is to include cleveref. A hunch i had,
% after diffing the hyperref.sty from 2016 and 2018 near
% lines 7335. Uncomment the following to make it work:
%usepackage{cleveref}

usepackage{tikz}
usetikzlibrary{external}
% The lastpage warning about the aux file can be silenced by
% switching to make externalization, but this does not solve
% the issue. You can test it by uncommenting the next line:
%tikzset{external/mode=list and make}

tikzexternalize

% This implementation of the current answer from Ulrike Fischer
% does not seem to patch anything, as indicated by the tracingpatches output:
usepackage{etoolbox}
tracingpatches
makeatletter
tikzifexternalizing{%
patchcmdAtEndDocument{lastpage@fileswtest{thepage}{lastpage@lastpage}}{}{fail}
patchcmdAtEndDocument{lastpage@fileswtestHy}{}{fail}}{}
makeatother

begin{document}
The document must include at least one tikzpicture:
begin{tikzpicture}
draw (0,0) rectangle (2,3);
end{tikzpicture}
end{document}
``````

It fails the same way with the error:

``````! Argument of Hy@temp has an extra }.
<inserted text>
par
l.20 end{document}
``````

Interestingly, i found that when i use the hyperref from Texlive 2016 everything seems fine. A diff on `hyperref.sty` gave me the idea to
include `cleveref` which seems to solve it. But Why? Can some one insoder check the code and rule out that this is a bug?

Get this bounty!!!

## #StackBounty: #hyperref #ref Full referencing from exercises

### Bounty: 50

I have the following setup:

``````documentclass{book}
usepackage{enumitem}
usepackage{hyperref}
hypersetup
{
colorlinks=true,
linktoc=all,
linkcolor=black,
citecolor=teal,
}
newlist{exercise}{enumerate}{5}
setlist[exercise]{label*=thechapter.arabic*.,ref=thechapter.arabic*,
before={section*{hfil{Exercises -- thechapter}hfil}}%
addcontentsline{toc}{section}{Exercises -- thechapter}%
}
begin{document}
letoldref=ref
renewcommand{ref}[1]{oldref{#1} in page pageref{#1}}
chapter{title}
section{title}
begin{enumerate}
item   bla
begin{enumerate}
item   label{key1}
bla
end{enumerate}
end{enumerate}
begin{exercise}
item
begin{enumerate}
item   bla
begin{enumerate}
item   label{key}
bla
item   bla
end{enumerate}
item   bla
end{enumerate}
end{exercise}
Exercise ref{key}, ref{key1}.
end{document}
``````

This produces the following output.

What I want `ref` to produce for `exercise` is “1.1. 1.(a) in page 1” and for the first `enumerate` staff “1.(a) in page 1”. Of course both of them should be hyperlinks as they are now. How do I achieve this?

Get this bounty!!!