Finding matched parentheses

Mark Wieder mwieder at ahsoftware.net
Thu Jul 25 20:32:38 EDT 2013


David-

Thursday, July 25, 2013, 5:17:20 PM, you wrote:

> Has anyone scripted a function that will locate the closing  
> parenthesis (or bracket, etc.) of a pair?  Below is my effort.   
> Reports of its limitations or simpler alternatives (regex?) are invited.

Here's the one I wrote for glx2. I don't know if it counts as simpler,
but it does the trick. It's called from the mouseDown handler when the
user right-clicks on a parenthesis, thus the clickline and chunk
parameters.

private function FindMatching pClickLine, pChunk
    local tResult
    local tToken
    local tCharNum
    local tHowMany
    local tStartPos, tEndPos

    lock screen
    put false into tResult
    put word 2 of pChunk into tCharNum
    put char tCharNum of me into tToken
    put 1 into tHowMany
    switch tToken
        case "("
            put tCharNum into tStartPos
            repeat with x=1 to the number of chars in me
                switch char tCharNum+x of me
                    case tToken
                        add 1 to tHowMany
                        break
                    case ")"
                        subtract 1 from tHowMany
                        if tHowMany is 0 then
                            put tCharNum+x into tEndPos
                            put true into tResult
                            exit repeat
                        end if
                        break
                end switch
            end repeat
            break
        case ")"
            repeat with x=tCharNum-1 down to 1
                switch char x of me
                    case tToken
                        add 1 to tHowMany
                        break
                    case "("
                        subtract 1 from tHowMany
                        if tHowMany is 0 then
                            put x into tStartPos
                            put tCharNum into tEndPos
                            put true into tResult
                            exit repeat
                        end if
                        break
                end switch
            end repeat
            break
    end switch
    if tResult is true then
        -- now you have tStartPos and tEndPos in the line
        set the backcolor of char tStartPos to tEndPos of me to \
        "orange"
    end if
    unlock screen
    return tResult
end FindMatching

-- 
-Mark Wieder
 mwieder at ahsoftware.net





More information about the use-livecode mailing list