first version of legacy converter

This commit is contained in:
Maximilian Keßler 2022-02-16 14:47:29 +01:00
commit 7a7e199f91
2 changed files with 91 additions and 0 deletions

22
constants.py Normal file
View file

@ -0,0 +1,22 @@
ENVIRONMENTS = {
'prop': 'proposition',
'satz': 'theorem',
'kor': 'corollary',
'bsp': 'example',
'bem': 'remark',
}
ALPHABETS = {
'b': 'mathbb',
'c': 'mathcal',
'f': 'mathfrak',
'': 'mathbb',
}
DEPRECATED = {
r'\eps': r'\varepsilon',
r'\inv': r'^{-1}',
r'\se': r'\subseteq',
r'\sm': r'\setminus',
r'\st': r'^{\ast}',
}

69
latex_legacy_converter.py Normal file
View file

@ -0,0 +1,69 @@
from constants import ENVIRONMENTS, ALPHABETS, DEPRECATED
import re
import pathlib
from pathlib import Path
def _migrate_lazy_math_alphabet(line: str, letters: str, short: str, alph: str):
for letter in letters:
while True:
m = re.search(r'\\%s%s(?=![a-zA-Z@])' % (short, letter), line)
if m is None:
break
else:
line = line[:m.start()] + r'\%s{%s}' % (alph, letter) + line[m.end():]
return line
def migrate_lazy_math_alphabets(line: str) -> str:
for short, alph in ALPHABETS:
if short == '':
line = _migrate_lazy_math_alphabet(line, 'NZQRCFK', '', alph)
else:
line = _migrate_lazy_math_alphabet(line, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', short, alph)
if short == 'f':
line = _migrate_lazy_math_alphabet(line, 'klmspqabc', short, alph)
return line
def migrate_deprecated(line: str) -> str:
for old, new in DEPRECATED.items():
while True:
old = old.replace('\\', r'\\')
m = re.search(old + '(?=![a-zA-Z@])', line)
if m is None:
break
else:
line = line[:m.start()] + new + line[m.end():]
return line
def migrate_environments(line: str) -> str:
for old_env, new_env in ENVIRONMENTS.items():
line = line.replace(r'\begin{%s}' % old_env, r'\begin{%s}' % new_env)
line = line.replace(r'\end{%s}' % old_env, r'\end{%s}' % new_env)
return line
def optimize_line(line: str) -> str:
line = migrate_environments(line)
line = migrate_lazy_math_alphabets(line)
line = migrate_deprecated(line)
return line
def convert(path: Path):
with path.open('r') as f:
lines = f.readlines()
newlines = []
for line in lines:
newlines.append(optimize_line(line))
with path.open('w') as f:
path.write_text(''.join(newlines))
if __name__ == "__main__":
here = Path('.')
for file in here.rglob('*.tex'):
convert(Path(file))