6

I'd like to create a command with the following features:

\newcommand{\mycom}[2]{...}
\newcommand{\linktomycom}[1]{...}

In the doc body:

\mycom{firstitem}{This is the first item}

and later:

\linktomycom{firstitem}

Which would be equivalent to:

\hyperref[firstitem]{This is the first item}

and link to the position where I wrote \mycom.

...

I played around with phantomsec, but it seems to miss a naming feature. Thanks for any hint.

migrated from stackoverflow.com Apr 4 '11 at 19:53

This question came from our site for professional and enthusiast programmers.

  • Why don't you use \hyperlink and \hypertarget? – Gonzalo Medina Apr 4 '11 at 21:29
  • Thanks Gonzalo, I was missing these two commands, which bring the question a step further. There is still the problem: if I define \hyperlink{label}{my nice caption} I'd like to be able to write something like: \hypertarget{label} which should then be rendered as a clickable "my nice caption" this is not possible directly, as the caption field for \hyperlink is mandatory – Fuligginoso Apr 5 '11 at 11:44
  • (I switched hyperlink and hypertarget in the comment above) – Fuligginoso Apr 5 '11 at 11:56
3

The commands could be defined like this:

\makeatletter
\newcommand{\mycom}[2]{\hypertarget{#1}{#2}\global\@namedef{mycom@#1}{#2}}
\newcommand{\linktomycom}[1]{%
\@ifundefined{mycom@#1}{\textbf{??}\@latex@warning{Reference `#1' on page \thepage \space undefined}}%
{\hyperlink{#1}{\@nameuse{mycom@#1}}}%
}
\makeatother

\mycom{...}{...} creates a target named like the first argument with the text of the second argument and saves the caption in the macro \mycom@<first argument>.

\linktomycom{...} checks if \mycom@<first argument> is defined - if it isn't, two question marks and a LaTeX warning are produced, otherwise, a link to the specified target with the previously saved text is generated.

(The definitions are enclosed in \makeatletter ... \makeatother because internal LaTeX macros with an @ in their name are used.)

EDIT:

I couldn't find out if you want the \mycom command to produce a visible caption or just an (invisible) anchor - if you want the latter, you must define a target with an empty text:

\newcommand{\mycom}[2]{\hypertarget{#1}{}\@namedef{mycom@#1}{#2}}

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.