# Advanced Editing Tools

## Comment/Uncomment

The Comment and Uncomment commands, available from the Tools menu allow you to add or remove comment markers to the selection, or the current line if no text is selected, if comments are supported by the format of the text you are editing.

The rules for how commenting is done are defined in the syntax definitions, so if syntax highlighting is not used, commenting/uncommenting is not possible.

Some formats define single line comment markers, some multiline markers and some both. If multiline markers are not available, commenting out a selection that does not fully include its last line is not possible.

If a single line marker is available, commenting single lines is preferred where applicable, as this helps to avoid problems with nested comments.

When removing comment markers, no uncommented text should be selected. When removing multiline comment markers from a selection, any whitespace outside the comment markers is ignored.

To place comment markers, use the Tools Comment menu item or the related keyboard shortcut sequence, default is &Ctrl;D.

To remove comment markers, use the Tools Uncomment menu item or the related keyboard shortcut, default is &Ctrl;&Shift;D.

## The Editor Component Command Line

&kappname;'s editor component has an internal command line, allowing you to perform various actions from a minimal GUI. The command line is a text entry in the bottom of the editor area, to show it select View Switch to Command Line or use the shortcut (default is F7). The editor provides a set of commands as documented below, and additional commands can be provided by plugins.

To execute a command, type the command then press the return key. The command line will indicate whether it succeeded and possibly display a message. If you entered the command line by pressing F7 it will automatically hide after a few seconds. To clear the message and enter a new command, press F7 again.

The command line has a built-in help system, issue the command `help` to get started. To see a list of all available commands issue `help list`, to view help for a specific command, do `help `command``.

The command line has a built in history, so you can reuse commands already typed. To navigate the history, use the Up and Down keys. When showing historical commands, the argument part of the command will be selected, allowing you to easily overwrite the arguments.

### Standard Command Line Commands

### Argument types

BOOLEAN

- This is used with commands that turns things on or off. Legal values are `on`, `off`, `true`, `false`, `1` or `0`

INTEGER

- An integer number

STRING

- A string

#### Commands for Basic Editor Functions

    w

- Save the current document.

    wa

- Save all currently open documents.

    q

- Close the current document.

    qa

- Close all open documents.

    wq

- Save and close the current document.

    wqa

- Save and close all currently documents.

    x

- Save and close the current document only if it has changed.

    x

- Save and close all currently open documents only if they have changed.

    bp

- Go to the previous document in the documents list.

    bn

- Go to the next document in the documents list.

    new

- Open a new document in horizontal split view.

    vnew

- Open a new document in vertical split view.

    e

- Reload the current document if it has changed on disk.

    enew

- Edit a new document.

    print

- Open the Print dialog to print the current document.

#### Commands for Configuring the Editor

These commands are provided by the editor component, and allows you to configure the active document and view only. This is handy if you want to use a setting different from the default settings, for example for indentation.

    set-tab-widthINTEGER width

- Sets the tab width to the number `width`

    set-indent-widthINTEGER width

- Sets the indentation width to the number `width`. Used only if you are indenting with spaces.

    set-word-wrap-columnINTEGER width

- Sets the line width for hard wrapping to `width`. This is used if you are having your text wrapped automatically.

    set-icon-borderBOOLEAN enable

- Sets the visibility of the icon border.

    set-folding-markersBOOLEAN enable

- Sets the visibility of the folding markers pane.

    set-line-numbersBOOLEAN enable

- Sets the visibility of the line numbers pane.

    set-replace-tabsBOOLEAN enable

- If enabled, tabs are replaced with spaces as you type.

    set-remove-trailing-spaceBOOLEAN enable

- If enabled, trailing whitespace are removed whenever the cursor leaves a line.

    set-show-tabsBOOLEAN enable

- If enabled, TAB characters and trailing whitespace will be visualized by a small dot.

    set-show-indentBOOLEAN enable

