3

I want to define a \newcommand that produces the same font in both text and math modes. For example,

\newcommand{\abc}[1]{???#1}

Then

\abc{varName} is blah blah blah

$ \abc{varName} = 4 $

I want varName to have the same font in both cases, ideally the same as \mathsf font.

2 Answers 2

4

Here's something that is effectively the same as using \ensuremath: Just ask if LaTeX is in math - mode (\ifmmode) and then use \mathsf or switch temporarily to math-mode and apply \mathsf then.

By the way \textsf works both in math and text mode anyway.

\documentclass{article}


\newcommand{\abc}[1]{%
  \ifmmode
  \mathsf{#1}%
  \else
  $\mathsf{#1}$%
  \fi
}

\begin{document}

\LARGE 
\abc{varName} is blah blah blah

$ \abc{varName} = 4 $

\begin{equation}
\abc{Hello} = 7
\end{equation}

\end{document}

enter image description here

1
  • 1
    Awesome, did not know about \ifmmode
    – Arash
    Commented Jan 6, 2016 at 20:07
4

The \ensuremath command allows things from math mode to be used in both text mode and math mode. Thus, you can write your command like this.

\newcommand{\abc}[1]{\ensuremath{\mathsf{#1}}}
3
  • What document class or packages are you using? Commented Jan 6, 2016 at 21:29
  • @Z0lenDer: \ensuremath is a LaTeX core command, it should work always (unless some package disables it ;-))
    – user31729
    Commented Jan 6, 2016 at 22:58
  • Checked again and it worked, probably did not see the font clearly the first time! Anyway thanks to both of you Arun and Christian :)
    – Arash
    Commented Jan 7, 2016 at 2:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .