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))