2

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?

CarLaTeX
  • 62,716
mike
  • 35
  • 4
  • 3
    Don't. You gain nothing and lose much. – egreg Jan 03 '22 at 18:02
  • @egreg sorry , could you explain why it is a bad practice ? – mike Jan 03 '22 at 18:10
  • I went through similar thinking when I started with LaTeX as well: When not to use \ensuremath for math macro? – Peter Grill Jan 03 '22 at 19:12
  • See, besides the link posted by Peter, https://tex.stackexchange.com/a/35877/4427 https://tex.stackexchange.com/a/444671/4427 https://tex.stackexchange.com/a/289064/4427 – egreg Jan 03 '22 at 20:46
  • People recommand \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 \ensuremath is obsolete. – Ulrich Diez Jan 04 '22 at 18:07

1 Answers1

6

Use \ensuremath:

\documentclass[border=3.141592]{standalone}

\newcommand{\HT}{\ensuremath{\mathcal{H}} } \begin{document} See \HT and $\HT$ \end{document}

enter image description here

Addendum: You may be interested in the following version in which \HT enabled by xspace package:

\documentclass[border=3.141592]{standalone}
\usepackage{xspace}
\newcommand{\HT}{\ensuremath{\mathcal{H}}\xspace}

\begin{document} See \HT and $\HT$, and when at of the sentence is \HT. \end{document}

enter image description here

Zarko
  • 296,517