UPDATED:
These examples were originally written in a pre-release version of the scripting API, and have now been updated to use the newer editor.selection.selectedItems property.
The native scripting language of TP3 is JavaScript, but you can run TP3 scripts either from AppleScript or (in Yosemite onwards) from JavaScript for Applications.
Each has its advantages:
- launching TP3 JS from AppleScript may allow you to work in a more familiar environment, continuing to use AppleScript for integration with other applications
- running it from JavaScript for Applications simplifies things a bit – just one language on the page, allowing proper syntax highlighting throughout while you are editing, and there is no need to escape special characters. (JS quoted within AppleScript needs a backslash before newlines and tabs, and requires care with the use of single and double quote marks)
( for bigger or more complex scripts, JavaScript for Applications, from El Capitan onwards, also gives you the use of Safari’s powerful JavaScript debugger, which does make it a lot easier to see exactly what is going on )
For reference, here is a translation, from AppleScript into JavaScript for Applications, of the Getting Started AppleScript example at https://jessegrosjean.gitbooks.io/taskpaper/content/scripting.html
Original AppleScript version, running in Script Editor:
Running the same TP3 code from JavaScript for Applications:
(The language selector at top left of Script Editor has been set to JavaScript)
JavaScript also lets us work through the items of a list with .forEach()
(dropping some of the fiddlier details)
or, simplest of all, just translate one kind of list straight into another, with .map()
Code samples:
From AppleScript:
tell front document of application "TaskPaper"
evaluate script "function(editor, options) {
var items = editor.selection.selectedItems;
var itemStrings = [];
for (var i = 0; i < items.length; i++) {
itemStrings.push(items[i].bodyString);
}
return itemStrings;
}"
end tell
From JavaScript for Applications (JXA):
function TaskPaperContext(editor, options) {
var items = editor.selection.selectedItems;
var itemStrings = [];
for (var i = 0; i < items.length; i++) {
itemStrings.push(items[i].bodyString);
}
return itemStrings;
}
Application("TaskPaper").documents[0].evaluate({
script: TaskPaperContext.toString()
})
from JXA using .forEach()
function TaskPaperContext(editor, options) {
var itemStrings = [];
editor.selection.selectedItems.forEach(
function (item) {
itemStrings.push(item.bodyString)
}
);
return itemStrings;
}
Application("TaskPaper").documents[0].evaluate({
script: TaskPaperContext.toString()
});
and finally, from JXA using ‘.map()’
function TaskPaperContext(editor, options) {
return editor.selection.selectedItems.map(
function (item) {
return item.bodyString;
}
);
}
Application("TaskPaper").documents[0].evaluate({
script: TaskPaperContext.toString()
})