InsertDate in Lua

In case you’re a fan of InsertDate, here’s a Lua version!

local DAY_SECONDS = 60 * 60 * 24

function nDaysFromNow(n, extraSpec)
  if extraSpec == nil then
    extraSpec = ""
  end
  return os.date("%Y-%m-%d" .. extraSpec, os.time() + DAY_SECONDS * n)
end

local function selectDate()
  local options = {}

  local metaOptions = {
    {"Today", 0},
    {"Tomorrow", 1},
    {"Day after tomorrow", 2},
    {"In one week", 7},
    {"In two weeks", 14},
  }

  for _, pair in ipairs(metaOptions) do
    local desc = pair[1]
    local n = pair[2]
    table.insert(options, {
      name = desc .. " (" .. nDaysFromNow(n) .. ")",
      value = nDaysFromNow(n)
    })
  end

  for n = 1,365 do
    local desc = nDaysFromNow(n, " (%A)")
    table.insert(options, {
      name = desc,
      value = nDaysFromNow(n)
    })
  end

  local result = editor.filterBox("Pick a date", options)
  return result
end

slashcommand.define {
  name = "date",
  run = function()
    local result = selectDate()
    if result then
      editor.insertAtCursor(result.value)
    end
  end
}
5 Likes