Page 1 of 1

Find Strings and Mark Region

Posted: Fri Aug 16, 2013 4:21 am
by jussij

Code: Select all

--
--        Name: Find Strings and Mark Region
--
--      Author: Jussi Jumppanen
--
--    Language: Lua Macro
--
-- Description: This simple Lua macro asks the user for two search strings
--              and then searches the current document looking for the two
--              string values. If it finds the two strings it marks the
--              region between the two strings.

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

    if (document == 0) then
        message("This macro only works for document files.");
        beep();
        return;
    end

    -- the default command
    local nill = ""

    -- ask for a user for a command line
    input1, input2 = user_input("Start Text:", nill, "End Text:", nill, "Input the Start and End Text")

    -- check for user input
    if string.len(input1) > 0 and string.len(input2) > 0 then
        screen_update_disable()

        -- save the cursor details
        cursor_save()

        -- save the current search options
        search_options_save()

        -- set the search options
        set_search_option("UseCase"   , 0)
        set_search_option("WholeWord" , 0)
        set_search_option("RegExpress", 0)

        set_find_text(input1)

        if SearchNext() == 1 then
            -- save the starting location
            line_begin   = get_line_pos()
            cursor_begin = get_cursor_pos()

            set_find_text(input2)

            if SearchNext() == 1 then
                -- save the end location
                line_end   = get_line_pos()
                cursor_end = get_cursor_pos()

                -- ignore the saved cursor
                cursor_ignore()

                -- move to start of text
                set_line_pos(line_begin, cursor_begin)

                -- turn on marking
                MarkBlockSet()

                -- move to end of text
                set_line_pos(line_end, cursor_end)

                return
            else
                -- restore the saved cursor
                cursor_restore()
            end
        else
            -- restore the saved cursor
            cursor_restore()
        end

        -- restore the previous search options
        search_options_save()

        screen_update_enable()
        screen_update()
    else
        message("Operation cancelled by user.")
    end
end

key_macro() -- run the macro