def find_matching_paren()

in scripts/convert_addSourceLines_textblock.py [0:0]


def find_matching_paren(src: str, open_idx: int) -> Optional[int]:
    """Find matching ')' for the '(' at open_idx."""
    if open_idx >= len(src) or src[open_idx] != "(":
        return None
    depth = 1
    i = open_idx + 1
    state = "normal"
    while i < len(src):
        c = src[i]
        if state == "normal":
            if c == '"':
                state = "string"
            elif c == "'":
                state = "char"
            elif c == "/" and i + 1 < len(src) and src[i + 1] == "/":
                state = "line_comment"
                i += 1
            elif c == "/" and i + 1 < len(src) and src[i + 1] == "*":
                state = "block_comment"
                i += 1
            elif c == "(":
                depth += 1
            elif c == ")":
                depth -= 1
                if depth == 0:
                    return i
        elif state == "string":
            if c == "\\":
                i += 1
            elif c == '"':
                state = "normal"
        elif state == "char":
            if c == "\\":
                i += 1
            elif c == "'":
                state = "normal"
        elif state == "line_comment":
            if c == "\n":
                state = "normal"
        elif state == "block_comment":
            if c == "*" and i + 1 < len(src) and src[i + 1] == "/":
                state = "normal"
                i += 1
        i += 1
    return None