4

So, I've got this command that I use to format variable names in my homework:

\newcommand*{\var}[1]{\ensuremath{\mathord{\mathtt{#1}}}}

The problem is that it doesn't handle subscripts smoothly. I end up typing this frequently:

\var{Something}_{\var{SomethingElese}}

Which is a bit cumbersome. Can I make it work with:

\var{Something_SomethingElse}

or at least:

\var{Something}_\var{SomethingElse}
1
  • Welcome to TeX.sx! Your post was migrated here from Stack Overflow. Please register on this site, too, and make sure that both accounts are associated with each other (by using the same OpenID), otherwise you won't be able to comment on or accept answers or edit your question.
    – Werner
    Commented Nov 30, 2012 at 15:03

3 Answers 3

5

You must enclose the subscript in a brace/group to indicate the scope it. Therefore, using

\newcommand*{\var}[1]{$\mathtt{#1}$}

is sufficient:

enter image description here

\documentclass{article}
\newcommand*{\var}[1]{$\mathtt{#1}$}
\begin{document}
\var{Something_{SomethingElse}}
\end{document}
1
  • 1
    You omitted a closing $. I think it's better to use ensuremath so that it works in both environments. But otherwise, great answer, thanks!
    – Murph
    Commented Nov 27, 2012 at 22:17
1

Just using the definition

\newcommand*\var[1]{\mathtt{#1}}

will allow you to blithely apply subscripts without braces as in $\var{XYZ}_\var{ABC}$. Placing the whole thing in \mathord has the effect of making the contents immune to font family changes, but if you don't have a good reason for wanting this, I question whether it's a priority over the ease of use you do request.

I also suggest you remove \ensuremath; for one, it breaks braceless subscripts. In general I feel that it is undesirable to hide the "mathiness" of a formula even if it saves a little writing when you can (sometimes! And not when you're using subscripts) avoid writing $...$. See this question for a discussion.

1

The trick for subscripts is to define \var in such a way, that it expands to a subformula. This is achieved by an additional pair of curly braces. I have removed \mathord, because it is not needed. \mathtt also puts its argument into a subformula and subformulas are already "mathord".

\documentclass{article}

\newcommand*{\var}[1]{{\ensuremath{\mathtt{#1}}}}

\begin{document}
Variable \var{foo} and as subscript for \var{bar}: $\var{bar}_\var{foo}$

Another example: $X_\var{foo}^\var{bar}$
\end{document}

Result

This works, because subscript and superscript do not look for arguments, but for a math atom, a subfomula in this case.

You must log in to answer this question.