pangomarkup.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """
  2. pygments.formatters.pango
  3. ~~~~~~~~~~~~~~~~~~~~~~~~~
  4. Formatter for Pango markup output.
  5. :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
  6. :license: BSD, see LICENSE for details.
  7. """
  8. from pygments.formatter import Formatter
  9. __all__ = ['PangoMarkupFormatter']
  10. _escape_table = {
  11. ord('&'): '&',
  12. ord('<'): '&lt;',
  13. }
  14. def escape_special_chars(text, table=_escape_table):
  15. """Escape & and < for Pango Markup."""
  16. return text.translate(table)
  17. class PangoMarkupFormatter(Formatter):
  18. """
  19. Format tokens as Pango Markup code. It can then be rendered to an SVG.
  20. .. versionadded:: 2.9
  21. """
  22. name = 'Pango Markup'
  23. aliases = ['pango', 'pangomarkup']
  24. filenames = []
  25. def __init__(self, **options):
  26. Formatter.__init__(self, **options)
  27. self.styles = {}
  28. for token, style in self.style:
  29. start = ''
  30. end = ''
  31. if style['color']:
  32. start += '<span fgcolor="#%s">' % style['color']
  33. end = '</span>' + end
  34. if style['bold']:
  35. start += '<b>'
  36. end = '</b>' + end
  37. if style['italic']:
  38. start += '<i>'
  39. end = '</i>' + end
  40. if style['underline']:
  41. start += '<u>'
  42. end = '</u>' + end
  43. self.styles[token] = (start, end)
  44. def format_unencoded(self, tokensource, outfile):
  45. lastval = ''
  46. lasttype = None
  47. outfile.write('<tt>')
  48. for ttype, value in tokensource:
  49. while ttype not in self.styles:
  50. ttype = ttype.parent
  51. if ttype == lasttype:
  52. lastval += escape_special_chars(value)
  53. else:
  54. if lastval:
  55. stylebegin, styleend = self.styles[lasttype]
  56. outfile.write(stylebegin + lastval + styleend)
  57. lastval = escape_special_chars(value)
  58. lasttype = ttype
  59. if lastval:
  60. stylebegin, styleend = self.styles[lasttype]
  61. outfile.write(stylebegin + lastval + styleend)
  62. outfile.write('</tt>')