4

Background

Would like to define a base URL that can be reused by other macros.

Problem

Using the \goto macro requires a fully expanded URL.

Minimum Working Example

Here's code that illustrates the problem:

\setupinteraction[state=start]

\def\WPhomepagebase{http://tex.stackexchange.com/questions/}
\def\WPpagequestion{\WPhomepagebase{}201545}
%\def\WPpagequestion{http://tex.stackexchange.com/questions/201545}

\def\href#1#2{%
  \goto{#1}[url(#2)]%
}

\starttext
  \href{TeX StackExchange}{\WPpagequestion}
\stoptext

If the code is changed as follows:

%\def\WPhomepagebase{http://tex.stackexchange.com/questions/}
%\def\WPpagequestion{\WPhomepagebase{}201545}
\def\WPpagequestion{http://tex.stackexchange.com/questions/201545}

Then the document produces the correct hyperlink.

Question

How do you use \goto within a custom macro, as shown in the example code, such that the URL can contain other macros?

Dave Jarvis
  • 11,809

1 Answers1

4

In every case below, remove the extraneous braces:

\def\WPpagequestion{\WPhomepagebase 201545}

to prevent those braces from being included in the URL.

Plain TeX

A Plain TeX way for solving this would be:

\def\href#1#2{%
  \begingroup\def\x{\endgroup\goto{#1}[url(}%
  \expandafter\x#2)]%
}

or the more drastic:

\def\href#1#2{%
  \begingroup\edef\x{\endgroup\noexpand\goto{#1}[url(#2)]}\x
}

where \noexpand is possibly redundant, if \goto is a protected macro.

ConTeXt expanded Macro

As per the comments, in ConTeXt, the \expanded macro can be used:

\define[2]\href{%
  \expanded{%
    \goto{#1}[url(#2)]%
  }%
}

ConTeXt edef Macro

This can be simplified further using \edef:

\def\WPhomepagebase{https://tex.stackexchange.com/questions/}
\edef\WPpagequestion{\WPhomepagebase 201545}

\define[2]\href{%
  \goto{#1}[url(#2)]%
}

See Also

Dave Jarvis
  • 11,809
egreg
  • 1,121,712
  • 3
    ConTeXt has a \expanded command which can be used here, i.e. the \hrefcommand could be defined as \define[2]\href{\expanded{\goto{#1}[url(#2)]}}. – Wolfgang Schuster Sep 17 '14 at 10:46
  • @Metafox The definition is like \def\expanded#1{\xdef\tmp{\noexpand#1}\tmp}. What is the purpose of \noexpand there? – Manuel Sep 17 '14 at 18:37
  • @Manuel, without the noexpand, the goto in the above example will be expanded. – Aditya Sep 17 '14 at 18:58