0
votes

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

1
@Shatmers, is it a requirement to use wxRichTextCtrl? Can you try wxSTC? - Igor
@Igor, not necessarily. I'll take a look into it. Thanks edit: How will this work with pygment though? - Shatnerz
why do you need pygment? Both wxSTC and wxRE works fine by itself. Just look at the demo/wx C++ sample. - Igor
What is wxRE? So wx supports code highlighting for a variety of languages (I genuinely don't know)? That's why I need pygment - Shatnerz
Igor also suggested using wxStyledTextCtrl and I should add that it is a wrapper to Scintilla and has many features and Scintilla is used by many software. I would not suggest using wxRichTextCtrl unless you have to. - macroland

1 Answers

0
votes

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.