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?

  • 1
    Untested: you can use \edef\WPpagequestion{...}. – Aditya Sep 17 '14 at 19:00
  • @DaveJarvis Why would you write {} in the middle? – Manuel Sep 17 '14 at 22:43
  • I thought that the url needed to be written without a space, thusly: \WPhomepagebase201545. However, that is a macro (that doesn't exist). I didn't think \WPhomepagebase 201545 would work, so I added the {}. – Dave Jarvis Sep 17 '14 at 23:47
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.

ConTeX expanded Macro

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

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

ConTeX 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

  • 2
    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
  • @Aditya True, I didn't thought of that (I thought of that, but not as a feature). That's a nice feature. – Manuel Sep 17 '14 at 19:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.