Thursday, October 29, 2009

Extending Kate with Scripts

As mentioned in one of my last blogs, there has been quite some work for JavaScript scripting support in trunk recently. So what will Kate 3.4 (KDE 4.4) will bring? This is explained in detail in the sections:
  • Indentation Scripting
  • Command Line Scripting
  • Some Remarks
The scripting allows to extend Kate with lots of little helper functions. All users can add scripts as they wish. The documentation here is copied from the official Kate handbook. So instead of using this blog as reference, please use the handbook later for an up-to-date version. To script something useful, you'll need to know the scripting API. All the available functions are documented in the section Scripting API in the handbook as well. Enough said, here we go:

Extending Kate with Scripts

Since Kate 3.4 in KDE 4.4 the Kate editor component is easily extensible by writing scripts. The scripting language is ECMAScript (widely known as JavaScript). Kate supports two kinds of scripts: indentation and command line scripts.

Indentation Scripts

Indentation scripts - also referred as indenters - automatically indent the source code while typing text. As example, after hitting the return-key code the indentation level often increases.

The following sections describe step by step how to create the skeleton for a simple indenter. As first step, create a new *.js file called e.g. javascript.js in the local home folder $KDEHOME/share/apps/katepart/script.

The Indentation Script Header

The header of the file javascript.js is embedded in a comment and is of the following form

/* kate-script
* name: JavaScript
* author: Example Name
* license: BSD
* revision: 1
* kate-version: 3.4
* type: indentation
* required-syntax-style: javascript
* indent-languages: javascript
* priority: 0
*
* A line without colon ':' stops header parsing. That is, you can add optional
* text here such as a detailed license.
*/

Each entry is explained in detail now:

  • kate-script [required]: This text string has to appear in the first line of the *.js file, otherwise Kate skips the script.
  • name [required]: This is the indenter name that appears in the menu Tools->Indentation and in the configuration dialog.
  • author [optional]: The author's name and contact information.
  • license [optional]: Short form of the license, such as BSD or LGPLv3.
  • revision [required]: The revision of the script. This number should be increased whenever the script is modified.
  • kate-version [required]: Minimal required Kate version.
  • type [required]: The type must be “indentation”, otherwise Kate skips this script.
  • required-syntax-style [optional]: Comma separated list of required syntax highlighting styles. This is important for indenters that rely on specific highlight information in the document. If a required syntax style is specified, the indenter is available only when the appropriate highlighter is active. This prevents “undefined behavior” caused by using the indenter without the expected highlighting schema. For instance, the Ruby indenter makes use of this in the files ruby.js and ruby.xml.
  • indent-languages [optional]: Comma separated list of syntax styles the indenter can indent correctly, e.g.: c++, java.
  • priority [optional]: If several indenters are suited for a certain highlighted file, the priority decides which indenter is chosen as default indenter.

Kate reads all pairs of the form “key:value” until it cannot fine a colon anymore. This implies that the header can contain arbitrary text such as a license as shown in the example.

The Indenter Source Code

Having specified the header this section explains how the indentation scripting itself works. The basic skeleton of the body looks like this:

triggerCharacters = "{}/:;";
function indent(line, indentWidth, ch)
{
// called for each newline (ch == '\n') and all characters specified in
// the global variable triggerCharacters. When calling Tools->Align
// the variable ch is empty, i.e. ch == ''.
//
// see also: Scripting API
return -2;
}

The function indent() has three parameters:

  • line: the line that has to be indented
  • indentWidth: the indentation width in amount of spaces
  • ch: either a newline character (ch == '\n'), the trigger character specified in triggerCharacters or empty if the user invoked the action Tools->Align.

The return value of the indent() function specifies how the line will be indented. If the return value is a simple integer number, it is interpreted as follows:

  • return value -2: do nothing
  • return value -1: keep indentation (searches for previous non-blank line)
  • return value 0: numbers >= 0 specify the indentation depth in spaces

Alternatively, an array of two elements can be returned:

  • return [ indent, align ];

