Peter Damoc:
Hi List,
I've played recently with the StyledTextCtrl and I've tried to implement a very small editor.
The code is very small and I would like to get it even smaller...
Any ideas are welcomed.
Nice idea. I looked at customSTC.py and there is room for improvement, besides Josiah's suggestion. For example, this is the last method:
def Expand(self, line, doExpand, force=False, visLevels=0,
level=-1):
lastChild = self.GetLastChild(line, level)
line = line + 1
while line <= lastChild:
if force:
if visLevels > 0:
self.ShowLines(line, line)
else:
self.HideLines(line, line)
else:
if doExpand:
self.ShowLines(line, line)
if level == -1:
level = self.GetFoldLevel(line)
if level & stc.STC_FOLDLEVELHEADERFLAG:
if force:
if visLevels > 1:
self.SetFoldExpanded(line, True)
else:
self.SetFoldExpanded(line, False)
line = self.Expand(line, doExpand, force,
visLevels-1)
else:
if doExpand and self.GetFoldExpanded(line):
line = self.Expand(line, True, force,
visLevels-1)
else:
line = self.Expand(line, False, force,
visLevels-1)
else:
line = line + 1
return line
If I was to review this code, I would say it is too long, too deeply nested and suffers from duplication. In addition, there are no tests, so we would have to be careful refactoring this.
My first change would be to call self.SetFoldExpanded only once:
self.SetFoldExpanded(line, visLevels > 1)
My next step would be to remove the duplicated calls to self.Expand:
expandLine = doExpand
else:
expandLine = doExpand and self.GetFoldExpanded(line)
line = self.Expand(line, expandLine, force,
visLevels-1)
I would replace "line = line + 1" with "line += 1".
Further refactoring then gets me this version (untested):
def Expand(self, line, doExpand, force=False, visLevels=0,
level=-1):
lastChild = self.GetLastChild(line, level)
line += 1
while line <= lastChild:
if (force and visLevels > 0) or (not force and doExpand):
self.ShowLines(line, line)
elif force and visLevels == 0:
self.HideLines(line, line)
if level == -1:
level = self.GetFoldLevel(line)
if level & stc.STC_FOLDLEVELHEADERFLAG:
if force:
self.SetFoldExpanded(line, visLevels > 1)
expandLine = doExpand
else:
expandLine = doExpand and self.GetFoldExpanded(line)
line = self.Expand(line, expandLine, force, visLevels-1)
else:
line += 1
return line
To refactor this further I need to know more about how this works. E.g. does it make sense to hide a line and then call expand on it? What is force actually meant to force? Why does the recursive call to Expand not pass the level argument? Etc. If I understand the code better I could maybe extract a few extra methods, or reorder to make it show its intention better.
Other methods have similar issues, OnUpdateUI for example. Are you sure that method is correct? styleBefore is uninitialized if caretPos == 0. I noticed this while refactoring it...
Cheers, Frank