Friday, July 20, 2007

Kate: More on Indentation Scripting

My last blog was about the theory of how indentation works by using javascripts. Now we will look at a concrete example: a LISP-style indenter. (LISP indentation is easy, that's why it's a good example).
The rules:
  • comments starting with ;;; always have indentation 0
  • comments starting with ;; should be aligned with the next line
  • comments starting with ; should only appear behind code, so they are simply ignored
  • every '(' indents and every ')' unindents
lisp.js looks like this:
/** kate-script
 * name: LISP
 * license: LGPL
 * author: foo bar
 * version: 1
 * kate-version: 3.0
 * type: indentation
 */
// indent should be called when ; is pressed
triggerCharacters = ";";
function indent(line, indentWidth, ch)
{
    // special rules: ;;; -> indent 0
    //                ;;  -> align with next line, if possible
    //                ;   -> usually on the same line as code -> ignore
    textLine = document.line(line);
    if (textLine.search(/^\s*;;;/) != -1) {
        return 0;
    } else if (textLine.search(/^\s*;;/) != -1) {
        // try to align with the next line
        nextLine = document.nextNonEmptyLine(line + 1);
        if (nextLine != -1) {
            return document.firstVirtualColumn(nextLine);
        }
    }

    cursor = document.anchor(line, 0, '(');
    if (cursor) {
        return document.toVirtualColumn(cursor.line, cursor.column) + indentWidth;
    } else {
        return 0;
    }
}

The result:
;;; fib : number -> number
(define (fib n)
  (if (< n 2)
    1
    (+ (fib (- n 1)) (fib (- n 2)))))
As this indenter is scripted, everybody can adapt the style to the own needs.

3 comments:

Unknown said...

Hey nice work. Its good to have emacs' electric functionality in kate too :)

peppelorum said...

Wow! Now even hobby hackers can start to add plugins to kate/random part of kde. This seems like a good and nice idea.
One question though, there has been lots about Kross lately in at the planetkde, how come you don't use that instead of writing your own? Not critique in any way, just a question from a user that tries to understand what happens to sweet, sweet KDE=)

Btw, Kate is the best text editor I've used on *nix=)

thiago said...

This is exactly the kind of "Power Feature" I've been arguing for a while that should be provided as scripts. Yours is a perfect example.

I've been using as example the KMail expiry feature: "expire all emails that are 14 days old, except unread emails (30 days), important (never expire) or to-do emails (60 days)".

Can you imagine the UI nightmare that would be a hypothetical dialog configuring indention styles that please every developer under the Sun and their moms?

So, my vision for KDE is that we offer flexible configuration in the UI so that 80-90% can configure to work the way they want, and the rest is scriptable.