05-03-26

Smart Paste: Strip Formatting with Lua

This Lua script for Rebind hardware input strips formatting from your clipboard before pasting. It removes HTML tags, ANSI codes, and normalizes whitespace, providing clean text. Customize the filters

rebindlua scriptsmart pasteclipboardformattingstrip htmlremove ansi

Question

Smart paste: strip formatting before pasting

Rebind AI

luau
-- rebind: name=Smart Paste (Strip Formatting)

local cfg = UI.Schema({
    trigger = UI.Keybind("F9", { label = "Paste Key" }),
    strip_html = UI.Toggle(true, { label = "Remove HTML Tags" }),
    strip_ansi = UI.Toggle(true, { label = "Remove ANSI Codes" }),
    normalize_ws = UI.Toggle(true, { label = "Normalize Whitespace" }),
})

local function stripFormatting(text)
    if cfg.strip_html then
        -- remove HTML tags
        text = Regex.ReplaceAll(text, [[<[^>]+>]], "")
        -- decode common HTML entities
        text = text:gsub("&nbsp;", " "):gsub("&lt;", "<"):gsub("&gt;", ">"):gsub("&amp;", "&"):gsub("&quot;", '"'):gsub("&#39;", "'")
    end

    if cfg.strip_ansi then
        -- remove ANSI escape codes
        text = Regex.ReplaceAll(text, [[\x1b\[[0-9;]*m]], "")
    end

    if cfg.normalize_ws then
        -- collapse multiple spaces/tabs into single space
        text = Regex.ReplaceAll(text, [[\s+]], " ")
        -- trim leading/trailing whitespace
        text = text:match("^%s*(.-)%s*$") or text
    end

    return text
end

Bind(cfg.trigger, Async(function()
    local raw = Clipboard.Get()
    if not raw then
        UI.Notify("Clipboard empty", "warning")
        return false
    end

    local clean = stripFormatting(raw)
    Clipboard.Set(clean)
    HID.Press("LCtrl+V")

    return false
end))

How it works:

  1. HTML stripping – Removes <tags> and decodes HTML entities like &nbsp;, &amp;, &quot;
  2. ANSI codes – Strips terminal color/formatting codes (e.g., \x1b[31m)
  3. Whitespace normalization – Collapses multiple spaces/tabs and trims edges

Press the hotkey to grab clipboard, strip formatting, and paste the clean result.

Examples:

  • "<p>Hello&nbsp;&nbsp;World</p>""Hello World"
  • "\x1b[31mRed text\x1b[0m""Red text"
  • "Line 1 Line 2""Line 1 Line 2"

Customize which filters are active via the UI toggles.

Learn more: