[Tex/LaTex] simpler Macro for fraction

fractionsmacros

Is there a way to define a macro like {#1}/{#2} to abbreviate the command \frac{#1}{#2}?

Best Answer

The OP has indicated a preference for a pdfLaTeX-based solution. However, since I don't know how to provide such a solution, I'm providing a LuaLaTeX-based solution instead. Maybe readers who don't mind using (or actually prefer to use!) LuaLaTeX will find it useful.

enter image description here

The Lua function is set up to capture and process expressions of the form

{...}/{...}

The mandatory elements for a pattern match to occur are (a) two pairs of matching curly braces, (b) the / symbol, and (c) no whitespace to the left and right of /. If these three elements aren't found, no pattern match occurs, and no `\frac{...}{...} expression is produced.

Edit: The function can now handle nested expressions such as {{a}/{b}}/{{c}/{d}}; that'll produce \frac{\frac{a}{b}}{\frac{c}{d}}.

The code shown below also sets up two LaTeX macros: \InlineToFracStart and \InlineToFracStop. The former activates the Lua function, the latter disables it. Having these macros may be useful, as running the Lua function imposes some overhead in terms of scanning and processing the input lines. For instance, if it's known that the document contains expressions of the form {a}/{b} in sections 2 and 3, but not elsewhere, one could run \InlineToFracStart at the start of section 2 and rund \InlineToFracStop at the end of section 3. (Of course, if you don't mind or care about incurring overhead and just want to have the Lua function cover the entire document, simply run \InlineToFracStart just before or after the \begin{document} statement.)

% !TEX TS-program = lualatex
\documentclass{article}
\usepackage{luacode}
%% Lua-side code
\begin{luacode}
function inline2frac ( s )
   s = s:gsub ( "(%b{})/(%b{})" , function (x,y)
                    x = inline2frac ( x )
                    y = inline2frac ( y )            
                    return "\\frac{"..x.."}{"..y.."}"  
                end ) 
   return s
end
\end{luacode}
%% TeX-side code: macros to enable and disable the Lua function
\newcommand\InlineToFracStart{\directlua{luatexbase.add_to_callback(
   "process_input_buffer", inline2frac, "inline2frac" )}}
\newcommand\InlineToFracStop{\directlua{luatexbase.remove_from_callback(
   "process_input_buffer", "inline2frac" )}}

\begin{document}
\InlineToFracStart % enable the Lua function

$\displaystyle {a}/{b} \quad {{a}/{c}}/{b} 
  \quad {{a}/{b}}/{{u}/{{v}/{{w}/{{x}/{y}}}}} \quad a/b$
\end{document}
Related Question