March 03, 2016

Script to Paste Clipboard with Specific Font

A friend asked about a script to copy selected text and paste it into Word in a specified font face. My mind explodes with all the different ways, technologies one could do this with—Applescript, Automator, VBA within Word, and launcher/macro programs like KeyboardMaestro and Quicksilver.

Let's say you found the relevant text or from a PDF or website or in Accordance and you want to copy and paste it into your Word document, but you want to specify the font because it's a different language than your other normal text.*

I'd like to illuminate one little trick I learned some time ago that can be incorporated into several of those. Namely, you can use the command line textual tool to markup the text with the much-maligned HTML tag and then copy it to the clipboard converting the HTML text to styled text. The syntax for the line is:
echo '<i>I am some italicized text</i>' | textutil -format html -convert rtf -stdin -stdout | pbcopy -Prefer rtf
I normally would wrap that into a script which grabs the text and then pastes it wherever I want it. Here's an example of a script, which copies the selected text in the front app, then reads the clipboard into variable, adds a tag to the text of the variable, then copies that newly-styled text back onto the clipboard, and then brings Word to the front, and pastes the directly formatted text.

-- copy the text
tell application "System Events"
keystroke "c" using {command down}
end tell
delay 0.1
set myText to the clipboard
delay 0.1

-- add HTML style data to the text
set myText to "<font face=\"SBL BibLit\" size=3>" & myText"</font>"

-- convert the styled html text as styled text on the clipboard
do shell script "echo " & quoted form of myText & ¬
" | textutil -format html -convert rtf -stdin -stdout | pbcopy -Prefer rtf"

-- paste the newly styled keyboard into an app
tell application "Microsoft Word"
tell application "System Events"
keystroke "v" using {command down}
end tell

end tell

You could, of course, convert much of this script into Automator or other macro environment.

Another way of accomplishing this for Word would be to have the script set the Font info for the current selection point in Word, strip any style data from the clipboard, then Paste and Match Style the text into Word.

* Note: I would suggest that the best practice for writing in Word is to use Styles to format the document, not direct formatting. You could have a script environment that pasted a text and then selected that text and then set the style for that text using VBA or Applescript.