In this case, the first element is the indentation depth like above with the same meaning of the special values. However, the second element is an absolute value representing a column for “alignment”. If this value is higher than the indent value, the difference represents a number of spaces to be added after the indentation of the first parameter. Otherwise, the second number is ignored. Using tabs and spaces for indentation is often referred to as “mixed mode”.

Consider the following example: Assume using tabs to indent, and tab width is set to 4. Here, <tab> represents a tab and '.' a space:

1: <tab><tab>foobar("hello",
2: <tab><tab>......."world");

When indenting line 2, the indent() function returns [8, 15]. As result, two tabs are inserted to indent to column 8, and 7 spaces are added to align the second parameter under the first, so that it stays aligned if the file is viewed with a different tab width.

A default KDE installation ships Kate with several indenters. The corresponding JavaScript source code can be found in $KDRDIR/share/apps/katepart/script.

Developing an indenter requires to reload the scripts to see whether the changes behave appropriately. Instead of restarting the application, simply switch to the command line and invoke the command reload-scripts.

If you develop useful scripts please consider contributing to the Kate Project by contacting the mailing list.

Command Line Scripts

As it is hard to satisfy everyone's needs, Kate supports little helper tools for quick text manipulation through the built-in command line. For instance, the command sort is implemented as script. This section explains how to create *.js files to extend Kate with arbitrary helper scripts.

Command line scripts are located in the save folder as indentation scripts. So as first step, create a new *.js file called myutils.js in the local home folder $KDEHOME/share/apps/katepart/script.

The Command Line Script Header

The header of each command line script is embedded in a comment and is of the following form

/* kate-script
* author: Example Name
* license: BSD
* revision: 1
* kate-version: 3.4
* type: commands
* functions: sort, format-paragraph
*
* A line without colon ':' stops header parsing. That is, you can add optional
* text here such as a detailed license.
*/

Each entry is explained in detail now:

  • kate-script [required]: This text string has to appear in the first line of the *.js file, otherwise Kate skips the script.
  • author [optional]: The author's name and contact information.
  • license [optional]: Short form of the license, such as BSD or LGPLv3.
  • revision [required]: The revision of the script. This number should be increased whenever the script is modified.
  • kate-version [required]: Minimal required Kate version.
  • type [required]: The type must be 'commands', otherwise Kate skips this script.
  • functions [required]: Comma separated list of commands in the script.

Kate reads all pairs of the form “key:value” until it cannot fine a colon anymore. This implies that the header can contain arbitrary text such as a license as shown in the example. The value of the key functions is a comma separated list of command line commands. This means a single script contains an arbitrary amount of command line commands. Each function is available through Kate's built-in command line.

The Script Source Code

All functions specified in the header have to be implemented in the script. For instance, the script file from the example above needs to implement the two functions sort and format-paragraph. All functions have the following syntax:

function (arg1, arg2, ...)
{
// ... implementation, see also: Scripting API
}

Arguments in the command line are passed to the function as arg1, arg2, etc. In order to provide documentation for each command, simply implement the 'help' function as follows:

function help(cmd)
{
if (cmd == "sort") {
return "Sort the selected text.";
} else if (cmd == "...") {
// ...
}
}

Executing help sort in the command line then calls this help function with the argument cmd set to the given command, i.e. cmd == "sort". Kate then presents the returned text as documentation to the user.

Developing a command line script requires to reload the scripts to see whether the changes behave appropriately. Instead of restarting the application, simply switch to the command line and invoke the command reload-scripts.

If you develop useful scripts please consider contributing to the Kate Project by contacting the mailing list.

Final Remarks

Right now, it's not possible to assign shortcuts to command line commands. Thus, there is no way of executing scripted commands with shortcuts. Volunteers wanted!

The command line scripting can be accessed for all KTextEditor users through the KTextEditor::CommandInterface. That is, you can query a specific command and execute it with arbitrary parameters (The parameter cmd contains the command itself including all arguments. Example: cmd = "goto 65").

Kate's command line itself is actually a quite powerful tool. It's a little bit sad that it's rather unknown. If you want to know more, just invoke "View -> Swith to command line" (shortcut: F7) and start typing text. More details are in the Kate handbook as well.

The Kate scripting API can be found here.

9 comments:

kedadi said...

Good job with scripting support.

