Prev Up Next
User Scripting User Scripting The Example Scripts

Introduction

Safe and Advanced Scripts

As mentioned above user scripts in Sketch can cause data loss. To make things easier for you in this regard, Sketch supports two kinds of user scripts, safe scripts and advanced scripts.

Safe scripts take care of undo handling for you and they restrict what your script can actually do to keep you from harm. The disadvantage of this approach is that you can't do everything you might want to do with a safe script.

The advanced script has no restrictions but it has to take care of undo handling itself, which isn't difficult but has to be done with care.

The Script Function

Regardless of whether a script is a safe script or an advanced script it is just a Python function that accepts a context object as parameter. The context is an instance with three attributes:

document

The document for which the script was called.

The document contains all objects that make up the drawing and it manages the selection.

application

The application object.

The application object has methods for setting and retrieving the application's clipboard and to popup message boxes and file dialogs.

main_window

The top-level window containing the canvas widget that shows the current drawing. It has methods for loading and saving documents, among others.

A simple 'hello world' type script might look like this:
def hello_world(context):
    context.application.MessageBox(title = "My Script", 
                                   message = "Hello World!")

Registering Scripts

The Script menu just shows all the scripts in the script registry, so to have a script appear in that menu, you have to put it into the registry.

The registry is managed in a subpackage Scripting of the toplevel package Sketch. The function needed here is AddFunction and is called like this:

AddFunction(name, title, function)

name

is a name for that script. This name should be unique, as the scripts are identified in the registry by this name. It doesn't have to be the same as the function name.

title

The text of the menu entry.

function

the function that implements the script, e.g. hello_world above.

There are a few optional keyword arguments, one of which is type. The value of script_type must be either SafeScript (the default) or AdvancedScript. Both values are defined in the Scripting subpackage. The registry functions are covered in more detail in the script registry section.

As an