Code samples (a function and a language toggling test to illustrate its use) for JavaScript for Automation actions.
(There was some suggestion earlier today that until Dan’s excellent Atom+Debugging script the reading or resetting of the active language in Script Editor documents had been a little obscure).
(function () {
'use strict';
// Returns the language of the supplied Script Editor Document
// If there is a third argument, then the language may be reset.
// Any string in the 3rd argument is interpreted as 'JavaScript'
// if it contains a 'j' or 'J', and as 'AppleScript' otherwise
// The first and 3rd arguments may have the value `undefined`
// scriptEditorDocLanguage :: Maybe Application (SE) ->
// Document -> Maybe String -> Language
function scriptEditorDocLanguage(appSE, oDoc, maybeStrNewLang) {
// Reference to running Script Editor app ? (supplied or created afresh)
var se = appSE || Application('Script Editor');
// Current language and its name string ?
var oLang = oDoc.language(),
strLang = oLang.name(),
// Name of new language ? (or existing if no specified change)
strNewLang = maybeStrNewLang ? (
maybeStrNewLang.toLowerCase()
.indexOf('j') !== -1 ? 'JavaScript' : 'AppleScript'
) : strLang;
// New language object (possibly updated) ?
return strLang !== strNewLang ? (
oDoc.language = se.languages.byName(
strNewLang
),
oDoc.language()
) : oLang;
}
// TOGGLE TEST - REQUIRES A SECOND SCRIPT EDITOR DOC TO BE OPEN
var se = Application('Script Editor');
// Toggle the language setting of the second Script Editor document
// (not this one :-)
if (se.documents.length > 1) {
var docSecond = se.documents[1];
return scriptEditorDocLanguage(
se,
docSecond,
(
scriptEditorDocLanguage(se, docSecond)
.name()
.toLowerCase()
.indexOf('j') !== -1 ? 'as' : 'js'
)
);
} else {
return 'Only one Script Editor document found';
}
})();