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 - 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/indentation.
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 <example.name@some.address.org> * license: BSD * revision: 1 * kate-version: 3.4 * required-syntax-style: javascript * indent-languages: javascript * priority: 0 * i18n-catalog: mycatalog * * 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*.jsfile, otherwise Kate skips the script.name[required]: This is the indenter name that appears in the menu → 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.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 filesruby.jsandruby.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.i18n-catalog[optional]: Additional message catalog (pofile) loaded for translation of 3rd-party indenters.
Kate reads all pairs of the form
“key:value”
until it cannot find a colon anymore. This implies that the header can contain
arbitrary text such as a license as shown in the example.
Having specified the header this section explains how the indentation scripting itself works. The basic skeleton of the body looks like this:
// required katepart js libraries, e.g. range.js if you use Range
require ("range.js");
triggerCharacters = "{}/:;";
function indent(line, indentWidth, ch)
{
// called for each newline (ch == '\n') and all characters specified in
// the global variable triggerCharacters. When calling →
// 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 indentedindentWidth: the indentation width in amount of spacesch: either a newline character (ch == '\n'), the trigger character specified intriggerCharactersor empty if the user invoked the action → .
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 nothingreturn 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 $KDEDIR/share/apps/katepart/script/indentation.
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.
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 same 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/commands.
The header of each command line script is embedded in a comment and is of the following form
/* kate-script * author: Example Name <example.name@some.address.org> * license: BSD * revision: 1 * kate-version: 3.4 * functions: sort, format-paragraph * i18n-catalog: mycatalog * * 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*.jsfile, 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.functions[required]: Comma separated list of commands in the script.i18n-catalog[optional]: Additional message catalog (pofile) loaded for translation of 3rd-party scripts.
Kate reads all pairs of the form
“key:value”
until it cannot find 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.
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:
// required katepart js libraries, e.g. range.js if you use Range
require ("range.js");
function <name>(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 i18n("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. Make sure to
translate the strings.
In order to be able to assign shortcuts, the script needs to provide a
function called action as follows:
function action(cmd)
{
var a = new Object();
if (cmd == "sort") {
a.text = i18n("Sort Selected Text");
a.icon = "";
a.category = "";
a.interactive = false;
a.shortcut = "";
} else if (cmd == "moveLinesDown") {
// same for next action
}
return a;
}
The parameter cmd of the function specifies the command for
which a shortcut is requested. There are several fields you have to specify in
the returned javascript object:
a.text[required]: The text appears in the menu → . Make sure to usei18nfor translation.a.icon[optional]: The icon appears next to the text in the menu. All KDE icon names can be used here.a.category[optional]: If a category is specified, the script appears in a submenu. Make sure to usei18nfor translation.a.interactive[optional]: If the script needs user input, set this totrue.a.shortcut[optional]: The shortcut given here is the default shortcut. Example: Ctrl+Alt+t. See the Qt documentation for further details.
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.
The scripting API presented here is available in all scripts, i.e. indentation
scripts and command line commands.
The Cursor and Range are provided by library files in $KDEDIR/share/apps/katepart/libraries.
If you want to use them in your script, which is required to use some of the Document or View functions, please include the needed library by using:
// required katepart js libraries, e.g. range.js if you use Range
require ("range.js");
To extend the standard scripting API with own functions and prototypes simply
create a new file in the KDE's local configuration folder
$KDEHOME/share/apps/katepart/libraries and include it into your script using:
require ("myscriptnamehere.js");
To extend existing prototypes like Cursor or
Range, the recommended way is to
not modify the global *.js files.
Instead, change the Cursor prototype in JavaScript after the cursor.js is included into your
script via require.
As Kate is a text editor, all the scripting API is based on cursors and
ranges whenever possible. A Cursor is a simple (line, column)
tuple representing a text position in the document. A Range spans text from a
starting cursor position to an ending cursor position. The API is explained in
detail in the next sections.
Cursor();
Constructor. Returns a Cursor at position
(0, 0).Example:
var cursor = new Cursor();Cursor(
int,lineint);columnConstructor. Returns a Cursor at position (line, column).
Example:
var cursor = new Cursor(3, 42);Cursor(Cursor);otherCopy constructor. Returns a copy of the cursor
other.Example:
var copy = new Cursor(other);Cursor Cursor.clone();
Returns a clone of the cursor.
Example:
var clone = cursor.clone();bool Cursor.isValid();
Check whether the cursor is valid. The cursor is invalid, if line and/or column are set to
-1.Example:
var valid = cursor.isValid();Cursor Cursor.invalid();
Returns an new invalid cursor located at
(-1, -1).Example:
var invalidCursor = cursor.invalid();int Cursor.compareTo(Cursor);otherCompares this cursor to the cursor
other. Returns-1, if this cursor is located before the cursorother,0, if both cursors equal and+1, if this cursor is located after the cursorother.
bool Cursor.equals(Cursor);otherReturns
true, if this cursor and the cursorotherare equal, otherwisefalse.String Cursor.toString();
Returns the cursor as a string of the form “
Cursor(line, column)”.
Range();
Constructor. Calling
new Range()returns a Range at (0, 0) - (0, 0).Range(
Cursor,startCursor);endConstructor. Calling
new Range(returns the Range (start,end)start,end).Range(
int,startLineint,startColumnint,endLineint);endColumnConstructor. Calling
new Range(returns the Range from (startLine,startColumn,endLine,endColumn)startLine,startColumn) to (endLine,endColumn).Range(Range);otherCopy constructor. Returns a copy of Range
other.Range Range.clone();
Returns a clone of the range.
Example:
var clone = range.clone();bool Range.isValid();
Returns
true, if both start and end cursor are valid, otherwisefalse.Example:
var valid = range.isValid();bool Range.invalid();
Returns the Range from (-1, -1) to (-1, -1).
bool Range.contains(Cursor);cursorReturns
true, if this range contains the cursor position, otherwisefalse.bool Range.contains(Range);otherReturns
true, if this range contains the Rangeother, otherwisefalse.bool Range.containsColumn(int);columnReturns
true, ifcolumnis in the half open interval[start.column, end.column), otherwisefalse.bool Range.containsLine(int);lineReturns
true, iflineis in the half open interval[start.line, end.line), otherwisefalse.bool Range.overlaps(Range);otherReturns
true, if this range and the rangeothershare a common region, otherwisefalse.bool Range.overlapsLine(int);lineReturns
true, iflineis in the interval[start.line, end.line], otherwisefalse.bool Range.overlapsColumn(int);columnReturns
true, ifcolumnis in the interval[start.column, end.column], otherwisefalse.bool Range.onSingleLine();
Returns
true, if the range starts and ends at the same line, i.e. ifRange.start.line == Range.end.line.Since: KDE 4.9
bool Range.equals(Range);otherReturns
true, if this range and the Rangeotherare equal, otherwisefalse.String Range.toString();
Returns the range as a string of the form “
Range(Cursor(line, column), Cursor(line, column))”.
This section lists all global functions.
String read(String);fileWill search the given
filerelative to thekatepart/script/filesdirectory and return its content as a string.
void require(String);fileWill search the given
filerelative to thekatepart/script/librariesdirectory and evaluate it.requireis internally guarded against multiple inclusions of the samefile.Since: KDE 4.10
In order to support full localization, there are several functions to translate
strings in scripts, namely i18n, i18nc,
i18np and i18ncp. These functions behave
exactly like
KDE's translation functions.
The translation functions translate the wrapped strings through KDE's
translation system to the language used in the application. Strings in scripts
being developed in the official Kate sources are automatically extracted and
translatable. In other words, as a Kate developer you do not have to bother with
message extraction and translation. However, for 3rd-party scripts developed
outside of KDE, you have to extract and translate the messages yourself. Along
with your scripts you have to also distribute a translation catalog, that
includes all translated strings. Further, your script header then must
explicitly state the catalog to load by specifying
i18n-catalog.
void i18n(
String,textarg1, ...);Translates
textinto the language used by the application. The argumentsarg1, ..., are optional and used to replace the placeholders%1,%2, etc.void i18nc(
String,contextString,textarg1, ...);Translates
textinto the language used by the application. Additionally, the stringcontextis visible to translators so they can provide a better translation. The argumentsarg1, ..., are optional and used to replace the placeholders%1,%2, etc.void i18np(
String,singularString,pluralint,numberarg1, ...);Translates either
singularorpluralinto the language used by the application, depending on the givennumber. The argumentsarg1, ..., are optional and used to replace the placeholders%1,%2, etc.void i18ncp(
String,contextString,singularString,pluralint,numberarg1, ...);Translates either
singularorpluralinto the language used by the application, depending on the givennumber. Additionally, the stringcontextis visible to translators so they can provide a better translation. The argumentsarg1, ..., are optional and used to replace the placeholders%1,%2, etc.
Whenever a script is being executed, there is a global variable
“view” representing the current active editor
view. The following is a list of all available View functions.
Cursor view.cursorPosition()Returns the current cursor position in the view.
void view.setCursorPosition(
int,lineint); void view.setCursorPosition(columnCursor);cursorSet the current cursor position to either (line, column) or to the given cursor.
Cursor view.virtualCursorPosition();
Returns the virtual cursor position with each tab counting the corresponding amount of spaces depending on the current tab width.
void view.setVirtualCursorPosition(
int,lineint); void view.setVirtualCursorPosition(columnCursor);cursorSet the current virtual cursor position to (line, column) or to the given cursor.
String view.selectedText();
Returns the selected text. If no text is selected, the returned string is empty.
bool view.hasSelection();
Returns
true, if the view has selected text, otherwisefalse.Range view.selection();
Returns the selected text range. The returned range is invalid if there is no selected text.
void view.setSelection(Range);rangeSet the selected text to the given range.
void view.removeSelectedText();
Remove the selected text. If the view does not have any selected text, this does nothing.
void view.selectAll();
Selects the entire text in the document.
void view.clearSelection();
Clears the text selection without removing the text.
Whenever a script is being executed, there is a global variable
“document” representing the current active
document. The following is a list of all available Document functions.
String document.fileName();
Returns the document's filename or an empty string for unsaved text buffers.
String document.url();
Returns the document's full url or an empty string for unsaved text buffers.
String document.mimeType();
Returns the document's mime type or the mime type
application/octet-streamif no appropriate mime type could be found.String document.encoding();
Returns the currently used encoding to save the file.
String document.highlightingMode();
Returns the global highlighting mode used for the whole document.
String document.highlightingModeAt(Cursor);posReturns the highlighting mode used at the given position in the document.
Array document.embeddedHighlightingModes();
Returns an array of highlighting modes embedded in this document.
bool document.isModified();
Returns
true, if the document has unsaved changes (modified), otherwisefalse.String document.text();
Returns the entire content of the document in a single text string. Newlines are marked with the newline character “
\n”.String document.text(
int,fromLineint,fromColumnint,toLineint); String document.text(toColumnCursor,fromCursor); String document.text(toRange);rangeReturns the text in the given range. It is recommended to use the cursor and range based version for better readability of the source code.
String document.line(int);lineReturns the given text line as string. The string is empty if the requested line is out of range.
String document.wordAt(
int,lineint); String document.wordAt(columnCursor);cursorReturns the word at the given cursor position.
-
Range document.wordRangeAt(
int,lineint); Range document.wordRangeAt(columnCursor);cursor Return the range of the word at the given cursor position. The returned range is invalid (see Range.isValid()), if the text position is after the end of a line. If there is no word at the given cursor, an empty range is returned.
Since: KDE 4.9
String document.charAt(
int,lineint); String document.charAt(columnCursor);cursorReturns the character at the given cursor position.
String document.firstChar(int);lineReturns the first character in the given
linethat is not a whitespace. The first character is at column 0. If the line is empty or only contains whitespace characters, the returned string is empty.String document.lastChar(int);lineReturns the last character in the given
linethat is not a whitespace. If the line is empty or only contains whitespace characters, the returned string is empty.bool document.isSpace(
int,lineint); bool document.isSpace(columnCursor);cursorReturns
true, if the character at the given cursor position is a whitespace, otherwisefalse.bool document.matchesAt(
int,lineint,columnString); bool document.matchesAt(textCursor,cursorString);textReturns
true, if the giventextmatches at the corresponding cursor position, otherwisefalse.bool document.startsWith(
int,lineString,textbool);skipWhiteSpacesReturns
true, if the line starts withtext, otherwisefalse. The argumentskipWhiteSpacescontrols whether leading whitespaces are ignored.bool document.endsWith(
int,lineString,textbool);skipWhiteSpacesReturns
true, if the line ends withtext, otherwisefalse. The argumentskipWhiteSpacescontrols whether trailing whitespaces are ignored.bool document.setText(String);textSets the entire document text.
bool document.clear();
Removes the entire text in the document.
bool document.truncate(
int,lineint); bool document.truncate(columnCursor);cursorTruncate the given line at the given column or cursor position. Returns
trueon success, orfalseif the given line is not part of the document range.bool document.insertText(
int,lineint,columnString); bool document.insertText(textCursor,cursorString);textInserts the
textat the given cursor position. Returnstrueon success, orfalse, if the document is in read-only mode.bool document.removeText(
int,fromLineint,fromColumnint,toLineint); bool document.removeText(toColumnCursor,fromCursor); bool document.removeText(toRange);rangeRemoves the text in the given range. Returns
trueon success, orfalse, if the document is in read-only mode.bool document.insertLine(
int,lineString);textInserts text in the given line. Returns
trueon success, orfalse, if the document is in read-only mode or the line is not in the document range.bool document.removeLine(int);lineRemoves the given text line. Returns
trueon success, orfalse, if the document is in read-only mode or the line is not in the document range.bool document.wrapLine(
int,lineint); bool document.wrapLine(columnCursor);cursorWraps the line at the given cursor position. Returns
trueon success, otherwisefalse, e.g. if line < 0.Since: KDE 4.9
void document.joinLines(
int,startLineint);endLineJoins the lines from
startLinetoendLine. Two succeeding text lines are always separated with a single space.int document.lines();
Returns the amount of lines in the document.
int document.length();
Returns the number of characters in the document.
int document.lineLength(int);lineReturns the
line's length.void document.editBegin();
Starts an edit group for undo/redo grouping. Make sure to always call
editEnd()as often as you calleditBegin(). CallingeditBegin()internally uses a reference counter, i.e., this call can be nested.void document.editEnd();
Ends an edit group. The last call of
editEnd()(i.e. the one for the first call ofeditBegin()) finishes the edit step.int document.firstColumn(int);lineReturns the first non-whitespace column in the given
line. If there are only whitespaces in the line, the return value is-1.int document.lastColumn(int);lineReturns the last non-whitespace column in the given
line. If there are only whitespaces in the line, the return value is-1.int document.prevNonSpaceColumn(
int,lineint); int document.prevNonSpaceColumn(columnCursor);cursorReturns the column with a non-whitespace characters starting at the given cursor position and searching backwards.
int document.nextNonSpaceColumn(
int,lineint); int document.nextNonSpaceColumn(columnCursor);cursorReturns the column with a non-whitespace characters starting at the given cursor position and searching forwards.
int document.prevNonEmptyLine(int);lineReturns the next non-empty line containing non-whitespace characters searching backwards.
int document.nextNonEmptyLine(int);lineReturns the next non-empty line containing non-whitespace characters searching forwards.
bool document.isInWord(
String,characterint);attributeReturns
true, if the givencharacterwith the givenattributecan be part of a word, otherwisefalse.bool document.canBreakAt(
String,characterint);attributeReturns
true, if the givencharacterwith the givenattributeis suited to wrap a line, otherwisefalse.bool document.canComment(
int,startAttributeint);endAttributeReturns
true, if a range starting and ending with the given attributes is suited to be commented out, otherwisefalse.String document.commentMarker(int);attributeReturns the comment marker for single line comments for a given
attribute.String document.commentStart(int);attributeReturns the comment marker for the start of multi-line comments for a given
attribute.String document.commentEnd(int);attributeReturns the comment marker for the end of multi-line comments for a given
attribute.int document.attribute(
int,lineint); int document.attribute(columnCursor);cursorReturns the attribute at the given cursor position.
bool document.isAttribute(
int,lineint,columnint); bool document.isAttribute(attributeCursor,cursorint);attributeReturns
true, if the attribute at the given cursor position equalsattribute, otherwisefalse.String document.attributeName(
int,lineint); String document.attributeName(columnCursor);cursorReturns the attribute name as human readable text. This equals to the
itemDataname in the syntax highlighting files.bool document.isAttributeName(
int,lineint,columnString); bool document.isAttributeName(nameCursor,cursorString);nameReturns
true, if the attribute name at a certain cursor position matches the givenname, otherwisefalse.String document.variable(String);keyReturns the value of the requested document variable
key. If the document variable does not exist, the return value is an empty string.String document.setVariable(
String,keyString);valueSet the value of the requested document variable
key. Returns the value of set variable.See also: Kate document variables
Since: KDE 4.8
int document.firstVirtualColumn(int);lineReturns the virtual column of the first non-whitespace character in the given line or
-1, if the line is empty or contains only whitespace characters.int document.lastVirtualColumn(int);lineReturns the virtual column of the last non-whitespace character in the given line or
-1, if the line is empty or contains only whitespace characters.int document.toVirtualColumn(
int,lineint); int document.toVirtualColumn(columnCursor); Cursor document.toVirtualCursor(cursorCursor);cursorConverts the given “real” cursor position to a virtual cursor position, either returning an int or a Cursor object.
int document.fromVirtualColumn(
int,lineint); int document.fromVirtualColumn(virtualColumnCursor); Cursor document.fromVirtualCursor(virtualCursorCursor);virtualCursorConverts the given virtual cursor position to a “real” cursor position, either returning an int or a Cursor object.
Cursor document.anchor(
int,lineint,columnChar); Cursor document.anchor(characterCursor,cursorChar);characterSearches backward for the given character starting from the given cursor. As example, if '(' is passed as character, this function will return the position of the opening '('. This reference counting, i.e. other '(...)' are ignored.
Cursor document.rfind(
int,lineint,columnString,textint); Cursor document.rfind(attribute= -1Cursor,cursorString,textint);attribute= -1Find backward the given text with the appropriate
attribute. The argumentattributeis ignored if it is set to-1. The returned cursor is invalid, if the text could not be found.int document.defStyleNum(
int,lineint); int document.defStyleNum(columnCursor);cursorReturns the default style used at the given cursor position.
bool document.isCode(
int,lineint); bool document.isCode(columnCursor);cursorReturns
true, if the attribute at the given cursor position is not equal to all of the following styles:dsComment,dsString,dsRegionMarker,dsChar,dsOthers.bool document.isComment(
int,lineint); bool document.isComment(columnCursor);cursorReturns
true, if the attribute of the character at the cursor position isdsComment, otherwisefalse.bool document.isString(
int,lineint); bool document.isString(columnCursor);cursorReturns
true, if the attribute of the character at the cursor position isdsString, otherwisefalse.bool document.isRegionMarker(
int,lineint); bool document.isRegionMarker(columnCursor);cursorReturns
true, if the attribute of the character at the cursor position isdsRegionMarker, otherwisefalse.bool document.isChar(
int,lineint); bool document.isChar(columnCursor);cursorReturns
true, if the attribute of the character at the cursor position isdsChar, otherwisefalse.bool document.isOthers(
int,lineint); bool document.isOthers(columnCursor);cursorReturns
true, if the attribute of the character at the cursor position isdsOthers, otherwisefalse.