9

I want to use hypertarget caption in hyperlink caption automatically.

Example:

\hypertarget{myTarget}{My Target}

See \hyperlink{myTarget}{\useMyTargetCaption}.

Wanted result:

My Target

See My Target.

1
  • Welcome to TeX.SX! You can have a look at our starter guide to familiarize yourself further with our format. Apr 1, 2014 at 6:34

1 Answer 1

13

You can redefine \hypertarget so that it defines a new command corresponding to its first argument:

\let\oldhypertarget\hypertarget
\renewcommand{\hypertarget}[2]{%
  \oldhypertarget{#1}{#2}%
    \protected@write\@mainaux{}{%
        \string\expandafter\string\gdef
          \string\csname\string\detokenize{#1}\string\endcsname{#2}%
    }%
  }

In this way, when you issue

\hypertarget{myTarget}{My Target}

this also saves a command named \myTarget in the .aux file.

Then we define a new command \myhyperlink that takes care of that:

\newcommand{\myhyperlink}[1]{%
  \hyperlink{#1}{\csname #1\endcsname}%
  }

When you issue

\myhyperlink{myTarget}

this results in

\hyperlink{myTarget}{\myTarget}

MWE:

\documentclass{article}

\usepackage[colorlinks]{hyperref}

\makeatletter
\let\oldhypertarget\hypertarget
\renewcommand{\hypertarget}[2]{%
  \oldhypertarget{#1}{#2}%
    \protected@write\@mainaux{}{%
        \string\expandafter\string\gdef
          \string\csname\string\detokenize{#1}\string\endcsname{#2}%
    }%
  }
\newcommand{\myhyperlink}[1]{%
  \hyperlink{#1}{\csname #1\endcsname}%
  }
\makeatother

\begin{document}

\hypertarget{myTarget}{My Target}

See \myhyperlink{myTarget}.

\end{document} 

Output:

enter image description here

If you want to customize it, you can change it, for example, to (requires xcolor package`):

\newcommand{\myhyperlink}[1]{%
  \hyperlink{#1}{\textcolor{cyan}{\textit{\csname #1\endcsname}}}%
  }

and the result will be:

enter image description here

9
  • Thank you. As in this case, how to add spaces to label's name?
    – Supert
    Apr 1, 2014 at 8:50
  • @Supert I misunderstood. Now the answer is completely different. Apr 1, 2014 at 9:13
  • Yes, but there is a bug: if you place link before target, link will be empty.
    – Supert
    Apr 1, 2014 at 9:34
  • As far as I can see, myLink is trying to call myTarget.csname before it is defined
    – Supert
    Apr 1, 2014 at 9:39
  • If we return back to your previous answer, how we can add spaces to label's name? Well, it is workaround, but it is better than disappearing ninja links.
    – Supert
    Apr 1, 2014 at 10:03

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.