- If enabled, indentation will be visualized by a vertical dotted line.

    set-indent-spacesBOOLEAN enable

- If enabled, the editor will indent with `indent-width` spaces for each indentation level, rather than with one TAB character.

    set-mixed-indentBOOLEAN enable

- If enabled, &kappname; will use a mix of TAB and spaces for indentation. Each indentation level will be `indent-width` wide, and more indentation levels will be optimized to use as many TAB characters as possible.

  When executed, this command will additionally set space indentation enabled, and if the indent width is unspecified it will be set to half of the `tab-width` for the document at the time of execution.

    set-word-wrapBOOLEAN
    enable

- Enables dynamic word wrap according to `enable`

    set-replace-tabs-saveBOOLEAN enable

- When enabled, tabs will be replaced with whitespace whenever the document is saved.

    set-remove-trailing-space-saveBOOLEAN enable

- When enabled, trailing space will be removed from each line whenever the document is saved.

    set-indent-modeSTRING name

- Sets the autoindentation mode to `name`. If `name` is not known, the mode is set to 'none'. Valid modes are 'none', 'normal', 'cstyle', 'haskell', 'lilypond', 'lisp', 'python', 'ruby' and 'xml'.

    set-auto-identBOOLEAN name

- Enable or disable autoindentation.

    set-highlightSTRING highlight

- Sets the syntax highlighting system for the document. The argument must be a valid highlight name, as seen in the Tools Highlighting menu. This command provides an autocompletion list for its argument.

    reload-scripts

- Reload all JavaScript scripts used by Kate, including indenters and command line scripts.

    set-wrap-cursorBOOLEAN
    enable

- Enable or disable Wrap cursor.

    set-modeBOOLEAN
    enable

- Choose the filetype scheme for the current document.

    nn[oremap]STRING original
    STRING mapped

- Map the key sequence `original` to `mapped`.

#### Commands for editing

These commands modify the current document.

    indent

- Indents the selected lines or the current line.

    unindent

- Unindents the selected lines or current line.

    cleanindent

- Cleans up the indentation of the selected lines or current line according to the indentation settings in the document.

    comment

- Inserts comment markers to make the selection or selected lines or current line a comment according to the text format as defined by the syntax highlight definition for the document.

    uncomment

- Removes comment markers from the selection or selected lines or current line according to the text format as defined by the syntax highlight definition for the document.

    kill-line

- Deletes the current line.

    replace STRING pattern
    STRING replacement

- Replaces text matching `pattern` with `replacement`. If you want to include whitespace in the `pattern`, you must quote both the `pattern` and `replacement` with single or double quotes. If the arguments are unquoted, the first word is used as `pattern` and the rest for `replacement`. If `replacement` is empty, each occurrence of `pattern` is removed.

  You can set flags to configure the search by adding a colon, followed by one or more letters each representing a configuration, giving the form `replace:options pattern replacement`. Available options are:

  `b`

- Search backwards.

`c`

- Search from cursor position.

`e`

- Search in the selection only.

`r`

- Do regular expression search. If set, you may use `\N` where N is a number to represent captures in the replacement string.

`s`

- Do case sensitive search.

`p`

- Prompt for permission to replace the next occurrence.

`w`

- Match whole words only.

    dateSTRING format

