Search code examples
pythonwxpythonwxwidgets

wxPython - code highlighting and pygment


I am trying to utilize pygment for some code highlighting in a wxPython RichTextCtrl.

I can't find much online (other than broken links) about achieving this.

Here is some sample code. I've tried a few different formatters and they all fail. I believe editra using pygment and wxpython, but the source is difficult to navigate.

import wx
import wx.richtext

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters.rtf import RtfFormatter


lexer = get_lexer_by_name("python", stripall=True)
formatter = RtfFormatter()

code = """ # Comment
a = 5
print(a)
print(b)
"""

formatted_code = highlight(code, lexer, formatter)

########################################################################
class MyFrame(wx.Frame):

    # ----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, title='Richtext Test')

        sizer = wx.BoxSizer(wx.VERTICAL)
        self.rt = wx.richtext.RichTextCtrl(self)
        self.rt.SetMinSize((300, 200))
        self.rt.ChangeValue(formatted_code)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.rt, 1, wx.EXPAND | wx.ALL, 6)

        self.SetSizer(sizer)
        self.Show()


# ----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()

Thanks for any help


Solution

  • I ended up using StyledTextCtrl as suggested in the comments. It turns out there are 2 demos included with the wxPython source, the 2nd of which does exactly what I was trying. I would post the code but it is ~400 lines.