An year and a half old page from Kate's website (http://kate-editor.org/news/development-sprint-results) points out that Kross support is a long-term goal. Is there anything going on in that direction?

Thank you.

sergio_pistone said...

Does anybody know why QtScript is generally chosen over Kross for scripting (Amarok, Plasma, Kate, etc.)? I'm curious. I have not used QtScript but have added Kross support to an application without much problem (even though the docs were a bit lacking). Is supporting QtScript easier than supporting Kross? Is it related to security? Access to the Qt API?

Tempura said...

Is there any way to involve external apps in scripts? I mean, javascript is nice and so, but the most powerful tools aren't available there, so without them, the scripting-ability is just a little text-scribbling-toy.

dhaumann said...

@kedadi:
Thanks :) Noone looked into application level scripting support, i.e., there is no Kross integration in the Kate application, yet. Looking at the list of the developer sprint, quite a lot of the todos there are finished. Kross integration simply isn't one of them, unfortunately. PS: We are happy for any help, of course :)

@sergio_pistone:
We once chose QtScript as we wanted to have a lightweight scripting framework that has to very fast for e.g. indentation. Hence, we decided to use only one scripting language but make it work good. Both QtScript and Kross support JavaScript, so from the user's perspective it does not make any difference. At that time, we simply decided for QtScript from kjs, which was really a huge improvement in terms of developing with QtScript from the C++ side. There's not much more about it. One big plus for JavaScript is that JavaScript supports Unicode out of the box. Other languages do not necessarily do that, and all text strings in Kate are unicode.
Of course you can also argument with Security etc, but that was not really subject here.

@Tempura:
No, there is no way executing external apps. But you name it: "the scripting-ability is just a little text-scribbling-toy". As Kate is a *text editor*, this is exactly what we want: Tools for text manipulation. And JavaScript is pretty good there.
It's still possible to add an API like "system.exec(...)". But so far, noone needed that.

On the application level we want to add Kross. Then calling external apps is for free.

kevincolyer said...

I would love to have the key-binding for scripts. One of the things I miss so much is an easy way to raise or lower a paragraph over another (รก la ALT-CTRL up and down).

I made a patch once for Kate but that was not pursued. I would happily write a script but no key bindings make this a lost cause.

So I would be most grateful to anyone who can add key-bindings.

I use Kate a lot and love it! This for me would be the icing on the cake.

Cheers,

Kevin

dhaumann said...

Hi Kevin,

binding scripts to shortcuts is indeed on the todo list for a long time now.
To me it's still unclear how to do that best. My current idea is that you can create an action for a command line in the settings dialog. All actions are listed in the configure-shortcuts dialog, so it would appear there then.

As a side note: There are also commands that need parameters (such as goto #line). So we need more than just bind an action+execute. We probably have to ask the script whether it needs parameters and then open the command line with the preprinted command in it. Is that a good idea?

...thoughts welcome.

Greetings
Dominik

PS: yes, I remember you posting a patch. I don't know why it wasn't accepted anymore, maybe no one took the time to review + commit :(

Alex said...

Is there a way to make Kate execute a command-line script from qdbus or dbus-send? Because if there is, that's all you need for menu, toolbar, and keyboard shortcuts linking directly to command-line scripts without changing Kate at all.

If you can send a dbus command to org.kde.kate-$KATE_PID telling it to run a script, then you can put that command into a shell script in the External Tools menu.

Alternatively, even if the command-line functionality isn't exposed to dbus, you could write anything you want directly to the current document. The only problem is that if you want to insert content rather than replace everything, you have to give dbus argument specifying the location in the document. This is just a glorified array of (line #, col #) but it has to be a QPoint data-type for some reason and neither of the stupid command-line tools seem to be able to send these two simple pieces of data in that format.

Imagine the scripting possibilities if only this one little technical problem were solved (or if my ignorance of an existing solution was dispelled).

dhaumann said...

@Alex: no, it's not possible at the moment...

Alex said...

Okay, then perhaps there is a Perl, Python, or Javascript package that can handle DBUS's data-types. Then a small script can be written in one of those languages and add that to External Tools?

There's got to be something besides C++ that can talk to DBUS properly!