- Inserts a date/time string as defined by the specified `format`, or the format yyyy-MM-dd hh:mm:ss if none is specified. The following translations are done when interpreting `format`:

  `d` | The day as number without a leading zero (1-31).
  `dd` | The day as number with a leading zero (01-31).
  `ddd` | The abbreviated localized day name (e.g. 'Mon'..'Sun').
  `dddd` | The long localized day name (e.g. 'Monday'..'Sunday').
  `M` | The month as number without a leading zero (1-12).
  `MM` | The month as number with a leading zero (01-12).
  `MMM` | The abbreviated localized month name (e.g. 'Jan'..'Dec').
  `yy` | The year as two digit number (00-99).
  `yyyy` | The year as four digit number (1752-8000).
  `h` | The hour without a leading zero (0..23 or 1..12 if AM/PM display).
  `hh` | The hour with a leading zero (00..23 or 01..12 if AM/PM display).
  `m` | The minute without a leading zero (0..59).
  `mm` | The minute with a leading zero (00..59).
  `s` | The second without a leading zero (0..59).
  `ss` | The second with a leading zero (00..59).
  `z` | The milliseconds without leading zeroes (0..999).
  `zzz` | The milliseconds with leading zeroes (000..999).
  `AP` | Use AM/PM display. AP will be replaced by either "AM" or "PM".
  `ap` | Use am/pm display. ap will be replaced by either "am" or "pm".

    charSTRING identifier

- This command allows you to insert literal characters by their numerical identifier, in decimal, octal or hexadecimal form. To use it launch the Editing Command dialog and type `char: [number]` in the entry box, then hit OK.

  ##### `char` examples

  Input: `char:234`

  Output: `ê`

  Input: `char:0x1234`

  Output: `ሴ`

`s///[ig]` `%s///[ig]`

- This command does a sed-like search/replace operation on the current line, or on the whole file (`%s///`).

  In short, the text is searched for text matching the search pattern, the regular expression between the first and the second slash, and when a match is found, the matching part of the text is replaced with the expression between the middle and last part of the string. Parentheses in the search pattern create back references, that is the command remembers which part of the match matched in the parentheses; these strings can be reused in the replace pattern, referred to as `\1` for the first set of parentheses, `\2` for the second and so on.

  To search for a literal `(` or `)`, you need to escape it using a backslash character: `\(\)`

  If you put an `i` at the end of the expression, the matching will be case insensitive. If you put a `g` at the end, all occurrences of the pattern will be replaced, otherwise only the first occurrence is replaced.

  ##### Replacing text in the current line

  Your friendly compiler just stopped, telling you that the class `myClass` mentioned in line 3902 in your source file is not defined.

  "Buckle!" you think, it is of course `MyClass`. You go to line 3902, and instead of trying to find the word in the text, you launch the Editing Command Dialog, enter `s/myclass/MyClass/i`, hit the OK button, save the file and compile – successfully without the error.

  ##### Replacing text in the whole file

  Imagine that you have a file, in which you mention a Miss Jensen several times, when someone comes in and tells you that she just got married to Mr Jones. You want, of course, to replace each and every occurrence of Miss Jensen with Ms Jones.

  Enter the command line and issue the command `%s/Miss Jensen/Ms Jones/` and hit return, you are done.

  ##### A More Advanced Example

  This example makes use of back references as well as a character class (if you do not know what that is, please refer to the related documentation mentioned below).

  Suppose you have the following line:

      void MyClass::DoStringOps( String      &foo, String &bar String *p, int  &a, int &b )

  Now you realize that this is not nice code, and decide that you want to use the `const` keyword for all address of arguments, those characterized by the & operator in front of the argument name. You would also like to simplify the white space, so that there is only 1 whitespace character between each word.

  Launch the Editing Command Dialog, and enter: `s/\s+(\w+)\s+(&)/ const \1 \2/g` and hit the OK button. The `g` at the end of the expression makes the regular expression recompile for each match to save the backreferences.

  Output: `void MyClass::DoStringOps( const String &foo, const String &bar String *p, const int &a, const int &b )`

  Mission completed! Now, what happened? Well, we looked for some white space (`\s+`) followed by one or more alphabetic characters (`\w+`) followed by some more whitespace (`\s+`) followed by an ampersand, and in the process saved the alphabetic chunk and the ampersand for reuse in the replace operation. Then we replaced the matching part of our line with one whitespace followed by const followed by one whitespace followed by our saved alphabetical chunk (`\1`) followed by one whitespace followed by our saved ampersand (`\2`)

  Now in some cases the alphabetical chunk was String, in some int, so using the character class `\w` and the `+` quantifier proved a valuable asset.

    sort

