The trick is to make the comma math active
This way, the command \MakeCommaBreakable
can properly go inside the formula, so the effect of math activation is confined.
\documentclass{article}
\usepackage{amsmath}
\newcommand{\MakeCommaBreakable}{%
\mathchardef\normalcomma=\mathcode`,
\begingroup\lccode`~=`,\lowercase{\endgroup\let~}\BreakableComma
\mathcode`,="8000
}
\newcommand{\BreakableComma}{%
\normalcomma\mspace{0mu plus 6mu}\penalty0
}
\begin{document}
$\MakeCommaBreakable xxx, xxx, xxx, xxx, xxx, xxx, xxx, xxx, xxx, xxx,
xxx, xxx, xxx, xxx, xxx, xxx, xxx, xxx, xxx, xxx, xxx, xxx, xxx, xxx,
xxx, xxx, xxx, xxx, xxx, xxx, xxx, xxx, xxx$
\end{document}
What's the problem with your code?
First, even if it's fixed, you're making the comma active at the outer level, which isn't a good thing. But this is not the main reason: when TeX reads the definition of \MakeBreakableComma
, the replacement text is tokenized and ,
has category code 12, so it cannot follow \def
.
With the \lowercase
trick, what TeX sees is an active comma, because \lowercase
doesn't change category codes.
You might make the comma active instead of just math active, but I wouldn't recommend it, because if it's active you cannot use it in option specifications, for instance. A math active character instead takes on the “active dress” only when TeX is examining math codes.
For completeness, you might also place \MakeBreakableComma
at the outer level, and all commas in math formulas would become breakable: definitely not recommended, because you don't want to break something like f(x,y)
.