[Tex/LaTex] Using hypertarget caption in hyperlink caption

hyperref

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.

Best Answer

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