Cut & Paste Rich Text with Pandoc and Markdown

I love the plain-text goodness of Markdown for taking notes and writing documentation. Most of the tooling in my world plays nicely with it and so almost all is well. GitHub will render Markdown READMEs and other documents handsomely. Heck, they even provide rendered diffs!

But there is one edge case, a fly in the plain-text ointment, that comes up from time to time. Some input fields on websites expect to be given rich text. Let's say that I have the following document in markdown:

# My Document

Documents should have bullet points!

- This is most important
- This is also important
- Lists have to have three things

And I want to paste it into, oh let's say Basecamp. If I did the naive thing from the command line: pbcopy <, I'd end up with all the pound signs and asterisk bullets directly in the Basecamp document — not at all what I wanted.

Enter stage left: Pandoc. Pandoc is an extremely handy document conversion tool (sotto voce: written in Haskell) that can convert tons of formats into tons of other formats. Here we'll use it to convert our Markdown source into RTF, which OS X understands as rich text, ready to be pasted into text fields. This is the command to create a standalone RTF document from Markdown:

pandoc --standalone --from=markdown --to=rtf --output=my_doc.rtf

It looks like this:

a sample rich text document

But for the purposes of cut'n paste, we can skip the detour into an RTF file. What I do is simply send the output of that command to standard out, and then pipe that into pbcopy, OS X's nice command line clipboard tool.

pandoc --standalone --from=markdown --to=rtf --output=- | pbcopy

And that's it! The rich text is now sitting comfortably in the clipboard waiting to be pasted into a text field. To make this nicer to use, you can define a function that does the needed argument schlepping:

md2rt() {
  pandoc --standalone --from=markdown --to=rtf --output=- "$1" | pbcopy

This function can then be called like: md2rt

Happy rich-texting!

Category: Development