Page 1 of 1

Matching Brace Select

Posted: Thu May 05, 2011 2:08 am
by jussij
The Lua macro below will highlight the region between the current brace character and it's matching brace character.

Code: Select all

--
--        Name: Matching Brace Select
--
--    Language: Lua Macro
--
-- Description: This Lua macro will select the region from the current
--              brace character to the matching brace character.
--

function key_macro()
    -- macro only works for documents
    local document = is_document()

    if document > 0 then
        screen_update_disable()

        -- save the current cursor
        cursor_save()

        current = get_char_at()
        previous = '\0'

        if get_cursor_pos() > 1 then
            previous = get_char_at(get_line_pos(),get_cursor_pos()-1)
        end

        -- position the cursor for the brace match that follows
        if current  == string.byte('(') or
           current  == string.byte('<') or
           current  == string.byte('[') or
           current  == string.byte('{') then
              MoveLineRight()
        elseif
            previous == string.byte(')') or
            previous == string.byte('>') or
            previous == string.byte(']') or
            previous == string.byte('}') then
              MoveLineLeft()
        end

         MarkBlockSet()

         if BraceMatch() == 1 then
             -- ignore the saved cursor details
             cursor_ignore()

             -- see where we ended up
             current = get_char_at()
             previous = '\0'

             if get_cursor_pos() > 1 then
                 previous = get_char_at(get_line_pos(),get_cursor_pos()-1)
             end

             -- position the cursor inside the brace chracters found
             if current  == string.byte('(') or
                current  == string.byte('<') or
                current  == string.byte('[') or
                current  == string.byte('{') then
                   MoveLineRight()
             elseif
                 previous == string.byte(')') or
                 previous == string.byte('>') or
                 previous == string.byte(']') or
                 previous == string.byte('}') then
                   MoveLineLeft()
             end

             MarkBlockReset()
         else
            -- restore the cursor as no matching brace was found
            cursor_restore()
            MarkHide()
         end

        screen_update_enable()
        screen_update()
    else
        message("This macro only works for document files.")
        beep()
    end
end

key_macro() -- run the macro