Can I write one macro that works conditioned on it is in math formula or not?
For example, assume I have an algorithm named "alg1" and I want the name to be in \mathsf so normally I define two macros as follows: 1) \def\a{\mathsf{alg1}} and 2) \def\b{$\mathsf{alg1}$}. One is for when I want to use "alg1" name in a math formula and the other one is for when I want to use the name in a text environment.
So is there a way to write one macro for both applications?


\ensuremath. I don't. If in text-mode consecutive "\ensuremath-commands" occur, this will not be treated as a single math-formula but will be treated as different adjoining formulas. This will not necessarily look good. You need to have TeX enter math-mode, then to process subsequent "\ensuremath-commands", then to leave math-mode. But this way\ensuremathis obsolete. – Ulrich Diez Jan 04 '22 at 18:07