Scripting

From Freeplane - free mind mapping and knowledge management software
Revision as of 23:31, 19 January 2010 by Boercher (talk | contribs) (Overview / Entry into the scripting documentation)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Freeplane's builtin functionality can be extended by Groovy scripts:

  • Groovy scripts can access the mindmap by means of a Scripting API.
  • Scripts can use some Freeplane utility classes that are provided by Freeplane, e.g. UITools, LogTool or HtmlTools.
  • Scripts can use more or less every functionality that those libraries provide that are included in freemind.

Scripts can be defined in three ways:

  • External Groovy scripts can be integrated simply by telling Freeplane where they are. Such scripts can be used like any other builtin function of Freeplane.
  • Patterns may contain scripts for formatting purposes. They are automatically applied to any node with the given pattern assigned.
  • Map local scripts may be defined within a map as attributes of some node. These scripts are embedded within a map and can be easily shipped with a map. A special, builtin editor is used for script editing.

Getting started: sumNodes.groovy

Let's get started with our first script. In the end it will sum up the numerical values of all selected nodes. We'll define it in a separate file so we can use it like a builtin function in all maps.

Preparation

Create a new mindmap with this content (just copy 'n paste it into a new map):

test
  numbers
    1
    2
    3
  text
  text
  text ok
  text okay

Then add some icons to the map.

Create a script and integrate it into Freeplane

You can start with scripting without any prior download of additional software. (Although a proper programming editor might help to get you started.)

  1. Create an empty Groovy script file with an expressive name, e.g. sumNodes.groovy. The suffix .groovy is mandatory.
  2. Create the directory ~/.freeplane/scripts (Unix) or %USERPROFILE%\.freeplane\scripts if it doesn't exist yet.
  3. Place sumNodes.groovy into the new directory.
  4. Start Freeplane and find your new script in the menu location Extras/Scripts/SumNodes. You see three sub menus Execute on one selected node, Execute on all selected nodes and Execute on all selected nodes, recursively.
  5. Execute the script by selecting Extras/Scripts/SumNodes/Execute on one selected node. (Never mind the difference between the Execute ... variants; we'll come to that later.)

Nothing happens. - That' not unexpected, right? The script is empty yet and doesn't do anything. So let's add some action in the next section.

First steps in Groovy

First, open sumNodes.groovy in an editor that you are most comfortable with. Of course it would be helpful if the editor understands groovy or at least knows about parens not closed. The Groovy Console might be a good choice to get started.

sumNodes.goovy shall sum the numerical values of all selected nodes. So we have to iterate over the selected nodes. We have to look up the API on how to get a list of the selected nodes and find, under interface Controller the method List<Node> getSelecteds(). On the top of this page it is stated that every script is given the variables

<groovy> final Proxy.Node node; final Proxy.Controller c; </groovy>

We conclude, that c.getSelecteds() will return a list of selected nodes. Let's try and just put that into the script:

<groovy> println c.getSelecteds() </groovy>

Again nothing happens. Why that?

The reason is that all print output goes into the logfile. So open it, either ~/.freeplane/log.0 (Unix) or %USERPROFILE%\.freeplane\log.0. Note: if you have multiple instances of Freeplane opened than there will be more than one logfile. Find the one that was changed last, then. The logfile should contain a line like this:

 STDOUT: [org.freeplane.plugin.script.proxy.NodeProxy@1f0174fc]

showing that only one node was selected and that its type is NodeProxy. The API of NodeProxy is described in the API, too.

Getting started with Lists

Lookup how to deal with Lists in Groovy here. Skim through the article and search for sum. This method sums over all List elements. Note the argument of the sum method: It often uses the token it which stands for the list element in which cases braces {} instead of parens () are used. These parts in braces are program fragments, so called blocks.

Now let's use sum and change the content of test.groovy to

<groovy> println c.getSelecteds().sum{it.getText()} </groovy>

The argument of sum is a block, that extracts the text content from NodeProxy (you will find this method in the API).

Then select the nodes "1", "2" and "3", execute the script again via the menu and look in the logfile again:

 STDOUT: 123

That's sort of a sum but possibly not the expected: It's a concatenation of all node's text but not the sum of the numbers.

Numbers

To take the numerical sum it's necessary to convert the string into a number. Therefore we define a new method within the script:

<groovy> def doubleValue(String text) {

   text.isDouble() ? text.toDouble() : 0

} println c.getSelecteds().sum{doubleValue(it.getText())} </groovy>

Now we have

 STDOUT: 6.0

in the log. By checking if a node has a numerical text content (text.isDouble()) we don't have to care for selected nodes with non-numerical content. (Try what happens if you erase this check and execute the script with the root node ("test") selected!)

Getting interactive

Printing results into the logfile isn't very comfortable. Let's show them in an popup window. Therefore we will use a utility class that is part of Freemind, UITools. We will need these methods:

<groovy> void informationMessage(Frame frame, String message, String title); void Frame getFrame(); </groovy>

The final script looks like this:

<groovy> // @ExecutionModes({ON_SINGLE_NODE}) import java.text.NumberFormat; import org.freeplane.core.ui.components.UITools;

def doubleValue(String text) {

   text.isDouble() ? text.toDouble() : 0

}

sum = c.selecteds.sum{doubleValue(it.text)} sumFormatted = NumberFormat.getInstance().format(sum) UITools.informationMessage(UITools.getFrame(), sumFormatted, "Sum") </groovy>

In the next section we'll see what the "@ExecutionModes" line is about.

Execution modes

In the beginning we had three submenu entries for "SumNodes". These entries are different with respect to multiple selected nodes:

  • In the case of Execute on one selected node a script is executed once no matter how many nodes are selected. Its node variable is set to an arbitrarily chosen node within the selection.
  • With Execute on all selected nodes it is called once for each selected node (with node set to the respective node) and with * Execute on all selected nodes, recursively the selection will be implicitely extended by all child trees of the selected nodes.

If we would choose Execute on all selected nodes for "SumNodes" then one dialog box would pop up for each selected node. - This clearly would not be intended. By adding the line

<groovy> // @ExecutionModes({ON_SINGLE_NODE}) </groovy>

only one menu entry survives for "SumNodes". It's a good idea to put the "annotations" at the beginning of the script. (In section Simple text replacement we will see an exception.) To get the opposite effect, i.e. to exclude the Execute on one selected node we would have to write:

<groovy> // @ExecutionModes({ON_SELECTED_NODE, ON_SELECTED_NODE_RECURSIVELY}) </groovy>

Note that for Groovy this is a comment. - This line is only interpreted by Freeplane. Omitting the '//' will result in a Groovy compilation error.

Caching policy

As soon as you have fixed all typo and other bugs in a script you can tell Freeplane that's safe to cache its content by adding this line to a script:

<groovy> // @CacheScriptContent(true) </groovy>

The only reasons not to have it in a script are:

  • You are not done with debugging and you don't want to restart Freeplane after each little change of a script.
  • Laziness: You have the impression that caching has a minor impact on the execution times of a script.
  • Memory concerns: The script is really large (many, many KB) and you don't want Freeplane to keep it in the memory. (Note that a script is only loaded on its first invocation.)

Per node execution: addIcon.groovy

The script in the previous section was working on the selected nodes but it fetched them from the controller (Variable c). It didn't make use of the node variable. Let's use this variable now in our next script, addIcon.groovy. This script shall add the "button_ok" icon to any selected node. Since the node variable references one selected node we don't have to navigate to them via the controller and we don't have to iterate over them:

<groovy> node.getIcons().addIcon("button_ok") </groovy>

This will add the "check" icon to each selected node. Hopefully it's clear that the execution mode Execute on one selected node makes no sense for this script. So let's remove this from the "Extra" menu:

<groovy> // @ExecutionModes({ON_SELECTED_NODE, ON_SELECTED_NODE_RECURSIVELY}) node.getIcons().addIcon("button_ok") </groovy>

We will extend this script a little further to only set the icon if the node text contains the words "yes" or "OK" (case insensitively):

<groovy> // @ExecutionModes({ON_SELECTED_NODE, ON_SELECTED_NODE_RECURSIVELY}) if (node.text.toLowerCase().matches(".*\\b(yes|ok)\\b.*"))

   node.getIcons().addIcon("button_ok")

</groovy>

One word about the node.text. This makes use of the special (compared to Java) property handling. If an object (here NodeProxy node) has a method getXyz() then groovy allows to use node.xyz. If it also has a proper setXyz() method (proper in the sense of the JavaBeans specification) then the property is writable.

Simple text replacement: getIconName.groovy

Finding the proper name of an icon may be a bit difficult. One way is to use the wanted icon in some map and to look it up in the sources. The XML for a node with an icon might look like that:

 <node TEXT="done" ID="ID_789648746" CREATED="1239285242562" MODIFIED="1242658193277">
   <icon BUILTIN="button_ok"/>
 </node>

Let's do it with a simple script:

<groovy> = "Icons: " + node.getIcons().getIcons() </groovy>

This script simply replaces the content of the selected nodes, so after applying it you will want to perform an Undo operation (Cntr-z or via the toolbar). In order not to change too many nodes we should limit the execution to non-recursive mode only. Also the text should doesn't need to be changed if a node has no icon. Here's the improved version:

<groovy> = node.getIcons().getIcons().isEmpty() ?

  node.text : "Icons: " + node.getIcons().getIcons()

// @ExecutionModes({ON_SELECTED_NODE}) </groovy>

Notes:

  • We have to use the ternary operator (boolean) ? (if-value) : (else-value), since an if-statement returns no value).
  • The equal sign has to be the very first character in the script. That's why the @ExecutionModes line is at the bottom of the script.
  • The most important use case for "=" scripts are patterns where the text replacement is only performed for the display while keeping the node's text untouched.

Adding attributes

There's a second special case beside simple text replacement: Addition of node attributes. This will happen if the beginning of the script matches the pattern ^[a-zA-Z0-9_]+=. Let's revise our script of the last section a bit:

<groovy> icons=node.getIcons().getIcons().toString() // @ExecutionModes({ON_SELECTED_NODE}) </groovy>

And lastly a funny example: a script that adds a script to a map:

<groovy> script0= "import org.freeplane.core.ui.components.UITools;\n" + "UITools.errorMessage(\"oops, defined a completly useless script\")\n" + "// @ExecutionModes({ON_SINGLE_NODE})" </groovy>

Map local scripts can be defined as node attributes with name script0, script1, .... Execute the script via Extras/Scripts/Execute all scripts.

Conclusion

This guide should have given you a quick overview over what can be done with scripts in Freeplane. Of course we have only scratched the surface. Here are some suggestions to digg further into Groovy / Freeplane scripting:

Your participation is required!

Scripting support in Freeplane is still a pretty new feature. It's very likely that it's lacking some functionality that would be useful for a large number of users. For this reason you are strongly encouraged to give feedback on issues you are having with scripting and on things you are missing.