tex.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #!/usr/bin/env python3
  2. # Contest Management System - http://cms-dev.github.io/
  3. # Copyright © 2014 Fabian Gundlach <320pointsguy@gmail.com>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. REPLACEMENTS = {"&": r"\&{}",
  18. "%": r"\%{}",
  19. "$": r"\${}",
  20. "#": r"\#{}",
  21. "_": r"\_{}",
  22. "{": r"\{{}",
  23. "}": r"\}{}",
  24. "~": r"\textasciitilde{}",
  25. "^": r"\textasciicircum{}",
  26. "\\": r"\textbackslash{}"}
  27. def escape_tex_normal(string):
  28. """Escape a string for use inside latex.
  29. string (unicode): string to escape
  30. return (unicode): escaped string
  31. """
  32. def repc(c):
  33. if c in REPLACEMENTS:
  34. return REPLACEMENTS[c]
  35. else:
  36. return c
  37. return "".join(repc(c) for c in string)
  38. def escape_tex_tt(string):
  39. """Escape a string for use inside latex with \texttt.
  40. string (unicode): string to escape
  41. return (unicode): escaped string
  42. """
  43. def repc(c):
  44. if c in REPLACEMENTS:
  45. return "\\char\"%02X{}" % ord(c)
  46. else:
  47. return c
  48. return "".join(repc(c) for c in string)