- Sorts the selected text or entire document.

    natsort

- Sort the selected lines or entire document naturally.

  ##### `sort` vs. `natsort`

  `sort(a10, a1, a2)` results in `a1, a10, a2`

  `natsort(a10, a1, a2)` results in `a1, a2, a10`

    moveLinesDown

- Move selected lines down.

    moveLinesUp

- Move selected lines up.

    uniq

- Remove duplicated lines from the selected text or the whole document.

    rtrim

- Remove trailing space from the selected text or the whole document.

    ltrim

- Remove leading space from the selected text or the whole document.

    joinSTRING separator

- Join selected lines or whole document. Optionally takes a parameter defining a separator, for example: ``join` ', '`

    rmblank

- Remove all blank spaces from the selected text or the whole document.

    unwrap

- Unwrap the selected text or the whole document.

    eachSTRING script

- Given a JavaScript function as an argument, call that for the list of selected lines and replace them with the return value of that callback.

  ##### Join selected lines

  ``each` 'function(lines){return lines.join(", ")}'`

  Or, more briefly:

  ``each` 'lines.join(", ")'`

    filterSTRING script

- Given a JavaScript function as an argument, call that for the list of selected lines and remove those where the callback returns false.

  ##### Remove blank lines

  ``filter` 'function(1){return 1.length > 0;}'`

  Or, more briefly:

  ``filter` 'line.length > 0'`

    mapSTRING script

- Given a JavaScript function as an argument, call that for the list of selected lines and replace the line with the value of the callback.

  ##### Remove blank lines

  ``map` 'function(line){return line.replace(/^s+/,"");}'`

  Or, more briefly:

  ``map` 'line.replace(/^s+/,"")'`

    duplicateLinesUp

- Duplicate the selected lines above the current selection.

    duplicateLinesDown

- Duplicate the selected lines below the current selection.

#### Commands for navigation

    gotoINT line

- This command navigates to the specified line.

    grep STRING pattern

- Search the document for the regular expression `pattern`. For more information, see regular-expressions

    findSTRING pattern

- This command navigates to the first occurrence of `pattern` according to the configuration. Following occurrences can be found using Edit Find Next (the default shortcut is F3).

  The find command can be configured by appending a colon followed by one or more options, the form is `find:options pattern`. The following options are supported:

  `b`

- Search backwards.

`c`

- Search from cursor position.

`e`

- Search in the selection only.

`r`

- Do regular expression search. If set, you may use `\N` where N is a number to represent captures in the replacement string.

`s`

- Do case sensitive search.

`w`

- Match whole words only.

    ifindSTRING pattern

- This command provides as-you-type searching. You can configure the behavior of the search by appending a colon followed by one or more options, like this: `ifind:options pattern`. Allowed options are

  `b`

- Search backwards.

`r`

- Do regular expression search.

`s`

- Do case sensitive search.

`c`

- Search from cursor position.

## Using Code Folding

Code folding allows you to hide parts of a document in the editor, making it easier to overview large documents. In &kappname; the foldable regions are calculated using rules defined in the syntax highlight definitions, and therefore it is only available in some formats - typically program source code, XML markup and similar. Most highlight definitions supporting code folding also lets you manually define foldable regions, typically using the `BEGIN` and `END` keywords.

To use the code folding feature, activate the folding markers using View Show Folding Markers menu item if they are not already visible. The Folding Markers Pane in the left side of the screen displays a graphical view of the foldable regions, with triangle symbols to indicate the possible operation on a given region: a top down triangle means that the region is expanded, clicking it will collapse the region and a right pointing triangle will be displayed instead.

Eleven commands are provided to manipulate the state of folding regions, see the menu documentation.

