I've created some custom commands in my document so that if I change the variable, all occurcences can be changed easily. However, some of my command variables are contained in the math environment ($$). I use them both in plain text and inside equations. When I use them within an equation, I get Missing $ inserted. [ $\mycommand], presumably due to the math mode value being nested inside math mode a second time. Here's an example:
\documentclass[a4paper,12pt]{article}
\usepackage{xspace}
\begin{document}
\newcommand{\mycommand}{$my_{command}$\xspace}
Here is my \mycommand working fine.
Here is my \mycommand not working in math mode:
$\mycommand$
\end{document}
Is there a workaround to this?


$...$and used in text should always be used inside$...$. That gives your document the proper semantics and eliminate the need for\xspacewhich should never be used. – daleif Jan 25 '23 at 10:50\foo{}. Using\xpsaceis a bad idea as it does not cover all corner cases. – daleif Jan 25 '23 at 13:52