# Define a custom command with name, label and linkable

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

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


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.comApr 4 '11 at 19:53

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

This question is a good candidate for tex.stackexchange.com –  Yasir Arsanukaev Mar 20 '11 at 12:34
This is clearly a question about programming in latex, which makes it on-topic either here or on tex.se. You might be better choosing the specialty site in the future simply because you get a specialized audience, but the question is OK as it is. –  dmckee Mar 20 '11 at 15:05
shall I repeat the question there or is there a way to move questions around sites? –  Fuligginoso Mar 20 '11 at 19:17
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

The commands could be defined like this:

\makeatletter
\newcommand{\mycom}[2]{\hypertarget{#1}{#2}\global\@namedef{mycom@#1}{#2}}
\@ifundefined{mycom@#1}{\textbf{??}\@latex@warning{Reference #1' on page \thepage \space undefined}}%
}
\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}}
`
-