The folded lines are remembered when a file is closed, so when you reopen the file the folded nodes will still be folded. This applies to reload operations as well.

If you do not want to use the code folding feature, you can disable the Show folding markers (if available) option in the Appearance page of the editor configuration.

## Extending &kappname; with Scripts

Since &kappname; 3.4 in KDE 4.4 the &kappname; editor component is easily extensible by writing scripts. The scripting language is ECMAScript (widely known as JavaScript). &kappname; supports two kinds of scripts: indentation and command line scripts.

### Indentation 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`.

#### The Indentation Script Header

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
     * type: indentation
     * 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 `*.js` file, otherwise &kappname; skips the script.

- `name` [required]: This is the indenter name that appears in the menu Tools Indentation 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 &kappname; version.

- `type` [required]: The type must be `indentation`, otherwise &kappname; skips this script.

- `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 files `ruby.js` and `ruby.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 (`po` file) loaded for translation of 3rd-party indenters.

&kappname; 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 Indenter Source Code

Having specified the header this section explains how the indentation scripting itself works. The basic skeleton of the body looks like this:

    triggerCharacters = "{}/:;";
    function indent(line, indentWidth, ch)
    {
        // called for each newline (ch == '\n') and all characters specified in
        // the global variable triggerCharacters. When calling ToolsAlign
        // 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 indented

- `indentWidth`: the indentation width in amount of spaces

- `ch`: either a newline character (`ch == '\n'`), the trigger character specified in `triggerCharacters` or empty if the user invoked the action Tools Align.

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 nothing

- return 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 &kappname; with several indenters. The corresponding JavaScript source code can be found in `$KDEDIR/share/apps/katepart/script`.

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 &kappname; Project by contacting the mailing list.

### Command Line Scripts

As it is hard to satisfy everyone's needs, &kappname; 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 &kappname; 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`.

#### The Command Line Script Header

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
     * type: commands
     * 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 `*.js` file, otherwise &kappname; 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 &kappname; version.

- `type` [required]: The type must be `commands`, otherwise &kappname; skips this script.

- `functions` [required]: Comma separated list of commands in the script.

- `i18n-catalog` [optional]: Additional message catalog (`po` file) loaded for translation of 3rd-party scripts.

&kappname; 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 &kappname;'s built-in command line.

#### The Script Source Code

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:

    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"`. &kappname; then presents the returned text as documentation to the user. Make sure to translate the strings.

##### Binding Shortcuts

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 Tools Scripts. Make sure to use `i18n` for 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 use `i18n` for translation.

- `a.interactive` [optional]: If the script needs user input, set this to `true`.

- `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 &kappname; Project by contacting the mailing list.

### Scripting API

The scripting API presented here is available in all scripts, i.e. indentation scripts and command line commands. Before the contents of a script is loaded, &kappname; first adds several prototypes and functions to the scripting context. This convenience API contains prototypes like text cursors and text ranges and is located in the folder `$KDEDIR/share/apps/katepart/api`. There, the file names of each JavaScript file conforms with the following naming scheme:

    <number>_<name>.js

The number has two digits and the name is an arbitrary name such as `myutils`. Through the number &kappname; controls the execution order of the API. I.e., the file called `05_cursor.js` is called before the file `10_range.js`. (This is similar to the start order of the runlevel/init system in Linux).

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/api` and make sure it has a greater number (execution order) than the other `*.js` files in the global folder `$KDEDIR/share/apps/katepart/api`. &kappname; automatically searches in both folders for `*.js` files and executes them in the correct order.

To extend existing prototypes like `Cursor` or `Range`, the recommended way is to not modify the global `*.js` files. Instead, create a `*.js` file in the local folder that is being executed later than the `05_cursor.js` and then change the `Cursor` prototype in JavaScript.

#### Cursors and Ranges

As &kappname; 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.

##### The Cursor Prototype

    Cursor();

- Constructor. Returns a Cursor at position `(0, 0)`.

  Example: `var cursor = new Cursor();`

    Cursor(int line, int column);

- Constructor. Returns a Cursor at position (line, column).

  Example: `var cursor = new Cursor(3, 42);`

    Cursor(Cursor other);

- Copy 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 other);

