Search and Replace Macro
Posted: Tue Dec 17, 2013 3:39 am
The macro below will do a search and replace by showing and then hiding the search and replace dialog.
During the search and replace it will prompt the user for search and replace input via the status bar.
During the search and replace it will prompt the user for search and replace input via the status bar.
Code: Select all
--
-- Name: Search and Replace Macro
--
-- Author: Jussi Jumppanen
--
-- Language: Lua Macro
--
-- Description: This script shows how to write an alternative search and
-- replace macro function. This macro will take user input
-- from the status bar.
--
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.");
beep();
return;
end
-- the default search text
local nill = ""
-- ask for a user for the search and replace details
local find_text, replace_text = user_input("Find Text:", nill, "Replace Text:", nill, "Find and Replace Dialog")
-- check for user input
if string.len(find_text) > 0 then
screen_update_disable()
-- save current search settings
search_options_save()
-- save the current cursor details (optional)
--cursor_save()
-- set the find and replace details
set_find_text(find_text)
set_replace_text(replace_text)
-- set the other search options
set_search_option("UseCase" , 0)
set_search_option("WholeWord" , 0)
set_search_option("RegExpress", 0)
local found = SearchNext()
if found == 0 then
message("Text not found: " .. find_text);
else
-- decimal values of user input (see Tools, ASCII Chart menu)
local ALL_KEY_U = 65 -- A
local ALL_KEY_L = 97 -- a
local REPLACE_KEY_U = 82 -- R
local REPLACE_KEY_L = 114 -- r
local NEXT_KEY_U = 78 -- N
local NEXT_KEY_L = 110 -- n
local QUIT_KEY_U = 113 -- Q
local QUIT_KEY_L = 81 -- q
-- loop here asking the user for input
while found == 1 do
-- show the text found
screen_update()
-- ask the user for input
message("R)eplace N)ext A)ll Q)uit")
-- get the user keyboard input response
local key = keyboard_input()
if key == ALL_KEY_U or key == ALL_KEY_L then
-- replace all
while found == 1 do
found = ReplaceNext()
found = SearchNext()
end
elseif key == NEXT_KEY_U or key == NEXT_KEY_L then
-- next
found = SearchNext()
elseif key == REPLACE_KEY_U or key == REPLACE_KEY_L then
-- replace and search next
found = ReplaceNext()
found = SearchNext()
else
-- quit
message("Search and replace is complete.")
found = 0
end
end
-- restore the cursor details (optional)
-- cursor_restore()
search_options_restore()
screen_update_enable()
screen_update()
end
else
message("Search and replace cancelled by user.")
end
end
key_macro() -- run the macro