How to get Automator to treat text as RTF

applescriptautomatorservices

I am writing a book and trying to add a service to provide syntax highlighting to text selected in Pages with Automator. I have a service accepts selected text and runs it through a shell command (pygmentize) which converts it to syntax highlighted RTF.

The problem is that when the text is returned, Automator treats it as plain text and I get gibberish back. I've tried changing the accepts back and forth between rich and plain and it doesn't make any difference. I've tried piping the output through textutil to no avail.

My only work around for now is to have the shell command copy to the clipboard with pbcopy and then use an Automator to grab the contents of the clipboard. I'd rather find a way to do this without having to wipe the clipboard, any suggestions for getting Automator to treat my shell commands output as rich text?

Is there anyway to make this work with AppleScript?

Best Answer

I usually use scripts like this instead of Automator services:

try
    set old to the clipboard as record
end try
tell application "System Events" to keystroke "c" using command down
do shell script "export LC_CTYPE=UTF-8; pbpaste | /usr/local/bin/pygmentize -g -f rtf | pbcopy"
tell application "System Events" to keystroke "v" using command down
delay 0.05
try
    set the clipboard to old
end try
  • If the clipboard is empty, trying to get it results in an error.
  • pbpaste and pbcopy use ASCII if the locale variables are unset. I couldn't get pygmentize -f rtf to work with non-ASCII characters though.
  • Without the delay set the clipboard to old would sometimes be run before the text would get pasted.