- Compares this cursor to the cursor `other`. Returns

  - `-1`, if this cursor is located before the cursor `other`,

  - `0`, if both cursors equal and

  - `+1`, if this cursor is located after the cursor `other`.

    bool Cursor.equals(Cursor other);

- Returns `true`, if this cursor and the cursor `other` are equal, otherwise `false`.

    String Cursor.toString();

- Returns the cursor as a string of the form `Cursor(line, column)`.

##### The Range Prototype

    Range();

- Constructor. Calling `new Range()` returns a Range at (0, 0) - (0, 0).

    Range(Cursor start, Cursor end);

- Constructor. Calling `new Range(`start`, `end`)` returns the Range (`start`, `end`).

    Range(int startLine, int startColumn, int endLine, int endColumn);

- Constructor. Calling `new Range(`startLine`, `startColumn`, `endLine`, `endColumn`)` returns the Range from (`startLine`, `startColumn`) to (`endLine`, `endColumn`).

    Range(Range other);

- Copy 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, otherwise `false`.

  Example: `var valid = range.isValid();`

    bool Range.invalid();

- Returns the Range from (-1, -1) to (-1, -1).

    bool Range.contains(Cursor cursor);

- Returns `true`, if this range contains the cursor position, otherwise `false`.

    bool Range.contains(Range other);

- Returns `true`, if this range contains the Range `other`, otherwise `false`.

    bool Range.containsColumn(int column);

- Returns `true`, if `column` is in the half open interval `[start.column, end.column)`, otherwise `false`.

    bool Range.containsLine(int line);

- Returns `true`, if `line` is in the half open interval `[start.line, end.line)`, otherwise `false`.

    bool Range.overlaps(Range other);

- Returns `true`, if this range and the range `other` share a common region, otherwise `false`.

    bool Range.overlapsLine(int line);

- Returns `true`, if `line` is in the interval `[start.line, end.line]`, otherwise `false`.

    bool Range.overlapsColumn(int column);

- Returns `true`, if `column` is in the interval `[start.column, end.column]`, otherwise `false`.

    bool Range.equals(Range other);

- Returns `true`, if this range and the Range `other` are equal, otherwise `false`.

    String Range.toString();

- Returns the range as a string of the form `Range(Cursor(line, column), Cursor(line, column))`.

#### Global Functions

This section lists all global functions.

##### Debugging

    void debug(String text);

- Prints `text` to `stdout` in the console launching the application.

##### Translation

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 &kappname; sources are automatically extracted and translatable. In other words, as a &kappname; 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 text, arg1, ...);

- Translates `text` into the language used by the application. The arguments `arg1`, ..., are optional and used to replace the placeholders `%1`, `%2`, etc.

    void i18nc(String context, String text, arg1, ...);

- Translates `text` into the language used by the application. Additionally, the string `context` is visible to translators so they can provide a better translation. The arguments `arg1`, ..., are optional and used to replace the placeholders `%1`, `%2`, etc.

    void i18np(String singular, String plural, int number, arg1, ...);

- Translates either `singular` or `plural` into the language used by the application, depending on the given `number`. The arguments `arg1`, ..., are optional and used to replace the placeholders `%1`, `%2`, etc.

    void i18ncp(String context, String singular, String plural, int number, arg1, ...);

- Translates either `singular` or `plural` into the language used by the application, depending on the given `number`. Additionally, the string `context` is visible to translators so they can provide a better translation. The arguments `arg1`, ..., are optional and used to replace the placeholders `%1`, `%2`, etc.

#### The View API

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 line, int column)
    void view.setCursorPosition(Cursor cursor)

