# How to use normal label within a custom command for a definition of hypertarget?

I want to make a command that defines a \hypertarget with the target label (first argument of \hypertarget) by the contained \label and the target caption (second argument of \hypertarget) by its content.

\documentclass{article}

\usepackage{hyperref}
\newcommand\mytargetcommand[1]{?}

\begin{document}
\mytargetcommand{My content\label{tag}}
\ref{tag}
\end{document}


So this would output My content twice where the second references to the first.

• I think, you need a different strategy here
– user31729
May 31 '16 at 13:22
• @Christian Hupfer Yes, I thought I could use the the label redefinition but it did not work. Hope there is a way to do this as well. :) May 31 '16 at 13:24
• \ref{tag} will not give My content however!
– user31729
May 31 '16 at 13:29
• Perhaps you're looking rather for something like this: tex.stackexchange.com/a/271064/31729
– user31729
May 31 '16 at 13:33
• @Christian Hupfer No, I am really looking for a way to use the ordinary \label command while keeping the content and the label separate... \mytargetcommand{Text\label{tag}} -> \hypertarget{tag}{Text} May 31 '16 at 13:41

Perhaps there are better ways to split the My content\label{tag} stuff such that \hypertarget does not choke on \label: Use \def\splitcmd#1\label#2 and a similar command that splits the with undelimited arguments (actually, \label is the argument delimiter here).

This uses a dummy counter and to refer to the text, use \nameref instead.

\documentclass{article}

\usepackage{hyperref}
\makeatletter
% Two helper commands --> get the text before \label
\def\splitcmd#1\label#2{%
#1%
}
% Get the label tag
\def\splitcmdother#1\label#2{%
#2%
}

\newcounter{localtagcntr}

\newcommand\mytargetcommand[1]{%
\edef\local@tag{\splitcmdother#1}%
\edef\my@text{\splitcmd#1}%
\refstepcounter{localtagcntr}%
\def\@currentlabelname{\my@text}% Change the label content name
\label{\local@tag}% Set the label
\hypertarget{\local@tag}{\my@text}%
}

\makeatother
\begin{document}
Foostuff
\clearpage
\mytargetcommand{My content\label{tag}}
\ref{tag}

\clearpage

• Thanks. Okay, so one problem is that it depends on where the \label is inserted. If it is inserted not at the end of the argument of mytargetcommand it will not work. Also it does not work when mytargetcommand is used in, for example, labels of descriptions. These are unfortunately quite some drawback. May 31 '16 at 14:20
• It is still puzzling to me why one cannot just get a handle to the label in the current scope of the \mytargetcommand. May 31 '16 at 14:21