19

I'm having a similar problem as described here: How to use \newcommand for \href?

However, I want to specify an URL with an # sign in it. I know that I should escape the # by \#, but as we have many links containing the #, it may be nice to be able to copy and paste the URL directly into the LaTeX code.

My current solution looks like this:

\documentclass{article}
\usepackage{hyperref}
\usepackage{ifthen}

\newcommand*{\myhref}[2][]{\href{http://myserver/#2}%
                          {\ifthenelse{\equal{#1}{}}{#2}{#1}}}

\begin{document}
\myhref{somewhere} % WORKS
\myhref[LINK TEXT]{somewhere} % WORKS

\myhref{somewhere\#anchor} % WORKS
\myhref[LINK TEXT]{somewhere\#anchor} % WORKS

\myhref{somewhere/#anchor} % WORKS NOT - BUT I WANT IT TO WORK !!!
\myhref[LINK TEXT]{somewhere#anchor} % WORKS NOT - BUT I WANT IT TO WORK !!!
\end{document}

Is there a way to automatically escape the # character in the argument to \myhref?

1 Answer 1

18

You have to absorb the # as a "normal character"

\makeatletter
\newcommand*{\myhref}{\begingroup\@makeother\#\@myhref}
\newcommand*{\@myhref}[2][]{%
  \href{http://myserver/#2}{\ifthenelse{\equal{#1}{}}{#2}{#1}}%
  \endgroup}
\makeatother

The package hyperref does a good job with these strange characters, but here the problem is that when you say \myhref{somewhere#anchor} the # has already been absorbed by TeX with category code 6, which breaks \href.

Here we tell LaTeX to open a group in which # will be considered as a normal character and only after this we absorb the arguments.

3
  • Thank you very much! I have experimented with \catcode'\#=\somenumber a bit but I think I have tried to make # a letter (catcode 11). Nov 18, 2011 at 17:26
  • @WolfgangUlmer That would break the use of \#anchor which would become a unique control sequence.
    – egreg
    Nov 18, 2011 at 17:37
  • Yes. That has been my problem. I could make one of the two variants work but not both. Your solution works with both syntax variants. Nov 18, 2011 at 17:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .