6

First, apologies for my lack of knowledge in this matter. I am trying the following code without really understanding every bit and piece of it.

Anyway, can anyone help me find what is wrong with the following code?

\def\pm #1#2{\@bsphack
\newcommand{\currentValue}{\ref{#1}}
  \protected@write\@auxout{}%
  {\string\newlabel{test\currentValue}{{#2}{\thepage}}}%
\@esphack}

My intentions? To define a \pm command that takes two arguments. The first argument needs to be used as a reference itself in order to obtain another variable: \currentValue. Then, this variable (\currentValue) is appended to some other text ('test') in order to create a new label.

Things look good, but for some reason, when the final label is created, an \hbox {} is appended to the end of the test\currentValue label.

Any idea what the problem is? Or how can I achieve my goal, if not in this manner?

1
  • 3
    \ref{key} is a command to print something. If can contain boxes or font commands. It is normally not suitable as part of the key of a label. You could try the zref package. With it you can define reference commands which gives back "pure" values. Commented Jun 19, 2012 at 13:23

1 Answer 1

7

You'd obtain the same without the \newcommand{\currentValue}{\ref{#1}}: your code is equivalent to

\def\pm #1#2{\@bsphack
  \protected@write\@auxout{}%
  {\string\newlabel{test\ref{#1}}{{#2}{\thepage}}}%
\@esphack}

because the expansion of \currentValue would be exactly \ref{#1} (with the actual argument to \pm in place of #1).

Here is the problem: \protected@write is unable to get the value of \ref{#1}, because this requires performing assignments which are never performed in a write operation.

You may have better luck with

\usepackage{refcount}
\def\pm #1#2{\@bsphack
  \protected@write\@auxout{}%
  {\string\newlabel{test\getrefnumber{#1}}{{#2}{\thepage}}}%
\@esphack}

but it's unclear what you want to achieve here, because you'll need to know the value of \ref{foo} in order to refer to the label generated by

\pm{foo}{bar}

(assuming you have a \label{foo} somewhere). So the generate label can be test1 if \ref{foo} gives "1", but when \ref{foo} changes also the generated label will change.

Note \pm is a command of the LaTeX kernel, redefine it at your own risk.

1
  • 1
    Brilliant! Many thanks, it works. \getrefnumberis what I needed, instead of \ref. Also, thanks for noting that \pmis already a command of the LaTeX kernel.
    – nzo
    Commented Jun 19, 2012 at 13:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .