Defining a phrase containing math and text usable in both math and text mode
The only thing to do is to say
\newcommand{\Constraint}{%
\relax\ifmmode
x\neq 0 \text{ and } x\neq 1
\else
$x\neq 0$ and $x\neq 1$
\fi}
If one has loaded babel
, then \textormath
could be used instead of the conditional, but it's the same concept.
Why not \ensuremath{x\neq 0 \text{ and } x\neq1}
?
First of all because it uses \ensuremath
. :) Seriously, because the only break points would be after the relation symbols \neq
, which is where the break is less preferable. The problem is, in fact, that \text
creates a box.
Add ties and \nobreak
where it seems suitable. And be careful in defining such abbreviations (that will be mysterious when, a couple of months from now, you'll be again reading the document).
How to avoid repeating the text? My solution would be to spell the text without resorting to mysterious abbreviations. Or, if you insist,
\newcommand{\ensuretext}[1]{\ifmmode\text{#1}\else#1\fi}
\newcommand{\Constraint}{%
\ensuremath{x\neq 0}\ensuretext{ and }\ensuremath{x \neq 1}}
which is worse than specifying the text twice.
Edit: Next try: take the spaces outside \text
\newcommand\Space{\penalty\z@\hspace{1ex}}
\newcommand{\Constraint}{\ensuremath{x \neq 0\Space\text{and}\Space x \neq -1}}
I'd have expected there to be a breakable space for math mode already, so maybe I'm still getting something wrong...