Skip to content

Extending Kate by Scripts

Saturday, 21 July 2007 | Dominik Haumann


We have seen how scripting basically works for indentation. It’s also possible to register commandline functions (The command line is bound to F7 by default, or invoke View > Switch to Command Line). We will consider a small example again: sort the selected text.

/ kate-script
 
 name: unused
  author: foo bar
 
 license: LGPL
  version: 1
 
 kate-version: 3.0
  functions: sorter
 
/

function sorter ()
{
    if (view.hasSelection()) {
        var start = view.startOfSelection().line;
        var end = view.endOfSelection().line;

        var text = document.textRange(start, 0, end, document.lineLength(end));

        var lines = text.split(“\n”);
        lines.sort();
        text = lines.join(“\n”);

        view.clearSelection();

        document.editBegin();
        document.removeText(start, 0, end, document.lineLength(end));
        document.insertText(start, 0, text);
        document.editEnd();
    }
}

The header line functions: sorter makes Kate Part aware of the function in the script. A list of functions is supported, separated by white spaces. You can use the function by typing ‘sorter’ in the commandline.
Some todo items:

  • provide better JavaScript API. For example: document.textRange() takes 4 parameters. It would be more elegant to take one range or two cursors, just like we do in the KTextEditor interfaces in kdelibs/interfaces/ktexteditor
  • make is possible to bind scripts to shortcuts. This could be done by e.g. binding commandline functions to shortcuts or implementing a vim-like command-mode in Kate’s commandline. How to configure the shortcuts is unclear, though.
  • then, think about replacing the C++ implementations of ‘uppercase’, ‘lowercase’, ‘capitalize’ etc. with scripts
  • things I forgot…

If you are interested subscribe to kwrite-devel@kde.org and contribute :) We also need indentation scripts, of course!