- Returns the current cursor position in the view.

    void view.setCursorPosition(int line, int column);
    void view.setCursorPosition(Cursor cursor);

- Set 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 line, int column);
    void view.setVirtualCursorPosition(Cursor cursor);

- Set 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, otherwise `false`.

    Range view.selection();

- Returns the selected text range. The returned range is invalid if there is no selected text.

    void view.setSelection(Range range);

- Set 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.

#### The Document API

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-stream` if 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 pos);

- Returns 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), otherwise `false`.

    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 fromLine, int fromColumn, int toLine, int toColumn);
    String document.text(Cursor from, Cursor to);
    String document.text(Range range);

- Returns 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 line);

- Returns the given text line as string. The string is empty if the requested line is out of range.

    String document.wordAt(int line, int column);
    String document.wordAt(Cursor cursor);

- Returns the word at the given cursor position.

    String document.charAt(int line, int column);
    String document.charAt(Cursor cursor);

- Returns the character at the given cursor position.

    String document.firstChar(int line);

- Returns the first character in the given `line` that 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 line);

- Returns the last character in the given `line` that is not a whitespace. If the line is empty or only contains whitespace characters, the returned string is empty.

    bool document.isSpace(int line, int column);
    bool document.isSpace(Cursor cursor);

- Returns `true`, if the character at the given cursor position is a whitespace, otherwise `false`.

    bool document.matchesAt(int line, int column, int line, String text);
    bool document.matchesAt(Cursor cursor, String text);

- Returns `true`, if the given `text` matches at the corresponding cursor position, otherwise `false`.

    bool document.startsWith(int line, String text, bool skipWhiteSpaces);

- Returns `true`, if the line starts with `text`, otherwise `false`. The argument `skipWhiteSpaces` controls whether leading whitespaces are ignored.

    bool document.endsWith(int line, String text, bool skipWhiteSpaces);

- Returns `true`, if the line ends with `text`, otherwise `false`. The argument `skipWhiteSpaces` controls whether trailing whitespaces are ignored.

    bool document.setText(String text);

- Sets the entire document text.

    bool document.clear();

- Removes the entire text in the document.

    bool document.truncate(int line, int column);
    bool document.truncate(Cursor cursor);

- Truncate the given line at the given column or cursor position. Returns `true` on success, or `false` if the given line is not part of the document range.

    bool document.insertText(int line, int column, int line, String text);
    bool document.insertText(Cursor cursor, String text);

- Inserts the `text` at the given cursor position. Returns `true` on success, or `false`, if the document is in read-only mode.

    bool document.removeText(int fromLine, int fromColumn, int toLine, int toColumn);
    bool document.removeText(Cursor from, Cursor to);
    bool document.removeText(Range range);

- Removes the text in the given range. Returns `true` on success, or `false`, if the document is in read-only mode.

    bool document.insertLine(int line, String text);

- Inserts text in the given line. Returns `true` on success, or `false`, if the document is in read-only mode or the line is not in the document range.

    bool document.removeLine(int line);

- Removes the given text line. Returns `true` on success, or `false`, if the document is in read-only mode or the line is not in the document range.

    void document.joinLines(int startLine, int endLine);

- Joins the lines from `startLine` to `endLine`. 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 line);

- Returns 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 call `editBegin()`. Calling `editBegin()` 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 of `editBegin()`) finishes the edit step.

    int document.firstColumn(int line);

- Returns 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 line);

- Returns 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 line, int column);
    int document.prevNonSpaceColumn(Cursor cursor);

- Returns the column with a non-whitespace characters starting at the given cursor position and searching backwards.

    int document.nextNonSpaceColumn(int line, int column);
    int document.nextNonSpaceColumn(Cursor cursor);

- Returns the column with a non-whitespace characters starting at the given cursor position and searching forwards.

    int document.prevNonEmptyLine(int line);

- Returns the next non-empty line containing non-whitespace characters searching backwards.

    int document.nextNonEmptyLine(int line);

- Returns the next non-empty line containing non-whitespace characters searching forwards.

    bool document.isInWord(String character, int attribute);

- Returns `true`, if the given `character` with the given `attribute` can be part of a word, otherwise `false`.

    bool document.canBreakAt(String character, int attribute);

- Returns `true`, if the given `character` with the given `attribute` is suited to wrap a line, otherwise `false`.

    bool document.canComment(int startAttribute, int endAttribute);

- Returns `true`, if a range starting and ending with the given attributes is suited to be commented out, otherwise `false`.

    String document.commentMarker(int attribute);

- Returns the comment marker for single line comments for a given `attribute`.

    String document.commentStart(int attribute);

- Returns the comment marker for the start of multi-line comments for a given `attribute`.

    String document.commentEnd(int attribute);

- Returns the comment marker for the end of multi-line comments for a given `attribute`.

    int document.attribute(int line, int column);
    int document.attribute(Cursor cursor);

- Returns the attribute at the given cursor position.

    bool document.isAttribute(int line, int column, int attribute);
    bool document.isAttribute(Cursor cursor, int attribute);

- Returns `true`, if the attribute at the given cursor position equals `attribute`, otherwise `false`.

    String document.attributeName(int line, int column);
    String document.attributeName(Cursor cursor);

- Returns the attribute name as human readable text. This equals to the `itemData` name in the syntax highlighting files.

    bool document.isAttributeName(int line, int column, String name);
    bool document.isAttributeName(Cursor cursor, String name);

- Returns `true`, if the attribute name at a certain cursor position matches the given `name`, otherwise `false`.

    String document.variable(String key);

- Returns 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 key, String value);

- Set 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 line);

- Returns 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 line);

- Returns 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 line, int column);
    int document.toVirtualColumn(Cursor cursor);
    Cursor document.toVirtualCursor(Cursor cursor);

- Converts the given real cursor position to a virtual cursor position, either returning an int or a Cursor object.

    int document.fromVirtualColumn(int line, int virtualColumn);
    int document.fromVirtualColumn(Cursor virtualCursor);
    Cursor document.fromVirtualCursor(Cursor virtualCursor);

- Converts the given virtual cursor position to a real cursor position, either returning an int or a Cursor object.

    Cursor document.anchor(int line, int column, Char character);
    Cursor document.anchor(Cursor cursor, Char character);

- Searches 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 line, int column, String text, int attribute = -1);
    Cursor document.rfind(Cursor cursor, String text, int attribute = -1);

- Find backward the given text with the appropriate `attribute`. The argument `attribute` is ignored if it is set to `-1`. The returned cursor is invalid, if the text could not be found.

    int document.defStyleNum(int line, int column);
    int document.defStyleNum(Cursor cursor);

- Returns the default style used at the given cursor position.

    bool document.isCode(int line, int column);
    bool document.isCode(Cursor cursor);

- Returns `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 line, int column);
    bool document.isComment(Cursor cursor);

- Returns `true`, if the attribute of the character at the cursor position is `dsComment`, otherwise `false`.

    bool document.isString(int line, int column);
    bool document.isString(Cursor cursor);

- Returns `true`, if the attribute of the character at the cursor position is `dsString`, otherwise `false`.

    bool document.isRegionMarker(int line, int column);
    bool document.isRegionMarker(Cursor cursor);

- Returns `true`, if the attribute of the character at the cursor position is `dsRegionMarker`, otherwise `false`.

    bool document.isChar(int line, int column);
    bool document.isChar(Cursor cursor);

- Returns `true`, if the attribute of the character at the cursor position is `dsChar`, otherwise `false`.

    bool document.isOthers(int line, int column);
    bool document.isOthers(Cursor cursor);

- Returns `true`, if the attribute of the character at the cursor position is `dsOthers`, otherwise `false`.