Text Expander

@rebind / text-expanderv0.1.3Public

Type short abbreviations like ;sig or /date and press Tab to expand them anywhere.

Files

Older release. Installs get 0.1.3.

main.luau2.0 KB

-- Text Expander: type an abbreviation, press the expand key, and it is
-- replaced by its text. It types for you, so it works in every app.

local cfg = UI.Schema({
  trigger = UI.Keybind("Tab", { label = "Expand with" }),
  abbr1 = UI.Text("@@", { label = "Abbreviation 1", tab = "Snippets" }),
  text1 = UI.Text(
    "you@company.com",
    { label = "Expands to", tab = "Snippets" }
  ),
  abbr2 = UI.Text(";sig", { label = "Abbreviation 2", tab = "Snippets" }),
  text2 = UI.Text("Best,\nAlex", { label = "Expands to", tab = "Snippets" }),
  abbr3 = UI.Text("/date", { label = "Abbreviation 3", tab = "Snippets" }),
  text3 = UI.Text("{date}", {
    label = "Expands to ({date} is today's date)",
    tab = "Snippets",
  }),
})

local SHIFTED = { ["2"] = "@" }
local PUNCT =
  { Semicolon = ";", Slash = "/", Period = ".", Comma = ",", Minus = "-" }
local buffer = ""

local function snippets()
  local out = {}
  for n = 1, 3 do
    local abbr = cfg[`abbr{n}`]
    if abbr ~= "" then
      out[abbr] = cfg[`text{n}`]:gsub("{date}", os.date("%Y-%m-%d"))
    end
  end
  return out
end

local function typed(key)
  local mods = Input.GetModifiers()
  if mods.ctrl or mods.alt or mods.win then
    return nil
  end
  if mods.shift then
    return SHIFTED[key]
  end
  return PUNCT[key] or (if #key == 1 then key:lower() else nil)
end

local function expand(abbr, text)
  Run(function()
    for _ = 1, #abbr do
      HID.Press("Backspace", 10)
    end
    Clipboard.Set(text)
    HID.Press(if _REBIND.platform == "macos" then "LWin+V" else "LCtrl+V")
  end)
end

function OnDown(key)
  if key == cfg.trigger then
    for abbr, text in snippets() do
      if buffer:sub(-#abbr) == abbr then
        buffer = ""
        expand(abbr, text)
        return false
      end
    end
    return true
  end
  local char = typed(key)
  if char then
    buffer = (buffer .. char):sub(-30)
  elseif key == "Backspace" then
    buffer = buffer:sub(1, -2)
  elseif key == "Space" or key == "Enter" then
    buffer = ""
  end
  return true
end

3 files, 3.8 KB.