Categories
Uncategorized

A Tool for Copying HTML to the Clipboard

On my Mac I regularly use pbcopy and pbpaste to interact with the clipboard from the command line. Sometimes utilities output HTML formatted text. If this is piped into pbcopy it will be transferred as plain text. That means if I paste it into Word or gmail HTML sourcecode will be pasted. As both of these tools support rich text, it should be possible to paste the text as formatted text.

To this end I wrote a little macruby script that reads from STDIN and writes it to the clipboard declaring the type correctly. That way I can paste HTML generated by a utility and paste it into Word preserving the HTML formatting.

The script depends on macruby being available on the path and looks like this:

#!/usr/bin/env macruby
framework 'Cocoa'
 
def pbcopy(string)
    pasteBoard = NSPasteboard.generalPasteboard
    pasteBoard.declareTypes([NSHTMLPboardType], owner: nil)
    pasteBoard.setString(string, forType: NSHTMLPboardType) 
end 
 
s = STDIN.read
 
pbcopy(s)

The following incantation gets the contents of a markdown file as rich text into the clipboard:

pandoc readme.md | copy-html

Now pasting in gmail gives me a nicely formatted mail.

I would like to achieve a similar thing under Linux/ X11, but I haven’t managed so far. Perhaps someone has an idea.
Update: A similar effect can be achieved with osascript as shown here.

One reply on “A Tool for Copying HTML to the Clipboard”

JFYI: You get similar results using RTF as intermediate format with textutil, as pbcopy understands it:

pandoc README.md | textutil -format html -convert rtf -stdin -stdout | pbcopy

or as you already use pandoc you could leave out textutil and html entirely:

pandoc -s -t rtf README.md | pbcopy

Leave a Reply

Your email address will not be published. Required fields are marked *