Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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.

share|improve this question
    
Welcome to TeX.SX! You can have a look at our starter guide to familiarize yourself further with our format. –  karlkoeller Apr 1 at 6:34

1 Answer 1

up vote 6 down vote accepted

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

share|improve this answer
    
Thank you. As in this case, how to add spaces to label's name? –  Supert Apr 1 at 8:50
    
@Supert I misunderstood. Now the answer is completely different. –  karlkoeller Apr 1 at 9:13
    
Yes, but there is a bug: if you place link before target, link will be empty. –  Supert Apr 1 at 9:34
    
As far as I can see, myLink is trying to call myTarget.csname before it is defined –  Supert Apr 1 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 at 10:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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