I need a working example of a foldable code implementation for C++ lexer(STC)

Hello! I can’t figure out the implementation of the folding code.
Please give me a working example of a C++ lexer(syntax) implementation for Python 3.

Hi Daniil,

I extracted the essential part from “demo/StyledTextCtrl_2.py” and added some flavors.
The minimum c++ code editor with folding property would be like this:

import wx
from wx import stc

class Panel(stc.StyledTextCtrl):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        self.SetLexer(stc.STC_LEX_CPP)

        self.SetMarginType(1, stc.STC_MARGIN_NUMBER)
        self.SetMarginWidth(1, 32)
        self.SetMarginSensitive(1, False)

        self.SetMarginType(2, stc.STC_MARGIN_SYMBOL)
        self.SetMarginMask(2, stc.STC_MASK_FOLDERS) # mask for folders
        self.SetMarginWidth(2, 16)
        self.SetMarginSensitive(2, True)

        self.SetFoldFlags(0x10) # draw below if not expanded

        self.SetProperty('fold', '1') # Enable fold property

        v = ('white', 'black')
        self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN,    stc.STC_MARK_BOXMINUS, *v)
        self.MarkerDefine(stc.STC_MARKNUM_FOLDER,        stc.STC_MARK_BOXPLUS,  *v)
        self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB,     stc.STC_MARK_VLINE,    *v)
        self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL,    stc.STC_MARK_LCORNER,  *v)
        self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND,     stc.STC_MARK_TCORNER, *v)
        self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_TCORNER, *v)
        self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_VLINE, *v)

        self.Bind(stc.EVT_STC_MARGINCLICK, self.OnMarginClick)

    def OnMarginClick(self, evt): #<wx._stc.StyledTextEvent>
        lc = self.LineFromPosition(evt.Position)
        level = self.GetFoldLevel(lc) ^ stc.STC_FOLDLEVELBASE
        
        ## Note: level indicates indent-header flag or indent-level number
        if level and evt.Margin == 2:
            self.ToggleFold(lc)

app = wx.App()
frm = wx.Frame(None)
editor = Panel(frm)
frm.Show()
app.MainLoop()

Clipboard01

In the sample code, I used margin #1 for the line numbers and margin #2 for folders.
(see wxStyledTextCtrl - Margins)

Please try to customize the folder’s symbol.
(see wxStyledTextCtrl - Markers)

For highlighting c++ keywords, I think this post (python - How do I enable C++ highlighting in the Scintilla control in the wxPython library? - Stack Overflow) would be helpful.

EDIT Ah! the person who answered stack overflow was you! :grin:

1 Like

Yes, I answered that. :smile:

Wow! It works! Thank you so much :pray: I couldn’t figure out why my folding markers weren’t showing up before :smile: