Page 1 of 1

Numbers Macro

Posted: Fri Jul 25, 2008 5:58 am
by jussij
Assume you have this piece of code:

Code: Select all

    FieldXX
    FieldXX
    FieldXX
    FieldXX
    FieldXX
    FieldXX
    FieldXX
    FieldXX
    FieldXX
    FieldXX
    FieldXX
By column marking the XX values and running the Numbers.lua macro shown below the code gets changed to this:

Code: Select all

    Field00
    Field01
    Field02
    Field03
    Field04
    Field05
    Field06
    Field07
    Field08
    Field09
    Field10
Here is the Numbers.lua macro source code:

Code: Select all

--
--        Name: Numbers Macro
--
--      Author: Jussi Jumppanen
--
--    Language: Lua Macro
--
-- Description: This simple Lua macro will replace a column marked area
--              into a series of incremental numbers. To use the macro
--              column mark a range of lines and then run the macro.
--
--  How To Run: All Zeus macros can be run using the macro execute menu
--              item or they can be bound to the keyboard or they can
--              be attached to the macro drop down or popup menus.
--
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

  -- macro only works for marked documents
  if is_marked() == 0 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("Decimal 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()

  -- convert the number to a character
  local offset = string.format("%d", value)

  -- maximum number
  local max_number = range - 1 + offset

  -- the maximum length
  local max_length = string.len(string.format("%s", max_number)) - 1

  -- comment the lines selected
  for i = 0, range - 1, 1 do
    -- build the number
    local number = string.format("%s", i + offset)

    -- save the current cursor
    cursor_save()

    for k = string.len(number), max_length, 1 do
      -- write out the padding
      write("0")
    end

    -- write out the number
    write(number)

    -- restore cursor
    cursor_restore()

    -- move to the next line
    MoveLineDown()
  end

  -- restore screen updates
  screen_update_enable()
end

key_macro() -- run the macro