\newcommand, \begin{math} and \newglossaryentry

I have the following code snippet:

\newcommand{\jbv}[0]{j_{bv}}
\newcommand{\txtjbv}[0]{\begin{math}\jbv\end{math}}
\newglossaryentry{jbv}{name={\txtjbv}, sort={a03}, description={Bla}}


I get the following error:

    ! Undefined control sequence.
\in@ #1#2->\begingroup \def \in@@
##1#1{}\toks@ \expandafter {\in@@ #2{}{}#1...
l.27 ...3}, description={Bla}}


It seems that this is caused by name={\txtjbv} on the third line of the snippet, because it works when I just use name={jbv}.

How can I get those newcommands properly in order to use them inside my text, in equations and as the glossary name?

• Is this nesting really needed? Either use \ensuremath{\jbv}} or \glssetnoexpandfield{name} but I don't recommend this – user31729 Apr 18 '18 at 18:43
• See for example tex.stackexchange.com/a/259197/31729 – user31729 Apr 18 '18 at 18:45
• @ChristianHupfer The name field defaults to no expansion. It's the text field that's expanding and causing the problem, but I agree it's much simpler just to use name={\ensuremath{\jbv}}. – Nicola Talbot Apr 18 '18 at 19:42
• @ChristianHupfer Do you want to answer? – Nicola Talbot Apr 19 '18 at 10:56
• @ChristianHupfer Okay, done :-) – Nicola Talbot Apr 19 '18 at 12:16

The math environment, identified with \begin{math}...\end{math}, is fragile (but $...$ isn't) and so can break in an expandable context. By default, expansion is on for all fields except name, description, descriptionplural, symbol and symbolplural. (The exceptions are for backward-compatibility because early versions of the glossaries package had to write the name, description and symbol to the external glossary file, so those fields were sanitized instead of being expanded on definition.)

So in this case, \begin{math}...\end{math} doesn't get expanded when the name field is assigned, but it does get expanded when the other implicit fields (such as text) that take their default values from the name key are assigned.

As mentioned by Christian in the comments, it's much better to use \ensuremath in this situation. Although \ensuremath can cause problems in other contexts, it's the most convenient way of ensuring maths mode within glossary fields so that \gls can be used in either maths or text mode.

\documentclass{article}

\usepackage{glossaries}

\makeglossaries

\newcommand{\jbv}[0]{j_{bv}}
\newcommand{\txtjbv}[0]{\begin{math}\jbv\end{math}}
\newglossaryentry{jbv}{name={\ensuremath{\jbv}},sort={a03},description={Bla}}

\begin{document}
In text: $$\gls{jbv}$$. In an equation:
$$\gls{jbv}$$

In the glossary:
\printglossaries
\end{document}