Sublime Forum

How to fold when start and end markers are not balanced

#1

Hi, I’m trying to create a syntax-based Fold command, so far the command works well when all markers are balanced, it works by level too:


but fails when at least one marker is not matched:

    def get_folds(self, level: int, regex: str, ignore: str) -> [sublime.Region]:
        text = self.view.substr(sublime.Region(0, self.view.size()))
        # regex contains two named groups, start and end
        markers = ((m.groupdict(), sublime.Region(*m.span()))
                   for m in finditer(regex, text)
                   if not self.view.match_selector(m.start(), ignore))
        i = 0
        regions = []
        matched = True
        for g, r in markers:
            # found a start marker
            if g['start']:
                i += 1
            # found an end marker
            elif g['end']:
                i -= 1
            # found a start marker at level
            # take the position after the marker
            if i == level and matched:
                x = r
                matched = False
            # found an end marker at level
            # take the position before the marker
            elif i == level - 1 and not matched:
                regions.append(sublime.Region(x.b, r.a))
                matched = True
        return regions

how can i change the algorithm to not fail when markers are not balanced ?

0 Likes