Skip to content

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.