TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


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


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


or at least:

share|improve this question

migrated from stackoverflow.com Nov 30 '12 at 11:55

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

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 Nov 30 '12 at 15:03
up vote 5 down vote accepted

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


is sufficient:

enter image description here

share|improve this answer
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 Nov 27 '12 at 22:17

Just using the definition


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.

share|improve this answer

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".



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

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


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

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.