Using $\frac{x + 5}{y - 4}$
can make equations very long and difficult to read. I'd prefer to be able to write $(x + 5)/(y - 4)$
and have it interpreted as $\frac{x + 5}{y - 4}$
. How could I write a command that does this?
[Tex/LaTex] How to use a forward slash to display a fraction
fractionsmacrosmath-mode
Best Answer
Here's a LuaLaTeX-based solution. It consists of two LaTeX macros, called
\InlineToDispOn
and\InlineToDispOff
, and a Lua function calledinline_to_disp
. When activated via\InlineToDispOn
, the Lua function scans all lines of input and replaces all instances of(...)/(...)
with\frac{...}{...}
. (The parentheses that encase the numerator and denominator terms are stripped off.)Some additional comments:
Use the macro
\InlineToDispOff
to deactivate the Lua function. This may be needed if your document has passages which much be reproduced verbatim.Nested matching parentheses in the numerator or denominator are ok, but only the outermost ones are processed. Hence,
(2(x+5))/(y-4)
will be transformed to\frac{2(x+5)}{y-4}
.Whitespace to the left and right of the
/
division symbol is allowed.Per your write-up, the replacement operation requires both the numerator and denominator to be encased in pairs of matching parentheses.
By design, the Lua function
inline_to_disp
does not operate on expressions such asx/y
,(a)/b
, orc/(d)
.If you have an expression of the form
(x+5)/(y-4)
but do not want it to be changed to\frac{x+5}{y-4}
, change it to, say,(x+5){}/(y-4)
. The empty math group,{}
, will assure that thegsub
function insideinline_to_disp
does not perform a successful match.Any number of instances of
(...)/(...)
may occur on a given input line. (See below for examples.)No input sanity checking of any kind is performed.
If the numerator and denominator terms are not syntactically valid from a LaTeX point of view and/or if the parentheses that encase the numerator and denominator terms are not matched, Latex will generate various mysterious warning and error messages.
The Lua function also doesn't check whether
(...)/(...)
occurs in (display or inline) math mode; if it occurs in text mode, Latex will crash with a comment that, you guessed it,\frac
is not allowed to occur in text mode. This is, I trust, not much of a constraint since you're looking, in part, to replace various existing\frac
expressions.In the following screenshot, the upper row is typeset in
\textstyle
, while the lower one is typeset in\displaystyle
: