I've been forced by the TeX.sx chatroom mafia to post my lovely, buggy, terrible, traumatic, post-apocalyptic poor man's implementation of a replacement script. :)
Well, sadly this won't be a TeX answer. :)
Here's my humble attempt, with a script language I'm terrible at.
(I'm looking at you, Python!)
import re
import sys
if len(sys.argv) != 3:
print('We need two arguments.')
sys.exit()
inputHandler = open(sys.argv[1], 'r')
mathDictionary = {}
commandDictionary = {}
print('Extracting commands...')
for line in inputHandler:
mathOperator = re.search('\\\\DeclareMathOperator{\\\\([A-Za-z]*)}{(.*)}', line)
if mathOperator:
mathDictionary[mathOperator.group(1)] = mathOperator.group(2)
newCommand = re.search('\\\\newcommand{\\\\([A-Za-z]*)}{(.*)}', line)
if newCommand:
commandDictionary[newCommand.group(1)] = newCommand.group(2)
inputHandler.seek(0)
print('Replacing occurrences...')
outputHandler = open(sys.argv[2],'w')
for line in inputHandler:
current = line
for x in mathDictionary:
current = re.sub('\\\\DeclareMathOperator{\\\\' + x + '}{(.*)}', '', current)
current = re.sub('\\\\' + x + '(?!\w)', '\\operatorname{' + mathDictionary[x] + '}', current)
for x in commandDictionary:
current = re.sub('\\\\newcommand{\\\\' + x + '}{(.*)}', '', current)
current = re.sub('\\\\' + x + '(?!\w)', commandDictionary[x], current)
outputHandler.write(current)
print('Done.')
inputHandler.close()
outputHandler.close()
Now, we simply call it:
$ python myconverter.py input.tex output.tex
Extracting commands...
Replacing occurrences...
Done.
input.tex
\documentclass{amsart}
\usepackage{amsmath,amssymb}
\newcommand{\N}{\mathbb{N}}
\DeclareMathOperator{\End}{End}
\begin{document}
In this lecture we'll study the ring of Endomorphisms of an Abelian group $A$.
Let's denote this ring by $\End(A)$. Throughout the lecture, $\N$ will denote
the set of natural numbers.
\end{document}
output.tex
\documentclass{amsart}
\usepackage{amsmath,amssymb}
\begin{document}
In this lecture we'll study the ring of Endomorphisms of an Abelian group $A$.
Let's denote this ring by $\operatorname{End}(A)$. Throughout the lecture, $\mathbb{N}$ will denote
the set of natural numbers.
\end{document}
Limitations:
- It's my code, so beware!
:)
- It works only with
\DeclareMathOperator{...}{...}
and \newcommand{...}{...}
.
- No optional arguments are supported for
\newcommand
.
- The declaration must be in only one line.
- Balanced curly brackets, please.
:)
I know that regular expressions are not suitable for parsing TeX, but they should work for very simple replacements.
Here's a beautiful reading about regex. Have fun. :)
$\N$
with$\mathbb {N}$
. So, basically, I'd like the script to replacefoo
withoof
if the preamble has the line\newcommand{foo}{oof}
.perl
will be ideal for this... but are you after something inTeX
?