PageRenderTime 47ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/src/comms/imc2lib/imc2_ansi.py

https://code.google.com/p/evennia/
Python | 60 lines | 38 code | 7 blank | 15 comment | 1 complexity | 23d6482c5a7aabb5106f8bc88afae717 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """
  2. ANSI parser - this adds colour to text according to
  3. special markup strings.
  4. This is a IMC2 complacent version.
  5. """
  6. import re
  7. from src.utils import ansi
  8. class IMCANSIParser(ansi.ANSIParser):
  9. """
  10. This parser is per the IMC2 specification.
  11. """
  12. def __init__(self):
  13. normal = ansi.ANSI_NORMAL
  14. hilite = ansi.ANSI_HILITE
  15. self.ansi_map = [
  16. (r'~Z', normal), # Random
  17. (r'~x', normal + ansi.ANSI_BLACK), # Black
  18. (r'~D', hilite + ansi.ANSI_BLACK), # Dark Grey
  19. (r'~z', hilite + ansi.ANSI_BLACK),
  20. (r'~w', normal + ansi.ANSI_WHITE), # Grey
  21. (r'~W', hilite + ansi.ANSI_WHITE), # White
  22. (r'~g', normal + ansi.ANSI_GREEN), # Dark Green
  23. (r'~G', hilite + ansi.ANSI_GREEN), # Green
  24. (r'~p', normal + ansi.ANSI_MAGENTA), # Dark magenta
  25. (r'~m', normal + ansi.ANSI_MAGENTA),
  26. (r'~M', hilite + ansi.ANSI_MAGENTA), # Magenta
  27. (r'~P', hilite + ansi.ANSI_MAGENTA),
  28. (r'~c', normal + ansi.ANSI_CYAN), # Cyan
  29. (r'~y', normal + ansi.ANSI_YELLOW), # Dark Yellow (brown)
  30. (r'~Y', hilite + ansi.ANSI_YELLOW), # Yellow
  31. (r'~b', normal + ansi.ANSI_BLUE), # Dark Blue
  32. (r'~B', hilite + ansi.ANSI_BLUE), # Blue
  33. (r'~C', hilite + ansi.ANSI_BLUE),
  34. (r'~r', normal + ansi.ANSI_RED), # Dark Red
  35. (r'~R', hilite + ansi.ANSI_RED), # Red
  36. ## Formatting
  37. (r'~L', hilite), # Bold/hilite
  38. (r'~!', normal), # reset
  39. (r'\\r', normal),
  40. (r'\\n', ansi.ANSI_RETURN),
  41. ]
  42. # prepare regex matching
  43. self.ansi_sub = [(re.compile(sub[0], re.DOTALL), sub[1])
  44. for sub in self.ansi_map]
  45. # prepare matching ansi codes overall
  46. self.ansi_regex = re.compile("\033\[[0-9;]+m")
  47. ANSI_PARSER = IMCANSIParser()
  48. def parse_ansi(string, strip_ansi=False, parser=ANSI_PARSER):
  49. """
  50. Shortcut to use the IMC2 ANSI parser.
  51. """
  52. return parser.parse_ansi(string, strip_ansi=strip_ansi)