Copying Rich Text to the Clipboard from the Command Line on Mac

Posted on

A colleague recently shared some code to copy plain text Org Mode markup to the clipboard, such that the formatting would be properly represented when pasting in other applications. The idea is you can draft some text in Org (or another markup like Markdown) and then paste it into rich text fields in your web browser or other application.

However, their solution used xclip, which wouldn’t work for me on a Mac. There are some solutions1, 2 that use pbcopy as an alternative, however I found that it didn’t work with Firefox or Slack. I could paste the formatted text into Chrome, but nothing would happen when I tried to paste in these other applications.

After some research I found this was because pbcopy only populates the RTF attribute of the clipboard, it doesn’t set the text attribute3. Some applications seem to require this, even if it’s just a blank string.

I couldn’t find a way to have pbcopy populate this, but found Apple Script could. After a lot of help from Stack Overflow answers I found the proper Apple Script syntax and came up with this:

echo "<b>bolded text</b>" |\
hexdump -ve '1/1 "%.2x"' |\
xargs printf "set the clipboard to {text:\" \", «class HTML»:«data HTML%s»}" |\
osascript -

In addition to adding the HTML content (in hex) to the clipboard, it sets the text attribute to a single space, which fixes issues with applications like Firefox and Slack.

  1. From Markdown To Pastable Formatted Text In OS X Terminal ↩︎

  2. Ox Clip for Org Mode - I plan to open an issue for this ↩︎

  3. This may not be the proper terminology. ↩︎