• Kate: More on Indentation Scripting

    by  • July 20, 2007 • Users

    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.

    About

    Dominik is a PhD student at the Control Theory and Robotics Lab, TU Darmstadt, as part of the Research Training Group GKMM (GRK1362). My research focuses on state estimation in distributed systems. As hobby, I contribute to the KDE project and work on the Kate application and editor component.

    http://www.kate-editor.org