I have the following situation: I have to use the ocgcolorlinks
option in hyperref
, so that links are not broken. So I had the idea to set each char as a link with \href
. After putting some code together and understanding only half of what I was doing, I arrived with a solution that worked: both the linking as well as issues with escaping the special characters in the URLs with catcode.
Unfortunately, the intention was to mainly use it in the bibliography, and when backref
and pagebackref
is used in hyperref
, some macros or something are redefined so that the escaping again does not work there. I was not able to fix this.
In the following you find a minimal example using my ugly hack:
\documentclass{report}
\usepackage[T1]{fontenc}
\usepackage[ocgcolorlinks,breaklinks=true,backref=page,pagebackref=true]{hyperref}
\usepackage{url}
%adapted from http://tex-and-stuff.blogspot.com/2011/03/counting-number-of-characters-in-tex_10.html
\newcommand{\targetlink}{}
\def\gobblechar{\let\char= }
\newcount\charcount
\def\countunlessnil{%
\ifx\char\nil \let\next=\relax%
\else%
\let\next=\auxcountchar%
\advance\charcount by 1%
\fi\next
}%
\def\assignthencheck{\afterassignment\checknil\gobblechar}
\def\checknil{%
\ifx\char\nil%
\let\next=\relax%
\else%
\oldhref{\targetlink}{\char}\allowbreak\let\next=\assignthencheck% %%this is the place where each char is processed
\fi%
\next%
}
\let\oldhref\href%
%inspired of http://tex.stackexchange.com/questions/20890/define-an-escape-underscore-environment and https://texfaq.org/FAQ-actinarg
\def\href#1{
\renewcommand{\targetlink}{#1}%
\begingroup
\catcode`\_=12
\catcode`\&=12
\catcode`\~=12
\xhref
}
\def\xhref#1{
\assignthencheck #1\nil%
\endgroup
}%
\def\url{%
\begingroup
\catcode`\_=12
\catcode`\&=12
\catcode`\~=12
\xurl
}%
\def\xurl#1{
\renewcommand{\targetlink}{#1}%
\assignthencheck #1\nil%
\endgroup
}%
\begin{document}
\url{http://a_b/c&d/~e}
\href{http://a_b/c&d/~e}{http://a_b/c&d/~e}
$\begin{array}{cc}s&ep\end{array}up_down$no~tilde
\bibliographystyle{diss1}
\begin{thebibliography}{1}
\bibitem[t]{test}
\newblock
\url{http://a_b/c&d/~e} %error here
\href{http://a_b/c&d/~e}{http://a_b/c&d/~e} %error here
$\begin{array}{cc}s&ep\end{array}up_down$no~tilde
\end{thebibliography}
\end{document}
The output should then be two times:
http://a_b/c&d/~e http://a_b/c&d/~e s epdownno tilde
Any idea what is happening and how I can fix it? Note that escaping the characters in the source in not really an option since I get it from a database and it would also set the links incorrectly.
Any other suggestions for cleaning the code or inserting \allowbreak
only at non-letters/spaces are also welcome.