I want to define a command called \ksp{} that looks like this:
\newcommand*{\ksp}{K_{sp}}
However, this function gives an error if it's not invoked in math mode. See example here.
\documentclass{article}
\newcommand*{\ksp}{K_{sp}}
\begin{document}
Determine the \ksp{} of xyz. This will give an error
\end{document}
So, I modified the command to be inline math mode.
\newcommand*{\ksp}{$K_{sp}$}
However, this new version of the command gives an error if I invoke the function while already in math mode. See example here.
\documentclass{article}
\newcommand*{\ksp}{$K_{sp}$}
\begin{document}
\begin{equation}
Determine the \ksp{} of xyz. will get an error.
\end{equation}
\end{document}
So, I made a newer version that tries to determine if we're already in math mode or not when the command is invoked. I pilfered this code from here
% Ksp
\newif\ifstartedinmathmode
\newcommand*{\ksp}{
\relax\ifmmode\startedinmathmodetrue\else\startedinmathmodefalse\fi
{\ifstartedinmathmode K_{sp}\else\hspace{0pt}$K_{sp}$\fi}
}
This command (above) works under both conditions. However, it introduces an extra "space" in front of (and maybe after) the Ksp. You can see this in the document below.
\documentclass{article}
% Ksp
\newif\ifstartedinmathmode
\newcommand*{\ksp}{
\relax\ifmmode\startedinmathmodetrue\else\startedinmathmodefalse\fi
{\ifstartedinmathmode K_{sp}\else$K_{sp}$\fi}
}
\begin{document}
\begin{enumerate}
\item Determine the $K_{sp}$ of blahblah. \% this is the normal way of writing the term.
\item Determine the \ksp{} of blahblah. \% this is with the conditional command and it has extra whitespace surrounding the term.
\end{enumerate}
\end{document}
Questions:
- any way to fix the spacing issue?
- should I be taking a completely different approach? I am simply trying to avoid typing some complicated formatting over and over again (Ksp is a simplification of the formatting that I'm actually trying to do, but it illustrates the point well enough).



Determine the $\ksp$ of xyz.It's as easy as that. – egreg Apr 07 '16 at 13:52{and}but simpler is use\ensuremath{K_{sp}}but better really is just useK_{sp}and mark up math explicitly as for all standard latex math commands like\alphaor\sum. – David Carlisle Apr 07 '16 at 13:53\ksp{}in text mode for code readability purposes. – A Feldman Apr 07 '16 at 15:25