/ coding

Mac OS X Yosemite JavaScript automation: TextEdit

This is simply a review of some of the JavaScript automation covered in the WWDC 2014 video on Mac OS X Yosemite’s new ability to automate using JavaScript (search the WWDC 2014 page for “JavaScript for Automation”).

The WWDC video was made before the Yosemite was officially released, so some interface elements have moved around in the output area of Script Editor. But everything should be findable.

Putting text into a blank document

TextEdit = Application(‘TextEdit’);

doc = TextEdit.documents[‘Log’];

doc.text = ‘I love JavaScript’;

doc.text.font = ‘Menlo Regular’;
doc.text.size = ’40’;
doc.text.color = ‘blue’;


doc = TextEdit.documents[‘Log’]; gets an existing TextEdit file titled ‘Log’. It seems that Log.txt needs to be saved in the iCloud TextEdit folder to work. No mention of this was made in the video and it was a real head-scratcher for me.

It’s also worth noting that this script will rewrite all text in the document, so you can run the script ten times, but there will only ever be one instance of the string (in this case, “I love JavaScript”) showing.

Appending text to a document using a function

function log(message, format) {

    TextEdit = Application(‘TextEdit’);

    doc = TextEdit.documents[‘Log’];
    doc.paragraphs.last = doc.paragraphs.last() + ‘\n’ + message;

    doc.paragraphs.last.properties = format || {
        font: ‘Menlo Regular’,
        size: ’40’,
        color: ‘blue’

log(‘I love functions’, {color: ‘red’});
log(‘Me too’, {color:’brown’, font: ‘Helvetica’});
log(‘I love default formatting’);


doc.paragraphs.last() is where we append the next text.

You can compare this to doc.text = ‘string’ from the first example, which overwrites all document text.

These are just a couple of basic examples from the WWDC video. It’s worth watching the video itself to get a good overview of what’s possible because it get much better than the examples here.

Mac OS X Yosemite JavaScript automation: TextEdit
Share this