preprocess_tex_for_word.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/env python3
  2. import re
  3. import sys
  4. from pathlib import Path
  5. if len(sys.argv) != 3:
  6. print("Usage: preprocess_tex_for_word.py input.tex output.tex", file=sys.stderr)
  7. sys.exit(1)
  8. src = Path(sys.argv[1]).read_text(encoding="utf-8")
  9. text = src
  10. # Rename \includegraphics{file.ext} -> \includegraphics{file.png}
  11. text = re.sub(
  12. r'(\\includegraphics(?:\[[^\]]*\])?\{[^{}]+?)\.[^./{}\\]+(\})',
  13. r'\1.png\2',
  14. text
  15. )
  16. # Replace siunitx S[...] columns with plain right-aligned columns
  17. text = re.sub(r'S\[[^\]]*\]', 'r', text)
  18. # Replace bare S columns with r as well
  19. text = re.sub(r'(?<![A-Za-z])S(?![A-Za-z])', 'r', text)
  20. # Remove \resizebox{...}{...}{ ...tabular... }
  21. # Allow optional % after opening { and before closing }
  22. resizebox_tabular = re.compile(
  23. r'''
  24. \\resizebox\s*
  25. \{[^{}]*\}\s* # first arg
  26. \{[^{}]*\}\s* # second arg
  27. \{\s*%?\s* # opening body, optional %
  28. (\\begin\{tabular\}.*?\\end\{tabular\}) # inner tabular
  29. \s*%?\s*\} # optional % before closing }
  30. ''',
  31. re.DOTALL | re.VERBOSE
  32. )
  33. while True:
  34. new_text, n = resizebox_tabular.subn(r'\1', text)
  35. text = new_text
  36. if n == 0:
  37. break
  38. Path(sys.argv[2]).write_text(text, encoding="utf-8")