0

I am looking for a solution to auto convert rich-text copied to clipboard (pasteboard) to plain text one in Hammerspoon (lua code).

I know how to access the pasteboard in lua but no idea on how to bind this action to the copy or paste event in order to automate it (neither on how to convert content to plain text).

local pasteboard = require("hs.pasteboard")
sorin
  • 161,544
  • 178
  • 535
  • 806

1 Answers1

1

The easiest method would be to just use the answer described here to fetch the RTF data in the pasteboard and pipe the data to the already available textutil command to convert it to plain text to stdout:

osascript -e 'the clipboard as «class RTF »' | \
    perl -ne 'print chr foreach unpack("C*",pack("H*",substr($_,11,-3)))' | \
    textutil -stdin -stdout -convert txt

We can then in the Hammerspoon environment use hs.execute to run the shell command and return the converted value, so in your Lua code it's as simple as:

local text = hs.execute([[
    osascript -e 'the clipboard as «class RTF »' | \
        perl -ne 'print chr foreach unpack("C*",pack("H*",substr($_,11,-3)))' | \
        textutil -stdin -stdout -convert txt
]])

FYI the Hammerspoon API does allow you to retrive RTF data from the pasteboard using hs.pasteboard.readDataForUTI using the "public.rtf" UTI, so technically you could do all this in Lua, but you would have to manually convert the RTF data yourself.

andrewk
  • 381
  • 2
  • 5
  • So, AppleScript, into a Perl script, into a shell program, into Lua. Interesting. You most surely don’t need the Perl or `textutil` if you just read `the clipboard as text`. But, as you said, you probably don’t need the AppleScript. I imagine if one copies some rich text and then looked at the available content types using `hs.pasteboard.contentTypes()`, that if `"public.rtf"` is among them, then `"public.plain-text"` will probably be too,, so you should just read the data for *that* UTI. I think the entire solution is gonna just be `hs.pasteboard.readDataForUTI("public.plain-text")`. – CJK Oct 15 '19 at 09:54
  • As a side note, if you’re going to run an AppleScript with Lua, it’s probably best to use the `hs.osascript` functions rather than `hs.execute`. The goal shouldn’t be to use as many different programs and languages as one can chain together, because it gets pretty costly fairly easily, and slows stuff down. – CJK Oct 15 '19 at 10:05