Detab current document

This forum allows you to share scripts with other Zeus users. Please do not post bug reports, feature requests or questions to this forum, but rather use it exclusively for posting scripts or for the discussion of scripts that have been posted.
Post Reply
aphor
Posts: 21
Joined: Mon Dec 16, 2013 6:01 am

Detab current document

Post by aphor »

Replacemnent for CodeWright's Detab() function.

Code: Select all

--        Name: Detab
--    Language: Lua Macro
-- Description: Converts all tabs to spaces in the current document.
--              optionally limited to only tabs at the beginning of
--              a line.
function key_macro()

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

    -- macro only works for read / write documents.
    local locked = is_read_only()

    if (locked == 1) or (document == 0) then
        message("This macro only works for writable document files.");
        return;
    end

    -- decimal values of user input (see Tools, ASCII Chart menu)
    local YES_KEY_U    = 89  -- Y
    local YES_KEY_L    = 121 -- y
    local NO_KEY_U     = 78  -- N
    local NO_KEY_L     = 110 -- n
    local CANCEL_KEY_U = 99  -- C
    local CANCEL_KEY_L = 67  -- c

    -- ask the user for input
    message("Limit to beginning of line? (Y)es (N)o (C)ancel")

    -- get the user keyboard input response
    local key = keyboard_input()

    if key == YES_KEY_U or key == YES_KEY_L then
        -- find any sequence of tabs at the beginning of a line
        set_find_text("^\t+")
    elseif key == NO_KEY_U or key == NO_KEY_L then
        -- find any sequence of tabs
        set_find_text("\t+")
    elseif key == CANCEL_KEY_U or key == CANCEL_KEY_U then
        message("Detab aborted!");
        return;
    else
        message("Invalid response");
        return;
    end

    search_options_save()
    set_search_option("RegExpress", 1)
    screen_update_disable()
    cursor_save()
    set_line_pos(1)

    local found = SearchNext()

    if found == 0 then
        message("No tabs found to replace");
    else
        while found == 1 do
            -- create a sequence of spaces equal to the column width of
            -- the tab sequence found to use as the replacement text.
            replace_text = string.rep(' ', get_marked_right() - get_marked_left() )
            set_replace_text(replace_text)
            found = ReplaceNext()
            found = SearchNext()
        end

        message("Finished!");
    end

    search_options_restore()
    screen_update_enable()
    screen_update()
    cursor_restore()
end

key_macro() -- run the macro
Post Reply