My document have many fractions of the form m/n
. Now I want to convert all fractions from the form m/n into the form \dfrac{m}{n}.
I can't find a way to convert. The unique way is by hand.
\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\begin{document}
\[ m/n + p/q = 2/3. \]
I want
\[\dfrac{m}{n} + \dfrac{p}{q} = \dfrac{2}{3}.\]
\end{document}
Best Answer
Here's a LuaLaTeX-based solution. If you are forced to use pdfLaTeX you may be out of luck. Hopefully, though, the answer will still be useful to other readers.
A major issue with infix fraction notation, such as
a/b
and1/2
, is that by the time TeX has a chance to notice the presence of a/
symbol in the input stream, the material that's supposed to form the numerator is already gone; backspacing to recover the numerator would be very tedious (or maybe even impossible). A preprocessor-based approach seems more promising. Fortunately, LuaTeX provides theprocess_input_buffer
callback, which is very suitable for pre-processing.The following example code provides a Lua function that performs the infix-to-dfrac conversion. The only syntactic requirement is that characters in the numerator and denominators consist solely of alphabetic characters and arabic numerals. (No parentheses allowed) Whitespace to the immediate left or right of the
/
(slash) symbol is permitted.Given the replacement of
/
with\dfrac
, this Lua function should never be run on inline-math mode material, let alone text-mode material, lest it play havoc with any/
characters. The code therefore also provides two LaTeX macros --\ReplaceOn
and\ReplaceOff
-- which activate and deactivate the Lua function. I suggest you insert a\ReplaceOn
directive at the start of each group of equations that contain infix fractions and a\ReplaceOff
directive at the end of each such group.Addendum: To extend the scope of the Lua function to the entire document automatically, it's necessary to perform some tests to check if we're in a display-math environment, and to perform the infix-to-frac conversion only if that's the case. How to do this is shown in the following example. Six display math environments are recognized automatically (in addition to the "basic LaTeX"
\[
and\]
commands):equation
,align
,alignat
,flalign
,gather
, andmultline
. Both the "starred" and "regular" variants of these environments are handled.The requirements regarding input syntax are fairly mild. Expressions with
\[ ... \]
are permissible, as are all display math environments in which the opening and closing statements, such as\begin{equation}
or\end{align}
, are on lines by themselves.The code below also provides the macros
\ReplaceOff
and\ReplaceOn
, as it may be necessary to suspend operation of the Lua function "by hand", say, in case of averbatim
-like material that contains displaymath code.