Welcome! Share code as fast as possible.

local pastePlainMenu = hs.menubar.new()
local log = hs.logger.new('PastePlainNative','debug')

if pastePlainMenu then
    local iconImage = hs.image.imageFromName("doc.on.clipboard.fill")

    if iconImage then
        pastePlainMenu:setIcon(iconImage)
    else
        pastePlainMenu:setTitle("📋")
        log.wf("SF Symbol 'doc.on.clipboard.fill' not found. Using text title.")
    end

    pastePlainMenu:setTooltip("Paste as Plain Text (Native Clipboard)")

    pastePlainMenu:setClickCallback(function()
        local plainText = hs.pasteboard.readString()

        if plainText and #plainText > 0 then
            local originalClipboardContents = hs.pasteboard.readAllData()
            if not originalClipboardContents then
                log.w("Could not read original full clipboard data.")
            end

            hs.pasteboard.clearContents()
            local success = hs.pasteboard.writeObjects(plainText)

            if not success then
                log.ef("Failed to write plain text to clipboard.")
                hs.notify.show("Paste Plain Error", "Could not write to clipboard", "Hammerspoon")
                if originalClipboardContents then
                    hs.pasteboard.clearContents()
                    hs.pasteboard.writeAllData(originalClipboardContents)
                    log.i("Original clipboard (potentially) restored after write failure.")
                end
                return
            end

            log.i("Plain text written to clipboard.")

            hs.eventtap.keyStroke({"cmd"}, "v")
            hs.notify.show("Pasted Plain", "", "Hammerspoon")
            log.i("Paste Plain: Triggered Cmd+V after clipboard modification.")

            if originalClipboardContents then
                hs.timer.doAfter(0.2, function()
                    hs.pasteboard.clearContents()
                    hs.pasteboard.writeAllData(originalClipboardContents)
                    log.i("Original clipboard content restored.")
                end)
            else
                log.w("No original clipboard data to restore.")
            end

        else
            log.i("Clipboard is empty or does not contain text.")
            hs.notify.show("Paste Plain", "Clipboard empty or no text", "Hammerspoon")
        end
    end)

else
    log.ef("Paste Plain: Could not create menubar item.")
end