Difference between revisions of "Scripting"

From Freeplane - free mind mapping and knowledge management software
m (Text replacement - "<groovy>" to "<syntaxhighlight lang="Groovy" line>")
m (Text replacement - "</groovy> " to "</syntaxhighlight> ")
Line 148: Line 148:
 
<syntaxhighlight lang="Groovy" line>
 
<syntaxhighlight lang="Groovy" line>
 
// @ExecutionModes({ON_SINGLE_NODE})
 
// @ExecutionModes({ON_SINGLE_NODE})
</groovy>  
+
</syntaxhighlight>  
  
 
It's a good idea to put the "annotations" at the beginning of the script. (In section [[#Simple_text_replacement:_getIconName.groovy|Simple text replacement]] we will see an exception.) ON_SELECTED_NODE_RECURSIVELY applies a script on any node in the branch that has a selected node as root. You can also enable more than one mode by concatening them with commas:
 
It's a good idea to put the "annotations" at the beginning of the script. (In section [[#Simple_text_replacement:_getIconName.groovy|Simple text replacement]] we will see an exception.) ON_SELECTED_NODE_RECURSIVELY applies a script on any node in the branch that has a selected node as root. You can also enable more than one mode by concatening them with commas:
Line 154: Line 154:
 
<syntaxhighlight lang="Groovy" line>
 
<syntaxhighlight lang="Groovy" line>
 
// @ExecutionModes({ON_SELECTED_NODE, ON_SELECTED_NODE_RECURSIVELY})
 
// @ExecutionModes({ON_SELECTED_NODE, ON_SELECTED_NODE_RECURSIVELY})
</groovy>  
+
</syntaxhighlight>  
  
 
Note that for Groovy this is a comment. - This line is only interpreted by Freeplane. Omitting the <tt>//</tt> will result in a Groovy compilation error.  
 
Note that for Groovy this is a comment. - This line is only interpreted by Freeplane. Omitting the <tt>//</tt> will result in a Groovy compilation error.  
Line 175: Line 175:
 
node.icons.add("button_ok")
 
node.icons.add("button_ok")
 
// @ExecutionModes({ON_SELECTED_NODE})
 
// @ExecutionModes({ON_SELECTED_NODE})
</groovy>  
+
</syntaxhighlight>  
  
 
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 in this case. So let's remove this from the "Extra" menu:
 
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 in this case. So let's remove this from the "Extra" menu:
Line 182: Line 182:
 
// @ExecutionModes({ON_SELECTED_NODE, ON_SELECTED_NODE_RECURSIVELY})
 
// @ExecutionModes({ON_SELECTED_NODE, ON_SELECTED_NODE_RECURSIVELY})
 
node.icons.add("button_ok")
 
node.icons.add("button_ok")
</groovy>  
+
</syntaxhighlight>  
  
 
(To see the change in the menu you have to restart Freeplane.)
 
(To see the change in the menu you have to restart Freeplane.)
Line 192: Line 192:
 
if (node.text.toLowerCase().matches(".*\\b(yes|ok)\\b.*"))
 
if (node.text.toLowerCase().matches(".*\\b(yes|ok)\\b.*"))
 
     node.icons.add("button_ok")
 
     node.icons.add("button_ok")
