Knowledge package coloring

colorhyperrefmath-mode

I am having a somewhat complex issue with the knowledge package. A MWE is the following:

\documentclass{article}

\usepackage{xcolor}

\usepackage{hyperref}
\usepackage{cleveref}
\usepackage{knowledge}

\hypersetup{ % Set up hyperref options
    colorlinks=true,
}

\knowledgestyle{no}{color=.}

\knowledgedirective*{automatic in command}{autoref,style=no,intro style=no}

\knowledgenewcommand{\foo}{\cmdkl{foo}}

% Colors in math mode, with correct spacing
% https://tex.stackexchange.com/questions/21598/how-to-color-math-symbols

\makeatletter

\def\mathcolor#1#{\@mathcolor{#1}}
\def\@mathcolor#1#2#3{%
    \protect\leavevmode
    \begingroup
    \color#1{#2}#3%
  \endgroup
}

\makeatother

\newcommand{\targetcolor}[1]{\mathcolor{green}{#1}}

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

  \Cref{sec:sec} is a section
  \[\intro*\foo\]
  \[\foo\]
  \[\targetcolor{\foo}\]

\end{document}

First, I’d still like to have internal links – such as the section reference – colored. So AFAIK I have to set colorlinks=true.

Now the issue is that the knowledge package does a lot of linking. The main use I’d like to have for this is to have all notations (such as foo here) refer to their definition, so that people can go look them up if they are unsure of their meaning. So far, so good.

I definitely do not want to have all those colored, because that would turn most of my mathematics into the link color – not very informative. Now knowledge provides the knowledgestyle command to give a specific color to each knowledge command. So I could just put black in there, so that foo is printed in black.

Now the issue is that later on I want to have different parts of equations colored – I’m doing programming languages theory, that’s basically syntax highlighting. So I define the targetcolor macro, and use it. But then this clashes with the two former: If I set the knowledgestyle to black, I lose because foo is black instead of green. If I do not set knowledgestyle, then the link color wins again and foo turns red.

A solution would be to deactivate link colors in math environments. But I do not know how to do that. I searched around and found AtBeginEnvironment, but I am not an expert enough to understand how to use it with mathematical environments (are these actually evene environments?).

Best Answer

You can try \everydisplay{\hypersetup{allcolors=.}} and \everymath{\hypersetup{allcolors=.}}. Then hyperref will pick up the current color for the links. (Completly disabling the coloring doesn't work, this needs the new hyperref driver from pdfmanagement-testphase).

Be aware that other packages or code can overwrite this.