[Tex/LaTex] How to replace all “slash” division expressions with \frac{}{}

fractionsmath-mode

Is there a way to autoreplace .../... with \frac{...}{...}?

For example, 143/23 should be rendered as \frac{143}{23}

Best Answer

Here's a LuaLaTeX-based solution. It works for all fractional expressions where both the numerator and the denominator contain only (one or more) digits, and it works both in inline-math and display-math modes. In order for \frac to work, the fractional terms must be in math-mode material. Only fractional expressions with digits are processed; expressions such as a/b will not be modified.

If you want "large" fractions throughout the document, be sure to load the amsmath package and change frac to dfrac in the Lua function below.

In case you're curious: The lua function replace_slash uses so-called captures to identify the numerator and denominator terms. The lua function is assigned to the process_input_buffer callback. This means that the function operates on the input before TeX starts its own processing. Thus, TeX's "eyes" will never even see an expression such as $1/2$; instead, they'll only get to see the expression $\frac{1}{2}$.

(Addendum 9 Nov 2015: Generalized the Lua code so that (i) signed integers (positive or negative) and (ii) any whitespace in the input are handled correctly.)

enter image description here

% !TEX TS-program = lualatex
\documentclass{article}

\usepackage{luacode} 

\begin{luacode}
function replace_slash ( line )
   return string.gsub ( line, "([%+%-]?%d+)%s-/%s-([%+%-]?%d+)", "\\frac{%1}{%2}" )
end
luatexbase.add_to_callback ( "process_input_buffer", replace_slash , "replace_slash" )
\end{luacode}

\begin{document}

How do we know that $55/110=1/2$?

\bigskip
$\displaystyle 55/110 = 1/2 $

\bigskip
Not modified: $a/(b+c)$, $x/y$, $2/x$
\end{document}

Addendum: Allowing an optional factorial symbol, viz., !, in the numerator and/or denominator would be very easy: In the Lua function, simply replace the search string

   "([%+%-]?%d+)%s-/%s-([%+%-]?%d+)"

with

   "([%+%-]?%d+!?)%s-/%s-([%+%-]?%d+!?)"

In Lua's pattern matching jargon, %s- means "0 or more occurrences of whitespace", and the !? substring means "0 or 1 instance of !". With this modification, $3! / 2!$ will be typeset as $\frac{3!}{2!}$.