Pygments in PyGTK


/ Published in: Python
Save to your folder(s)

How to use pygments in PyGTK textview


Copy this code and paste it in your HTML
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. GTKPygments
  5. ~~~~~~~~~~~
  6.  
  7. proof of concept pygments to gtk widget renderer
  8.  
  9. :copyright: 2007 by Armin Ronacher.
  10. :license: GNU GPL.
  11. """
  12. import pygtk
  13. pygtk.require('2.0')
  14. import gtk
  15. import pango
  16. from pygments.lexers import PythonLexer
  17. from pygments.styles.colorful import ColorfulStyle
  18.  
  19.  
  20. STYLE = ColorfulStyle
  21. f = file(__file__)
  22. try:
  23. SOURCE = f.read()
  24. finally:
  25. f.close()
  26.  
  27.  
  28. class GTKPygments(gtk.Window):
  29.  
  30. def __init__(self):
  31. super(GTKPygments, self).__init__()
  32. self.set_title('GTK Pygments')
  33.  
  34. win = gtk.ScrolledWindow()
  35. self.add(win)
  36. self.textview = gtk.TextView()
  37. win.add(self.textview)
  38. buf = gtk.TextBuffer()
  39.  
  40. styles = {}
  41. for token, value in PythonLexer().get_tokens(SOURCE):
  42. while not STYLE.styles_token(token) and token.parent:
  43. token = token.parent
  44. if token not in styles:
  45. styles[token] = buf.create_tag()
  46. start = buf.get_end_iter()
  47. buf.insert_with_tags(start, value.encode('utf-8'), styles[token])
  48.  
  49. for token, tag in styles.iteritems():
  50. style = STYLE.style_for_token(token)
  51. if style['bgcolor']:
  52. tag.set_property('background', '#' + style['bgcolor'])
  53. if style['color']:
  54. tag.set_property('foreground', '#' + style['color'])
  55. if style['bold']:
  56. tag.set_property('weight', pango.WEIGHT_BOLD)
  57. if style['italic']:
  58. tag.set_property('style', pango.STYLE_ITALIC)
  59. if style['underline']:
  60. tag.set_property('underline', pango.UNDERLINE_SINGLE)
  61.  
  62. self.connect('delete-event', lambda *a: gtk.main_quit())
  63.  
  64. self.textview.set_buffer(buf)
  65. self.textview.set_editable(False)
  66. self.textview.modify_font(pango.FontDescription('monospace'))
  67.  
  68. self.resize(800, 500)
  69. self.show_all()
  70.  
  71. def run(self):
  72. gtk.main()
  73.  
  74.  
  75. if __name__ == '__main__':
  76. GTKPygments().run()

URL: http://lucumr.pocoo.org/2007/5/30/pygments-gtk-rendering

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.