29

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?

rendered

  • Also, maybe you want to use some sort of code environment and font (fixed size) to insert code into your PDF's, instead of a math environment, such as listings (or verbatim if all else fails) – Thomas Jul 1 '13 at 22:46
40

+ 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.

enter image description here

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.

enter image description here

  • Very good explanation. – Mikaël Mayer Jul 1 '13 at 13:04
  • Can there be a libe break between two rel symbols? – Aditya Jul 1 '13 at 17:48
  • 1
    @Aditya No, only after a relation symbol; consecutive ones are treated as a unit. Try $\relpenalty-10000 a==b$\bye and see; of course one could add a penalty in between to explicitly allow a line break. – egreg Jul 1 '13 at 17:54
  • Good. Curiously, the newcommand doesn't work for me. I had to type \mathrel{+}= inside my equations. – erickrf Apr 30 '14 at 3:41
  • @erickrf Do you refer to \newcommand{\pluseq}{\mathrel{+}=}? Can you show an example of this failure? Maybe with a new question. – egreg Apr 30 '14 at 9:06
13

enter image description here

$\texttt{TEST}(v \mathrel{{*}{=}} 2, v \mathrel{{+}{=}} 2, v = 4)$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.