File Insert Macro
Posted: Wed Feb 28, 2007 1:04 am
The following file_insert.lua Lua macro inserts a user selected file at the current cursor location:
Cheer Jussi
Code: Select all
--
-- Name: file_insert
--
-- Author: Jussi Jumppanen
--
-- Language: Lua Macro
--
-- Description: A simple Lua macro that inserts the user selected file
-- at the current cursor location. This macro should only
-- be used for relatively small (ie < 100 kBytes) files.
--
function file_insert()
-- macro only works for documents
if is_document() == 0 then
message("This macro only works for document files!")
beep()
return
end
-- macro only works for read/write documents
if is_read_only() == 1 then
message("The current document is marked as read only!")
beep()
return
end
-- the starting directory
local dir = macro_tag("$FDD")
-- build up a file filter string
local cpp_files = "C/C++ files (*.cpp;*.c;*.hpp;*.h)|*.cpp;*.c;*.hpp;*.h|"
local txt_files = "Text Files (*.txt)|*.txt|"
local filter = cpp_files .. txt_files
-- display the file select dialog using the filter
local file_name = file_select_dialog(dir, filter)
if string.len(file_name) > 0 then
screen_update_disable()
-- save the current cursor location
cursor_save()
-- open the file selected for text reading mode
local file_in = io.open(file_name, "r+t")
if file_in ~= nil then
local result = ""
-- read the file into a local variable
for line in file_in:lines() do
-- add the line to the results buffer
result = result .. line .. "\r\n"
end
-- insert the text into the file (without smart indent)
write(result, false)
-- close the input file
file_in:close()
-- operation complete
message("Inserted '" .. file_name .. "' file.")
else
-- display an error message
message("Error opening '" .. file_name .. "' file.")
beep()
end
-- restore original cursor location
cursor_restore()
-- update the screen
screen_update_enable()
screen_update()
end
end
file_insert() -- run the macro