Is there a way to autoreplace .../...
with \frac{...}{...}
?
For example, 143/23
should be rendered as \frac{143}{23}
Is there a way to autoreplace .../...
with \frac{...}{...}
?
For example, 143/23
should be rendered as \frac{143}{23}
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.)
% !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!}$
.
%
) My comment was perhaps a bit garbled, but anyway I'll remove both comments as the question is now edited
Commented
Oct 5, 2015 at 13:23
There is TeX primitive \over
. \frac
is not the same, but the results in the basic case will be the same. Hence you can write
\catcode`\/=13
\def/{\over}
There are some disadvantages of making /
an active character, but it is your choice.
MWE (please make them in the future) in your situation:
\documentclass{article}
\begin{document}
\catcode`\/=13
\def/{\over}
\[
143/23
\]
\end{document}
/
in other meaning than division, you should expect problem. But my MWE is working for you?
Commented
Oct 5, 2015 at 11:44
#1/#2
by \frac{#1}{#2}
manually.
Commented
Oct 5, 2015 at 11:56