3

I'm trying to find a tool to convert TeX into something like the following:

{\frac{-x}{y}}

to

((-x)/(y))

or

{\frac{1}{x\ln(b)}}

to

((1)/(xln(b)))

I built a very simple converter for it but it has trouble with some edge cases, and I was wondering if there were any tools that already did this.

Mico
  • 506,678
Slackow
  • 33
  • You mention "trouble with some edge cases" -- please give some examples. – Mico Sep 30 '20 at 05:16
  • 1
    I have an unusual answer here that examines this problem: https://tex.stackexchange.com/questions/332012/translate-in-line-equations-to-tex-code-any-package/332061#332061. However, it's focus is the opposite...to take code similar to your desired endstate, and convert it into LaTeX code. – Steven B. Segletes Sep 30 '20 at 09:28

1 Answers1

3

If you're free to use LuaLaTeX, the following solution may be of interest to you. It sets up a LaTeX macro called \TexToText which calls a Lua function called tex2text to do most of the work. Four separate steps are performed by tex2text:

  • convert \frac notation to inline-math notation
  • drop sizing instructions for math "fence" symbols
  • remove the \ (backslash) character in front of other TeX macro names (e.g, \exp and \ln)
  • encase the final expression in a pair of parentheses.

enter image description here

% !TEX TS-program = lualatex
\documentclass{article}
\usepackage{luacode} % for 'luacode' env. and '\luastringN' macro
\begin{luacode}
-- Aux. function to trim first and last char. of a string:
function trim ( s )
  return s:sub(2,-2) 
end
-- Aux. function to get rid of \frac wrapper
function frac2text ( s )
  s =  s:gsub ( "\\frac%s-(%b{})%s-(%b{})", 
                function (u,v)
                   return "("..trim(u)..")/("..trim(v)..")" 
                end ) 
  return s
end
-- The main Lua function:
function tex2text ( s )
   -- Call frac2text function:
   s = frac2text ( s )
   -- Drop fence-sizing macros:
   s = s:gsub ( "\\left" , "" )
   s = s:gsub ( "\\right" , "" )
   s = s:gsub ( "\\[Bb]igg?[lmr]?" , "" )
   -- Remove leading backslash char from all other macros:
   s = s:gsub ( "\\(%a+)" , "%1\\ignorespacesafterend" )
   -- Encase the result in a pair of parentheses:
   return "(" .. s .. ")"
end
\end{luacode}
\newcommand\TexToText[1]{\directlua{tex.sprint(tex2text(\luastringN{#1}))}}

\begin{document} \TexToText{\ln(\exp(0))} \quad \TexToText{\frac{-x}{y}} \quad \TexToText{\frac{1}{x\ln(b)}} \end{document}

Mico
  • 506,678