Parenthesise math expression if it contains operator
Here, I search for +
, -
, \bullet
, and \cdot
, but you can add more operators to the \setsepchar
list.
Also, if the operator is leading, such as -3
, I do not add parens. You could change that by commenting the line \ignoreemptyitems
.
EDITED to workaround a strange error when \sim
appears by itself as an argument to \inlinefrac
.
\documentclass{article}
\usepackage{listofitems}
\newcommand\inlinefrac[2]{
\setsepchar{+||-||\bullet||\cdot||\oplus}
\ignoreemptyitems
\readlist*\xator{ #1}
\ifnum\listlen\xator[]>1\relax(#1)\else{#1}\fi
/
\readlist*\xator{ #2}
\ifnum\listlen\xator[]>1\relax(#2)\else{#2}\fi
}
\begin{document}
\[
\frac{2}{3}\quad\let\frac\inlinefrac\frac{2}{3}
\]
\[
\frac{2}{-3}\quad\let\frac\inlinefrac\frac{2}{-3}
\]
\[
\frac{2+x}{3}\quad\let\frac\inlinefrac\frac{2+x}{3}
\]
\[
\frac{2\bullet x}{3\cdot y}\quad\inlinefrac{2\bullet x}{3\cdot y}
\]
\centering$\inlinefrac{M\oplus N}{\sim}$
\end{document}
I propose an \ifrac
command. If given with *
it will call \inlinefrac
, but it will also obey the setting done by \fractionsinline
(local setting).
This way it's easy to switch from one form to the other, by adding or removing *
. You can also use \inlinefrac
directly.
Symbols that trigger the parentheses need not be the same in the numerator and the denominator: multiplication symbols should trigger parentheses in the denominator only.
\documentclass{article}
\usepackage{amsmath}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\ifrac}{smm}
{
\IfBooleanTF { #1 }
{ \inlinefrac { #2 } { #3 } }
{
\bool_if:NTF \l_bubaya_frac_inline_bool
{
\inlinefrac { #2 } { #3 }
}
{
\frac { #2 } { #3 }
}
}
}
\bool_new:N \l_bubaya_frac_inline_bool
% extend the regex at will; \+ and \- stand for + and -,
% \c{command name} for a control sequence
\regex_const:Nn \c_bubaya_frac_num_regex { \+ | \- | \c{sin} | \c{cos} }
\regex_const:Nn \c_bubaya_frac_den_regex { \c{cdot} | \c{times} | \c{bullet} }
\NewDocumentCommand{\fractionsinline}{}
{
\bool_set_true:N \l_bubaya_frac_inline_bool
}
\NewDocumentCommand{\inlinefrac}{mm}
{
\regex_match:NnTF \c_bubaya_frac_num_regex { #1 } { (#1) } { #1 }
/
\regex_match:NnTF \c_bubaya_frac_num_regex { #2 }
{
(#2)
}
{
\regex_match:NnTF \c_bubaya_frac_den_regex { #2 } { (#2) } { #2 }
}
}
\ExplSyntaxOff
\begin{document}
\begin{gather*}
\ifrac{2}{3}\qquad\ifrac*{2}{3}
\\
\ifrac{2}{-3}\qquad\ifrac*{2}{-3}
\\
\fractionsinline
\ifrac{2}{-3}\qquad\ifrac{2}{-3}
\\
\inlinefrac{2+x}{3}
\\
\ifrac{\sin x}{x}\qquad\ifrac*{\sin x}{x}
\\
\end{gather*}
\fractionsinline
\begin{gather*}
\ifrac{2+x}{3}
\\
\ifrac{2\bullet x}{3\cdot y}
\\
\ifrac{\sin x}{x}
\end{gather*}
\end{document}