I have the following inline code:
$\texttt{TEST}(v *= 2, v += 2, v = 4)$
But when it is rendered, the plus is very far away from the equal sign. How can I overcome this problem and make LaTeX consider += as a single operator?
+
is a binary operator and =
is a binary relation. When TeX finds the sequence
v + = 2
it transforms it into
Ord Bin Rel Ord
but a Bin is not allowed before a Rel, so it's changed into an Ord.
Solutions:
\documentclass{article}
\newcommand{\pluseq}{\mathrel{+}=}
\newcommand{\asteq}{\mathrel{*}=}
\begin{document}
$\texttt{TEST}(v \asteq 2, v \pluseq 2, v = 4)$
\end{document}
or, manually,
\documentclass{article}
\begin{document}
$\texttt{TEST}(v \mathrel{*}= 2, v \mathrel{+}= 2, v = 4)$
\end{document}
These exploit the fact that TeX doesn't insert any space between two consecutive Rel symbols.
You can also define a macro that switches the behavior, so you can type the formulas more naturally:
\documentclass{article}
\newcommand{\switch}{%
\mathcode`+=\numexpr\mathcode`+ + "1000\relax % turn + into a relation
\mathcode`*=\numexpr\mathcode`* + "1000\relax
}
\begin{document}
$\switch\texttt{TEST}(v *= 2, v += 2, v = 4)$
$a+=b \quad \begingroup\switch a+=b\endgroup \quad a+=b$
\end{document}
I added a nonsense line to show that \switch
respects grouping. The scope of \switch
ends with the formula (or group) in which it's issued.
$\relpenalty-10000 a==b$\bye
and see; of course one could add a penalty in between to explicitly allow a line break.
\mathrel{+}=
inside my equations.
\newcommand{\pluseq}{\mathrel{+}=}
? Can you show an example of this failure? Maybe with a new question.
listings
(orverbatim
if all else fails)