Page 1 of 1

Insert String

Posted: Thu Jan 31, 2013 2:53 am
by jussij
The following macro asks the user for an input value and insert that value into every line of the marked region.

Code: Select all

--
--        Name: Insert Macro
--
--      Author: Jussi Jumppanen
--
--    Language: Lua Macro
--
-- Description: This simple Lua macro will replace a column marked area
--              with the text provided.
--
function key_macro()
  -- macro only works for read/write documents.
  if (is_read_only() == 1) or (is_document() == 0) then
    message("This macro can only be used with a writable document.")
    beep()
    return
  end

  local MARK_COLUMN = 0

  -- macro only works for column marked regions
  if is_marked() == 0 or get_marked_mode() ~= MARK_COLUMN then
    message("This macro needs a column marked area.")
    beep()
    return
  end

  -- the initial value
  local initial_value = "0"

  -- ask for a user supplied decimal number
  local value = user_input("String Value:", initial_value)

  if string.len(value) == 0 then
    message("Operation cancelled by user!")
    return
  end

  -- get the marked text details
  local top   = get_marked_top()
  local range = get_marked_bottom() - top + 1

  -- disable screen updates
  screen_update_disable()

  -- delete the marked area
  MarkDeleteEx()

  -- number the lines selected
  for i = 0, range - 1, 1 do
    -- save the current cursor
    cursor_save()

    -- write out the value
    write(value)

    -- restore cursor
    cursor_restore()

    -- move to the next line
    MoveLineDown()
  end

  -- restore screen updates
  screen_update_enable()
end

key_macro() -- run the macro