Groovy script custom tool

jaap-karssenberg edited this page Oct 25, 2013 · 2 revisions
Clone this wiki locally

Hi, I've created a little Groovy script which allows you to execute arbitrary Groovy code from within a zim page. Basically it parses the zim page and executes every line starting with '$'. The result is stored in a subsequent line starting with '->'.

It can be used like the arithmetic plugin but it can be used to define functions and execute much more advanced code. Please have a look at the examples to decide if this may be interesting for you.

Examples

Example I

Example I

Example II

Example II

Example III

Example III

Script Source Code

This is the complete source code of the required program:

    class ZimGroovyExec
    {
    static main(String[] args)
    {
        def lines=new File(args[0]).readLines()
        def binding=new Binding()   
        def shell=new GroovyShell(binding)

        new File(args[0]).withWriter { file->
            for (line in lines)
            switch(line)
            {
                case ~/\$ (.*)/:
                    file.println line
                    try{
                        file.println "-> "+shell.evaluate(line.substring(1))
                    } catch (Exception e)
                    { file.println "-> Exception: "+e.message.replaceAll('\n','; ') }
                    break;

                case ~/-> (.*)/:
                    break;

                default:
                    file.println(line)
                    break;
            }
        }
    }
    }

How to run it

  1. Make sure that groovy is properly installed on your system.
  2. Copy the above script into a text file and name it 'ZimGroovyExec.groovy' (for example)
  3. Create a script file which executes the above file. (The reason why is is required is that zim puts quotation marks around everything when using custom tools and apparently the groovy command does not like this.) Consider this example for Linux and copy it to /usr/bin/groovyexec (as superuser) and mark it as executable (chmod a+x groovyexec).
    #!/bin/sh
    groovy ~/Dropbox/ZimGroovyExec.groovy $1
  1. Add it as a new tool in zim by specifying the script name and the "%f" commandline argument
  2. After completing these steps, the GroovyExecute command should be available from withim zim. Enjoy. :)