Generate Rich Text in AppleScripts and Shell Scripts

Normally, AppleScript absolutely mangles rich text once it comes in to the system. I have recently discovered a workaround for this, which is the “pbcopy” terminal command. Anything piped to this command will be copied to the clipboard. Normally, this is done only as plain text, but if the incoming data is rich text (has an RTF header), it will come in as rich text. The second part of this is the use of the “textutil” command, which can take text of various formats and output them in, among other formats, rich text. Now, even if you’re limited to only plain text (as in AppleScript), textutil will happily accept HTML, so if you can generate formatted HTML, you can pipe it through textutil and end up with lovely rich text in your clipboard, and it even retains links!

So from the shell, your command is something like:

% echo [html text] | textutil -stdin -stdout -format html -convert rtf | pbcopy

Just make sure that your HTML text is properly escaped.

If you want to do this from AppleScript, you can simply encapsulate the whole thing in a “do shell script” command.

BONUS: You can also put Markdown or MultiMarkdown in the mix to take Markdown-formatted content and convert it to rich text on the clipboard. The following is an example of how this would work with MultiMarkdown:

% echo [markdown text] | mmd | textutil -stdin -stdout -format html -convert rtf | pbcopy

Twitter, Facebook

Written on January 27, 2012