</groovy>  
+
</syntaxhighlight>  
  
 
Note that <tt>node.text</tt> makes use of the special (compared to Java) attribute handling - see section [[#On_Groovy_properties_and_the_Scripting_API|On Groovy properties and the Scripting API]].
 
Note that <tt>node.text</tt> makes use of the special (compared to Java) attribute handling - see section [[#On_Groovy_properties_and_the_Scripting_API|On Groovy properties and the Scripting API]].
Line 210: Line 210:
 
<syntaxhighlight lang="Groovy" line>
 
<syntaxhighlight lang="Groovy" line>
 
c.statusInfo = "Icons: " + node.icons.icons
 
c.statusInfo = "Icons: " + node.icons.icons
</groovy>  
+
</syntaxhighlight>  
  
  
Line 219: Line 219:
 
<syntaxhighlight lang="Groovy" line>
 
<syntaxhighlight lang="Groovy" line>
 
= "Icons: " + node.icons.icons
 
= "Icons: " + node.icons.icons
</groovy>  
+
</syntaxhighlight>  
  
 
This will display the result of the formula instead of the formula itself.
 
This will display the result of the formula instead of the formula itself.
Line 236: Line 236:
 
node.object = 40
 
node.object = 40
 
def answer = node.to.num0 + 2
 
def answer = node.to.num0 + 2
</groovy>  
+
</syntaxhighlight>  
  
 
<syntaxhighlight lang="Groovy" line>
 
<syntaxhighlight lang="Groovy" line>
 
node.text = '2013-02-15'
 
node.text = '2013-02-15'
 
c.statusInfo = node.to.date + 1
 
c.statusInfo = node.to.date + 1
</groovy>  
+
</syntaxhighlight>  
  
 
<syntaxhighlight lang="Groovy" line>
 
<syntaxhighlight lang="Groovy" line>
 
node.object = 42
 
node.object = 42
 
node.format = '#.00'
 
node.format = '#.00'
</groovy>  
+
</syntaxhighlight>  
  
 
<syntaxhighlight lang="Groovy" line>
 
<syntaxhighlight lang="Groovy" line>
Line 263: Line 263:
 
<syntaxhighlight lang="Groovy" line>
 
<syntaxhighlight lang="Groovy" line>
 
c.statusInfo = node.parent.text
 
c.statusInfo = node.parent.text
</groovy>  
+
</syntaxhighlight>  
  
 
Other methods return node lists:
 
Other methods return node lists:
Line 280: Line 280:
 
def matches = c.find{ it.text.contains('ok') }
 
def matches = c.find{ it.text.contains('ok') }
 
c.statusInfo = matches.size() + " nodes contain 'ok'"
 
c.statusInfo = matches.size() + " nodes contain 'ok'"
</groovy>  
+
</syntaxhighlight>  
  
 
The method ''find'' has a closure argument which is applied to all nodes in the map. All nodes for which the closure returns ''true'' are returned as a new list which is assigned to the ''matches'' variable. In the closure the "current item" has a default name ''it''. As ''c.find'' iterates over nodes ''it'' is a Node that has the attribute ''text'' which is a String that has a method contains() returning true if ''OK'' is contained somewhere in the text, like in "grok" or "it's ok".
 
The method ''find'' has a closure argument which is applied to all nodes in the map. All nodes for which the closure returns ''true'' are returned as a new list which is assigned to the ''matches'' variable. In the closure the "current item" has a default name ''it''. As ''c.find'' iterates over nodes ''it'' is a Node that has the attribute ''text'' which is a String that has a method contains() returning true if ''OK'' is contained somewhere in the text, like in "grok" or "it's ok".
Line 388: Line 388:
 
assert node.getId() == node.id
 
assert node.getId() == node.id
 
println("ok")
 
println("ok")
</groovy>  
+
</syntaxhighlight>  
  
 
This will print "ok" into the logfile since the assertion is valid.  
 
This will print "ok" into the logfile since the assertion is valid.  
Line 396: Line 396:
 
node.text = "please note!"
 
node.text = "please note!"
 
println(node.text)
 
println(node.text)
</groovy>  
+
</syntaxhighlight>  
  
 
The second <tt>println</tt> will print the changed node text.
 
The second <tt>println</tt> will print the changed node text.
Line 403: Line 403:
 
<syntaxhighlight lang="Groovy" line>
 
<syntaxhighlight lang="Groovy" line>
 
c.statusInfo = "Icons: " + node.icons.icons
 
c.statusInfo = "Icons: " + node.icons.icons
</groovy>  
+
</syntaxhighlight>  
 
instead of
 
instead of
 
<syntaxhighlight lang="Groovy" line>
 
<syntaxhighlight lang="Groovy" line>
 
c.setStatusInfo("Icons: " + node.getIcons().getIcons())
 
c.setStatusInfo("Icons: " + node.getIcons().getIcons())
</groovy>  
+
</syntaxhighlight>  
  
 
The menu item ''Help -> Scripting API'' shows the attributes instead of get/set methods where possible and indicates if the attributes are read-only, read-write or write-only.
 
The menu item ''Help -> Scripting API'' shows the attributes instead of get/set methods where possible and indicates if the attributes are read-only, read-write or write-only.
Line 418: Line 418:
 
assert i == j
 
assert i == j
 
assert ! i.is(j)
 
assert ! i.is(j)
</groovy>  
+
</syntaxhighlight>  
  
 
==== Caveat  ====
 
==== Caveat  ====

Revision as of 11:03, 18 November 2018

Freeplane's builtin functionality can be extended by Groovy and JavaScript scripts. Starting with Freeplane 1.3.5_05 you can use many other languages, e.g Python. This page gives a first impression what you can do with Groovy scripting and helps to get started.

With Freeplane scripting you can

  • write your own functions and use them from the menu or via keyboard shortcuts,
  • use formulas in your map to compute stuff like in Excel, and
  • create add-ons to share it with other users,
  • have init scripts executed on startup that changes Freeplane's behavior (since Freeplane 1.5).

Most people use scripting to automate otherwise tedious procedures like creating a node with a special style and some standard attributes. But much more is possible with scripting.


External Groovy scripts can be integrated simply by placing them in the scripts subdirectory of the Freeplane homedir. Such scripts can be used like any other built-in function of Freeplane.

After some preparation we'll create the first script.

Preparation

A newly installed Freeplane installation is almost ready for scripting:

  • The scripts directory is created in the User Configuration Folder which you can open via Tools > Open user directory. It's empty, initially.
  • This directory is automatically searched for ".groovy" files on startup.
  • Scripting is disabled by default, but we'll fix that in a minute.

First 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 - no matter how many and which icons. But we'll need them later.


Select an editor

You will need a text editor. For the first steps presented on this page any editor will do, such as Notepad on Windows (though the free Notepad++is much better), Sublime Text or TextEdit on Mac OS X. You can find an overview of editors with Groovy support on Stackoverflow and on the Groovy website.

Freeplane also has a small script editor built into it. It is reached through Tools->Edit Script. You can run the scripts directly in the editor and store them as attributes of the node you are working in. But such map local scripts are most useful for quick tests since you can not write the scripts directly to ".groovy" files.

For ambitious scripting projects or if you have Java/Eclipse know-how you should have a look at the page on Scripting environment setup.


The first script: HelloWorld.groovy

"Hello World" is the traditional first program when taking up a programming language. Let's create a Groovy Freeplane version of it:

  • Create an empty Groovy script file named HelloWorld.groovy in your scripts directory (remember that you can get there via Tools > Open user directory). The suffix .groovy is mandatory.
  • Open HelloWorld.groovy in an appropriate editor as detailed above.
  • Copy the following script into the file and save it.
 1 node.text = "Hello World!"
 2 </groovy>
 3 * Now save your script in the editor and restart Freeplane since Freeplane will only find new scripts after a restart. Then you will find your new script in the Freeplane menu location ''Tools-&gt;Scripts-&gt;Hello World''. You see three sub menus ''Execute on one selected node'', ''Execute on all selected nodes'' and ''Execute on all selected nodes, recursively''. [Note: starting with FP version 1.5 there is no sub menu anymore. The execution mode is shown on mouse hover over the menu entry]
 4 * At ''Tools->Preferences->Plugins->Scripting''<!--
 5   --><ul><!--
 6   -->  <li> set ''Script execution enabled'' to ''Yes''</li><!--
 7   -->  <li> enable ''Permit File/Read Operations (NOT recommended)'' - despite the warning.<!--
 8   --></ul><!--
 9   -->These changes take effect without restarting Freeplane and only need to be done once. For more details see [[Scripting:_Security_considerations|Scripting: Security considerations]].
10 * Execute the script by selecting ''Tools-&gt;Scripts-&gt;Hello World-&gt;Execute on one selected node''. (Never mind the difference between the ''Execute ...'' variants; we'll come to that [[#Execution_modes|later]].)
11 * The text of the selected node will be changed to "Hello World!".
12 * To restore the original, press Ctrl-Z.
13 * If you like try the other "Execute..." menu items. Test the influence of selecting multiple nodes. Always press Ctrl-Z to revert the changes.
14 
15 == Hello Controller ==
16 
17 Every script is given the variables 
18 
19 <table border="1" style="background-color:#E0E0E0;">
20 <tr>
21 <td>'''node'''</td>
22 <td>set to the currently selected node</td>
23 <tr>
24 <td>'''c'''</td>
25 <td>tool box for various tasks relating to the map or Freeplane altogether</td>
26 </tr>
27 </table>
28 
29 These give access to the two most important bits of a map. In HelloWorld we used ''node'', which gave access to the selected node.
30 
31 Now we'll change HelloWorld.groovy to use the second, the Controller variable ''c'':
32 * Copy the following script into the file and save it:
33 <syntaxhighlight lang="Groovy" line>
34 c.statusInfo = "Hello World!"
35 </groovy>
36 * Execute the script by selecting ''Tools-&gt;Scripts-&gt;Hello World-&gt;Execute on one selected node''.
37 
38 The "Controller" manages the status bar. By assigning "Hello World!" to the Controller attribute "statusInfo" we are able to print text to the status bar.
39 
40 === The scripting API ===
41 The variables ''node'' and ''c'' are "objects" with a list of ''attributes'' (like "text", "details" or "style") and ''methods'' that operate on the object, like "addConnector()", "createChild()" or "moveTo()". The "type" of the object decides on the list of attribute of attributes and methods an object has. "node" is of type [http://freeplane.sourceforge.net/doc/api/org/freeplane/plugin/script/proxy/Proxy.NodeRO.html Proxy.Node] while "c" has the type [http://freeplane.sourceforge.net/doc/api/org/freeplane/plugin/script/proxy/Proxy.Controller.html Proxy.Controller].
42 
43 To get started with Freeplane scripting you have to get slowly accustomed to the Groovy syntax and the Freeplane specialities too. The types and objects that Freeplane supports are defined by [[Scripting_API|Freeplane's scripting API]]. You can learn it step by step: Very little is required to write useful scripts.
44 
45 An important resource is the built-in scripting documentation that is available via ''Help->Scripting API''. Open it now and search for the ''statusInfo'' attribute at ''Scripting API->Proxy->Controller->statusInfo: String (w)''. The text means: The Controller has an attribute ''statusInfo'' that only can be written to (''w''), that is you can't find out what is currently displayed on the status bar. The attribute has type ''String'' (either use "double quotes" or 'single quotes'). If you unfold the node you see ''void setStatusInfo(String)''. That means that
46 <syntaxhighlight lang="Groovy" line>
47 c.statusInfo = 'Hello World!'
48 </groovy>
49 and
50 <syntaxhighlight lang="Groovy" line>
51 c.setStatusInfo('Hello World!')
52 </groovy>
53 are equivalent. But the first "attribute" style is preferable since it is clearer. The clickable links in the "Scripting API" map carry to the respective location in the [http://freeplane.sourceforge.net/doc/api detailed API description] which might be a bit overwhelming at this point.
54 
55 
56 == Setting links ==
57 
58 In the "Scripting API" map, near to statusInfo you find the ''userDirectory'' attribute. You can use it to add a link to this directory to your map. Create a new script file ''addLink.groovy'' in the script directory with the following content:
59 <syntaxhighlight lang="Groovy" line>
60 node.link.file = c.userDirectory
61 </groovy>
62 
63 Here an slightly extended version that adds an ''external link'' to the selected node(s) and creates a node with a ''local link'' back to its parent node:
64 <syntaxhighlight lang="Groovy" line>
65 node.link.text = 'http://freeplane.org/wiki/index.php?title=Scripting'
66 </groovy>
67 
68 This script creates a ''local link'' back to its parent node:
69 <syntaxhighlight lang="Groovy" line>
70 node.link.node = node.parent
71 </groovy>
72 
73 In the next section we'll see what the "@ExecutionModes" line is about.
74 
75 == Execution modes  ==
76 
77 For each script we had three submenu entries of "Hello World". These entries are different with respect to multiple selected nodes: 
78 
79 *In the case of ''Execute on one selected node'' a script is executed only once no matter how many nodes are selected. It's best to be used when only a single node is selected since in this case the <tt>node</tt> variable of the script is set to the selected node. If multiple nodes are selected then <tt>node</tt> is set to one of the nodes arbitrarily. That is, you shouldn't count on the selection if multiple nodes are selected.
80 *With ''Execute on all selected nodes'' it is called once for each selected node (with <tt>node</tt> set to the respective node) and with 
81 *''Execute on all selected nodes, recursively'' the selection will be implicitly extended by all child trees of the selected nodes.
82 
83 If we chose ''Execute on all selected nodes'' for the first version of "Hello World" then the text of all selected nodes changed. - Probably what you expect. By adding the line
84 <syntaxhighlight lang="Groovy" line>
85 // @ExecutionModes({ON_SELECTED_NODE})
86 </groovy>
87 all other choices would be suppressed.
88 
89 The second "Hello World" version printed to the status bar. This only has to happen once so here ''Execute on one selected node'' is the right choice and we have to add the line 
90 
91 <syntaxhighlight lang="Groovy" line>
92 // @ExecutionModes({ON_SINGLE_NODE})

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.) ON_SELECTED_NODE_RECURSIVELY applies a script on any node in the branch that has a selected node as root. You can also enable more than one mode by concatening them with commas:

1 // @ExecutionModes({ON_SELECTED_NODE, ON_SELECTED_NODE_RECURSIVELY})

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

Menu locations

Scripts can determine to which menu or submenu a script will be added. Even the menu title can be set (although the standard file name to menu title translation should be enough in most cases):

 1 // @ExecutionModes({on_single_node="/menu_bar/help[scripting_api_generator_title]"})
 2 </groovy>
 3 
 4 You can find out about the internal menu keys using the [[Developer Tools/Menu item info|Add-ons#Add-on_Developer_Tools]].
 5 
 6 == Per node execution: addIcon.groovy  ==
 7 
 8 Now let's use the <tt>node</tt> variable again in our next script, <tt>addIcon.groovy</tt> (restart Freeplane to see it in the menu). This script will add the "button_ok" icon to any selected node:
 9 
10 <syntaxhighlight lang="Groovy" line>
11 node.icons.add("button_ok")
12 // @ExecutionModes({ON_SELECTED_NODE})

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 in this case. So let's remove this from the "Extra" menu:

1 // @ExecutionModes({ON_SELECTED_NODE, ON_SELECTED_NODE_RECURSIVELY})
2 node.icons.add("button_ok")

(To see the change in the menu you have to restart Freeplane.)

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

1 // @ExecutionModes({ON_SELECTED_NODE, ON_SELECTED_NODE_RECURSIVELY})
2 if (node.text.toLowerCase().matches(".*\\b(yes|ok)\\b.*"))
3     node.icons.add("button_ok")

Note that node.text makes use of the special (compared to Java) attribute handling - see section On Groovy properties and the Scripting API.


The status bar again: 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>

This scripts writes the icon names of the selected node to the status bar:

1 c.statusInfo = "Icons: " + node.icons.icons


Formulas

Starting with Freeplane 1.2 one use scripts as Formulas directly in the node core like in Excel. Type this formula in the node core:

1 = "Icons: " + node.icons.icons

This will display the result of the formula instead of the formula itself.

Notes:

  • The equal sign has to be the very first character in the script.
  • On typing the equal sign as the first character a special script editor pops up which supports syntax highlighting.


Data parsing and formatting

TODO: add text

1 node.object = 40
2 def answer = node.to.num0 + 2
1 node.text = '2013-02-15'
2 c.statusInfo = node.to.date + 1
1 node.object = 42
2 node.format = '#.00'
 1 c.statusInfo = format(42, '#.00').toString()
 2 </groovy>
 3 
 4 
 5 ==Navigation and iteration==
 6 
 7 Many useful scripts operate only on the current/selected node. But most scripts need to access multiple nodes. The scripting API provides methods for accessing special nodes:
 8 
 9 * node.parent - parent node
10 * node.map.root - root of the map
11 
12 For example this script prints the text of the parent node to the status bar:
13 <syntaxhighlight lang="Groovy" line>
14 c.statusInfo = node.parent.text

Other methods return node lists:

  • children - list of all children of a node, maybe empty
  • c.findAll() - all nodes of the map in breath first order
  • c.findDepthFirst() - all nodes of the map in depth first order
  • c.find(<closure>) - all nodes for which <closure> returns true.

The use of this methods requires some knowledge of Groovy collections.


Filtering

The most important concept is that of "closures", small code blocks that are used for filtering and modification of the element currently being iterated over. Let's start with filtering:

1 def matches = c.find{ it.text.contains('ok') }
2 c.statusInfo = matches.size() + " nodes contain 'ok'"

The method find has a closure argument which is applied to all nodes in the map. All nodes for which the closure returns true are returned as a new list which is assigned to the matches variable. In the closure the "current item" has a default name it. As c.find iterates over nodes it is a Node that has the attribute text which is a String that has a method contains() returning true if OK is contained somewhere in the text, like in "grok" or "it's ok".


Transformation

Many Groovy methods transform lists/collections into others:

 1 def squares = children.collect{ it.to.num0 * it.to.num0 }
 2 </groovy>
 3 
 4 and others transform lists into single values:
 5 
 6 <syntaxhighlight lang="Groovy" line>
 7 def sumOfSquares = children.sum(0){ it.to.num0 * it.to.num0 }
 8 </groovy>
 9 
10 When using ''sum()'' it's always a good idea to give it a start value since if the node had no children ''sumOfSquares'' would be ''null'' instead of ''0''.
11 
12 == Clones (since 1.5.5) ==
13 
14 There are several methods to create clones of nodes and to act on the clones of a node. Note that cloning works symmetrically so we could better speak of shared nodes instead of clone and cloned since none of both is privileged. However each clone or shared node has a unique nodeId and may or not (depending on the share mode) have its own child nodes.
15 
16 Add two clones of this node to the root node, one as single node, one including the branch starting at this node. Warning: before beta-1.5.5-pre03 appendAsCloneWithSubtree and appendAsCloneWithoutSubtree have reversed meaning!
17 <syntaxhighlight lang="Groovy" line>
18 def root = node.map.root
19 def lonelyClone = root.appendAsCloneWithoutSubtree(node)
20 def childWithSubtree = root.appendAsCloneWithSubtree(node)
21 // add nodes to the clones
22 lonelyClone.createChild('a child not shared')
23 childWithSubtree.createChild('a shared child')
24 </groovy>
25 
26 Mark a node with yellow background color if it has any clone:
27 <syntaxhighlight lang="Groovy" line>
28 if (node.getCountNodesSharingContent() > 0)
29     node.backgroundColorCode = '#ffff00'
30 </groovy>
31 
32 Mark all nodes of a map having any clone:
33 <syntaxhighlight lang="Groovy" line>
34 c.find{ it.getCountNodesSharingContent() > 0 }.each {
35     it.backgroundColorCode = '#ffff00'
36 }
37 </groovy>
38 If you should be interested in clones that share also the subtree (and not only the core properties) filter for countNodesSharingContentAndSubtree instead of countNodesSharingContent.
39 
40 Add a connector from node to all of its clones using property-access instead of method (nodesSharingContent instead of getNodesSharingContent()):
41 <syntaxhighlight lang="Groovy" line>
42 node.nodesSharingContent.each { node.addConnectorTo(it) }
43 </groovy>
44 
45 TODO: Tutorial ends here...
46 
47 == Appendix ==
48 
49 === Using external libraries ===
50 
51 Some libraries are [[Scripting:_Included_libraries|already included]], but almost all other available Java libraries can be used. Place them in the <tt>lib</tt> directory in the <freeplane_userdir> which is already included in the "Script classpath" (see also Tools->Preferences->Plugins). All .class files and the content of all .jar files are automatically available in scripts and formulas.
52 
53 Starting with Freeplane 1.3 [[Scripting:_Freeplane_Utility_Classes|utility scripts]] on the script classpath are compiled automatically.
54 
55 You can also create [[Your own utility script library|your own utility script library]].
56 
57 The add-on [http://freeplane.sourceforge.net/wiki/index.php/Add-ons_%28install%29#scriptlib '''scriptlib'''] contains some libraries you can load and install. They include some node operations missing in the scripting API, file operations and a method to play audio with a hidden player.
58 
59 === On Groovy  ===
60 
61 Although Groovy is more or less a superset of Java it would be a shame not to use the new opportunities Groovy provides. On the other hand there are notable differences between Groovy and Ruby. In this section some of the differences between Java, Groovy and Ruby will be listed. 
62 
63 ==== On iteration  ====
64 
65 Groovy provides much improved ways to work on collections of data. This helps a lot in Freeplane scripting since most of the time you are working with collection of <tt>Node</tt> instances. From Java you might be used to this pattern:
66 
67   // NEVER do that in Freeplane scripting!!!
68   for (i = 0; i < c.selecteds.size()-1; i++) {
69     aNode = c.selecteds[i]
70     aNode.text = "Do it groovy instead!"
71   }
72 
73 But this code is not even ineffective in Freeplane scripting (since every "c.selecteds" call creates a new list with new wrapped Node instances!) but it might even lead to errors since the list might change on the way. The following is better...
74 
75   // better, but still NOT GOOD
76   def selected = c.selecteds
77   for (i = 0; i < selected.size()-1; i++) {
78     def aNode = selected[i]
79     aNode.text = "Do it groovy instead!"
80   }
81 
82 Do yourself a favor and read this short [http://groovy-lang.org/Collections article on Groovy Collections]. Then you will see that the best way to do the same is
83 
84 <syntaxhighlight lang="Groovy" line>
85 // Good!
86 c.selecteds.each {
87   it.text = "That's groovy!"
88 }
89 </groovy>
90 c.selecteds is only evaluated once and there are no redundant variables and method calls.
91 
92 ==== On Groovy properties and the Scripting API  ====
93 
94 If an object, e.g. <tt>Node node</tt>, has a method <tt>getXyz()</tt> then groovy allows to use <tt>node.xyz</tt>. If it also has a proper <tt>setXyz()</tt> method (proper in the sense of the JavaBeans specification) then the property is writable. 
95 
96 Example of a read-only property: <syntaxhighlight lang="Groovy" line>
97 assert node.getId() == node.id
98 println("ok")

This will print "ok" into the logfile since the assertion is valid.

Example of a read-write property:

1 println(node.text)
2 node.text = "please note!"
3 println(node.text)

The second println will print the changed node text.

It's considered better style in Groovy if you use the properties instead of getters and setters. So better use

1 c.statusInfo = "Icons: " + node.icons.icons

instead of

1 c.setStatusInfo("Icons: " + node.getIcons().getIcons())

The menu item Help -> Scripting API shows the attributes instead of get/set methods where possible and indicates if the attributes are read-only, read-write or write-only.

The operator == means equals()

In Groovy the operator == is overridden to mean equals(). To check for identity use the method is():

1 Integer i = new Integer(3)
2 Integer j = new Integer(3)
3 assert i == j
4 assert ! i.is(j)

Caveat

Note that - unlike in Ruby - it's not allowed to omit the parens of a function without parameters in Groovy. So to get the number of children a node has, use node.children.size(), not node.children.size. The latter would be OK if java.util.List had a method getSize().


Wanted: Your participation!

It's very likely that scripting support 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.

What users say

Further reading

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 dig further into Groovy / Freeplane scripting:

  • For a list of all articles about Scripting click on "Category:Script" below.