[Tex/LaTex] Making aliases for variables

aliasmacrosmath-modepunctuationspacing

I'm trying to figure out how best to define an alias. I have some moderately complicated variable names, such as $p^{i,j}_{t}$, and having to type them over and over again is a pain. More importantly, if I decide later to change my naming convention, I'd have to go back and search replace in my whole document, which seems ridiculous. I've tried to use this method:

\newcommand{\varn}{$p^{i,j}_{t}$}

but this method is not powerful enough. First of all, I cannot use it in Math mode, and would have to define another command

\newcommand{\mathvarn}{p^{i,j}_{t}}

which seems redundant.

Second of all, latex doesn't know that it's supposed to insert a whitespace after I use the command in a text environment. If I force a whitespace in the command, I cannot use the command just before punctuation like full stop, or comma.

Any suggestions? Thank you!

Best Answer

You can use \ensuremath Running for cover, egreg will come soon.

\documentclass{article}
\newcommand*{\varn}{\ensuremath{p^{i,j}_{t}}}

\begin{document}
\varn  \qquad    $\varn$

Here is how \varn{} is used in text again \varn.

\end{document}

Fir the second part, you may insert an empty atom {} after \varn like \varn{} when you need a space. This is the usual behaviour. Thre is also xspace package, but it may fail some times.

\documentclass{article}
\usepackage{xspace}
\newcommand*{\varn}{\ensuremath{p^{i,j}_{t}}\xspace}
\begin{document}
\varn  \qquad $\varn$

Here is how \varn is used in text again \varn.

\end{document}

enter image description here

As noted by egreg, it won't take much work to write $\varn$ over \varn. It is also more symatec for you identify math code. So better define \newcommand*{\varn}{p^{i,j}_{t}} and use $\varn$.

Related Question