# Scripting

## Scripting in &kile;

&kile;'s scripting feature allows the execution of ECMAScript code, widely known as &javascript;. You will find a lot of tutorials, which provide information about objects (variables), functions and properties supported by &javascript;.

Scripting support can be enabled in the configuration dialog of &kile;: Settings Configure Kile... Kile Scripting. Enable or disable scripting support Enable or disable scripting support

If scripting is enabled, an additional scripting panel is visible in the sidebar, where scripts can be managed: Scripting panel in the sidebar Scripting panel in the sidebar

This widget contains six icons, which offer different tasks:

- Run the selected script.

- Create a new script.

- Open the selected script in the editor.

- Configure a key sequence for the selected script.

- Remove an assigned key sequence.

- Refresh the list of available scripts, which are all found in `$`KDEDIR`/share/apps/kile/scripts/`.

## Executing a Script

You can execute a script in three different ways:

1. Select the desired script and click on the Execute button on the left side of the script management widget.

   Scripting: execute button Scripting: execute button

2. Use a keyboard shortcut.

   Scripting: keyboard shortcut Scripting: keyboard shortcut

   You can assign a keyboard shortcut to a script using the Configure button in the script management widget.

   Scripting: configure sequence dialog Scripting: configure sequence dialog

3. Use an editor key sequence. The script will be executed, if you type the assigned key sequence in the editor.

   Scripting: editor key sequence Scripting: editor key sequence

   This method can be extended to a rather sophisticated kind of code completion. Let us assume that you have a written a script, which simply inserts the &latex; command `\textbf{}` into the current document.

       document.insertText("\\textbf{%C}");

   If you now type the assigned key sequence `bfx` in your text document, this key sequence will be removed and the script will be executed. It will insert `\textbf{}` and the cursor is placed between the braces.

   Scripting: typing an editor key sequence Scripting: typing an editor key sequence

   What a comfortable and powerful method of code completion.

## API Reference

The scripting API presented here is available in all scripts. Before the contents of a script is loaded, &kile; 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 `KILE_APP_DIR/script-plugins/`.

&kile; scripts differ slightly from &kate; scripts, which use another design, as they also can be started from the command line. But all functions of the &kate; scripting API are also available in &kile;'s scripting API, so porting &javascript; code from &kate; to &kile; should be very easy. But as &kile; is a very rich featured &latex; editor, its own scripting API offers many more possibilities than &kate;'s one.

Remark: Description of API calls, which are also available in &kate; scripting, have been taken from &kate;'s documentation.

### Global Functions

This section lists global functions.

    void debug(String text);

- Prints `text` to `stdout` in the console. The printed text is colored to distinguish it from other debug output.

### The Cursor Prototype

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

    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 a 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

As &kile; is a text editor, all the scripting API is based on cursors and ranges whenever possible. As 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.

    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 from cursor `start` to cursor `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))`.

### The View API

Whenever a script is being executed, there is a global object (variable) `view` representing the current active editor view. All functions of `view` work with cursor positions or selected text. The following is a list of all available `view` functions.

    void view.backspace();

- Programmatically performs the equivalent of pressing the backspace key.

    Cursor view.cursorPosition();

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

    void view.cursorLeft();

- Moves the cursor one position backward in the text.

    void view.cursorRight();

- Moves the cursor one position forward in the text.

    void view.cursorUp();

- Moves the cursor one line up in the document.

    void view.cursorDown();

- Moves the cursor one line down in the document.

    int view.cursorLine();

- Returns the line which the cursor is currently located at.

    int view.cursorColumn();

- Returns the column which the cursor is currently located at.

    void view.setCursorLine(int line);

- Set the cursor line to the given `line`.

    void view.setCursorColumn(int column);

- Set the cursor column to the given `column`.

    Cursor view.virtualCursorPosition();

- Get the current virtual cursor position. Virtual means the tabulator character (TAB) counts multiple characters, as configured by the user (e.g. one TAB is 8 spaces). The virtual cursor position provides access to the user visible values of the current cursor position.

    bool view.hasSelection();

- Returns `true`, if the view has selected text, otherwise `false`.

    String view.selectedText();

- Returns the selected text. If no text is selected, the returned string is empty.

    Range view.selectionRange();

- 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.selectAll();

- Selects the entire text in the document.

    void view.clearSelection();

- Clears the text selection without removing the text.

    void view.removeSelectedText();

- Remove the selected text. If the view does not have any selected text, this does nothing.

    void view.selectLine();

- Selects the text in the current line.

    void view.selectLine(int line);

- Selects the text in the given `line`.

    void view.selectLines(int from, int to);

- Selects the entire text from line `from` to line `to`.

    void view.selectWord();

- Selects the current word. If no word is found at the current cursor position, nothing is done.

    void view.selectLatexCommand();

- Selects the current &latex; command. If no command is found at the current cursor position, nothing is done.

    void view.selectEnvironment(bool inside = false);

- Selects the entire text of the current &latex; environment. If `inside` is `false`, the environment text including the surrounding &latex; tags `\begin{...}...\end{...}` will be selected, else without these tags. If no parameter is given, `inside` is set to `false`.

    void view.selectTexgroup(bool inside = true);

- Selects the text of the current &latex; group. If `inside` is `true`, only the texgroup without the surrounding braces will be selected. If no parameter is given, `inside` is set to `true`.

    void view.selectMathgroup();

- Selects the text of the current math group.

    void view.selectParagraph(bool wholeLines = true);

- Selects the entire text of the current &latex; paragraph. If `wholeLines` is `true`, the first and the last lines of the paragraph will be included in the selection entirely (including the end-of-line character); otherwise, the selection will only contain non-whitespace characters.

### The Document API

Whenever a script is being executed, there is a global object (variable) `document` representing the current active document. The following is a list of all available `document` functions.

    void document.insertText(String text);

- Inserts the `text` at the current cursor position.

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

- Inserts the `text` at the given cursor position.

    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.replaceText(Range range, String text);

- Replace the text of the given range with the specified text.

    int document.lines();

- Returns the number of lines in the document.

    int document.length();

- Returns the number of characters in the document.

    Range document.documentRange();

- Returns a range which encompasses the whole document.

    Cursor document.documentEnd();

- Returns the current cursor position of the document's end.

    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.

    bool document.setText(String text);

- Sets the entire document text.

    bool document.clear();

- Removes the entire text in the document.

    String document.line();

- Returns the current text line as string.

    String document.line(int line);

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

    int document.lineLength();

- Returns the length of the current line.

    int document.lineLength(int line);

- Returns the `line`'s length.

    bool document.insertLine(String s);

- Inserts text in the current 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.insertLine(int line, String s);

- 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();

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

    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.

    bool document.replaceLine(String text);

- Replace the text of the current line with the specified text.

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

- Replace the text of the given line with the specified text.

    bool document.truncateLine();

- Truncate the current 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.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.

    String document.word();

- Returns the word at the current cursor position. If no word is found at this cursor position, the returned string is empty.

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

- Returns the word at the given cursor position. If no word is found at this cursor position, the returned string is empty.

    Range document.wordRange();

- Returns the range of the word at the given cursor position. If no word is found, `Range.invalid()` is returned, which can be tested with `Range.isValid()`.

    String document.latexCommand();

- Returns the &latex; command at the current cursor position. If no command is found at this cursor position, the returned string is empty.

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

- Returns the &latex; command at the given cursor position. If no command is found at this cursor position, the returned string is empty.

    Range document.latexCommandRange();

- Returns the range of the &latex; command at the given cursor position. If no &latex; command is found, `Range.invalid()` is returned, which can be tested with `Range.isValid()`.

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

    void document.insertBullet();

- Insert a &kile; bullet. Remember that you can easily jump to the next or previous bullet. This will also highlight this bullet so that it will be deleted automatically, when you enter your first letter.

    void document.nextBullet();

- Jump to the next bullet in the text if there is one.

    void document.previousBullet();

- Jump to the previous bullet in the text if there is one.

    bool document.hasEnvironment();

- Returns `true` if a surrounding &latex; environment is found, else `false`.

    String document.environment(bool inside = false);

- Returns the entire text of the surrounding &latex; environment. If `inside` is `false`, the environment text including the surrounding &latex; tags `\begin{...}...\end{...}` will be returned, else without these tags. If no parameter is given, `inside` is set to `false`. If no environment is found, the returned string is empty.

    Range document.environmentRange(bool inside = false);

- Returns the range of the surrounding &latex; environment. If `inside` is `false`, the range including the surrounding &latex; tags `\begin{...}...\end{...}` will be returned, else without these tags. If no parameter is given, `inside` is set to `false`. If no environment is found, `Range.invalid()` is returned, which can be tested with `Range.isValid()`.

    String document.environmentName();

- Returns the name of the surrounding &latex; environment or an empty string.

    void document.removeEnvironment(bool inside = false);

- Removes the text of the surrounding &latex; environment. If `inside` is `false`, the environment text including the surrounding &latex; tags `\begin{...}...\end{...}` will be removed, else without these tags. If no parameter is given, `inside` is set to `false`.

    void document.closeEnvironment();

- Insert a closing environment tag, if an opened &latex; environment is found at the current cursor position.

    void document.closeAllEnvironments();

- Insert closing environment tags for all opened &latex; environments, which were found at the current cursor position.

    bool document.hasTexgroup();

- Returns `true` if a surrounding &latex; group is found at the current cursor position, else `false`.

    String document.texgroup(bool inside = true);

- Returns the text of the surrounding &latex; group. If `inside` is `false`, the text of this &latex; group including the surrounding braces `{...}` will be returned, else without them. If no parameter is given, `inside` is set to `false`. The returned string is empty, if no surrounding &latex; group is found at the current cursor position.

    Range document.texgroupRange(bool inside = true);

- Returns the range of the surrounding &latex; group. If `inside` is `false`, the range including the surrounding braces `{...}` will be returned, else without them. If no parameter is given, `inside` is set to `false`. If no group is found, `Range.invalid()` is returned, which can be tested with `Range.isValid()`.

    void document.removeTexgroup(bool inside = true);

- Removes the text of the surrounding &latex; group. If `inside` is `false`, the text of this &latex; group including the surrounding braces `{...}` will be removed, else without them. If no parameter is given, `inside` is set to `false`.

    bool document.hasMathgroup();

- Returns `true` if a surrounding &latex; mathgroup is found at the current cursor position, else `false`.

    String document.mathgroup();

- Returns the text of the surrounding &latex; mathgroup. The returned string is empty, if no surrounding &latex; mathgroup is found at the current cursor position.

    Range document.mathgroupRange();

- Returns the range of the surrounding &latex; mathgroup. If there is no surrounding mathgroup, `Range.invalid()` is returned, which can be tested with `Range.isValid()`.

    void document.removeMathgroup();

- Removes the text of the surrounding &latex; mathgroup.

    String document.paragraph();

- Returns the text of the current &latex; paragraph.

    Range document.paragraphRange();

- Returns the range of the surrounding &latex; paragraph.

    void document.removeParagraph();

- Removes the text of the current &latex; paragraph.

    bool document.matchesAt(int line, int column, 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 pattern, bool skipWhiteSpaces = true);

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

    bool document.endsWith(int line, String pattern, bool skipWhiteSpaces = true);

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

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

    void document.gotoBeginEnv();

- Go to the start of a surrounding &latex; environment.

    void document.gotoEndEnv();

- Go to the end of a surrounding &latex; environment.

    void document.gotoBeginTexgroup();

- Go to the start of a surrounding &latex; group.

    void document.gotoEndTexgroup();

- Go to the end of a surrounding &latex; group.

    void document.gotoNextParagraph();

- Go to the next &latex; paragraph.

    void document.gotoPrevParagraph();

- Go to the previous &latex; paragraph.

    void document.gotoNextSectioning();

- Go to the next &latex; section.

    void document.gotoPrevSectioning();

- Go to the previous &latex; section.

    void document.gotoLine(int line);

- Go to the given `line`.

    void document.insertChapter();

- Insert a `\chapter` command (see also `document.insertSection()`).

    void document.insertSection();

- Insert a `\section` command. As with choosing the menu entry LaTeX Sectioning section a dialog will appear, where you can choose the title and an optional label for this sectioning command. Dialog: insert chapter command Dialog: insert chapter command

    void document.insertSubsection();

- Insert a `\subsection` command (see also `document.insertSection()`).

    void document.insertSubsubsection();

- Insert a `\subsubsection` command (see also `document.insertSection()`).

    void document.insertParagraph();

- Insert a `\paragraph` command (see also `document.insertSection()`).

    void document.insertSubparagraph();

- Insert a `\subparagraph` command (see also `document.insertSection()`).

    void document.insertLabel();

- Insert a `\label` command.

    void document.insertReference();

- Insert a `\ref` command. As with choosing the menu entry &latex;References ref a dialog will appear, where you can choose from already defined labels, which are listed in a combobox. Dialog: insert a reference command Dialog: insert a reference command

    void document.insertPageref();

- Insert a `\pageref` command (see also `document.insertReference()`).

    void document.insertCitation();

- Insert a `\cite` command.

    void document.insertIndex();

- Insert a `\index` command.

    void document.insertFootnote();

- Insert a `\footnote` command.

    void document.comment();

- Inserts comment markers to make the selection or current line a comment.

    void document.uncomment();

- Removes comment markers from the selection or current line.

    void document.uppercase();

- Put the selected text or the letter after the cursor in uppercase.

    void document.lowercase();

- Put the selected text or the letter after the cursor in lowercase.

    void document.capitalize();

- Capitalize the selected text or the current word.

    void document.joinLines();

- Joins the lines of the current selection. Two succeeding text lines are always separated with a single space.

    void document.insertIntelligentNewline();

- Insert a smart newline (see editing_smartnewline).

    void document.insertIntelligentTabulator();

- Insert a smart tabulator (see editing_tabulator).

    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.

    StringList document.labelList();

- Returns all defined labels as a `StringList`, which can be used in &javascript; as an array of strings.

    StringList document.bibitemList();

- Returns all defined bibitems as a `StringList`, which can be used in &javascript; as an array of strings.

    void document.refreshStructure();

- Refresh the structure view (see navigating).

### The &kile; API

The global object (variable) `kile` is used to handle top level interactions with the outside world, input message and dialog interfaces. These API calls are divided into subobjects to structure this part of the scripting API. Conceptually `kile` is a bit like `window` in a browser API.

- `kile.alert`: message boxes

- `kile.input`: get user input

- `kile.wizard`: call one of &kile;'s wizards

- `kile.script`: get info about a running script

- `kile.file`: file operations like read and write.

#### Alert

    void kile.alert.information(String text, String caption);

- Display an Information dialog. `text` is the message string and `caption` the title of the message box. The default title is the script name.

    void kile.alert.sorry(String text, String caption);

- Display a Sorry dialog. `text` is the message string and `caption` the title of the message box. The default title is the script name.

    void kile.alert.error(String text, String caption);

- Display an Error dialog. `text` is the message string and `caption` the title of the message box. The default title is the script name.

    String kile.alert.question(String text, String caption);

- Display a simple question dialog. `text` is the message string and `caption` the title of the message box. The default title is the script name. The returned string is either `yes` or `no`.

    String kile.alert.warning(String text, String caption);

- Display a simple warning dialog. `text` is the message string and `caption` the title of the message box. The default title is the script name. The returned string is either `continue` or `cancel`.

#### Input

    String kile.input.getListboxItem(String caption, String label, StringList list);

- Function to let the user select an item from a list, which is shown as a listbox. `caption` is the text that is displayed in the title bar, `label` is the text that appears as the label for the list and `list` is the string list which is inserted into the list.

    String kile.input.getComboboxItem(String caption, String label, StringList list);

- Function to let the user select an item from a list, which is shown as a combobox. `caption` is the text that is displayed in the title bar, `label` is the text that appears as the label for the list and `list` is the string list which is inserted into the list.

    String kile.input.getText(String caption, String label);

- Function to get a string from the user. `caption` is the text that is displayed in the title bar and `label` the text that appears as a label for the line edit.

    String kile.input.getLatexCommand(String caption, String label);

- Function to get a &latex; command from the user. This means that only lower- and uppercase letters are allowed. `caption` is the text that is displayed in the title bar and `label` the text that appears as a label for the line edit.

    int kile.input.getInteger(String caption, String label, int min = INT_MIN, int max = INT_MAX);

- Function to get an integer from the user. `caption` is the text that is displayed in the title bar. `label` is the text that appears as the label for the spin box. `min` and `max` are the minimum and maximum allowable values the user may choose. Default values are `INT_MIN` and `INT_MAX`.

    int kile.input.getPosInteger(String caption, String label, int min = 1, int max = INT_MAX);

- Function to get a positive integer from the user. `caption` is the text that is displayed in the title bar. `label` is the text that appears as the label for the spin box. `min` and `max` are the minimum and maximum allowable values the user may choose. Default values are `1` and `INT_MAX`.

#### Wizard

    void kile.wizard.tabular();

- Calls the Tabular wizard, which helps to write a tabular environment (see wizard_array).

    void kile.wizard.array();

- Calls the Array wizard, which helps to write an array environment (see wizard_array).

    void kile.wizard.tabbing();

- Calls the Tabbing wizard, which helps to write a tabbing environment (see wizard_array).

    void kile.wizard.floatEnvironment();

- Calls the Floats wizard, which helps to insert floating elements (see wizard_float).

    void kile.wizard.mathEnvironment();

- Calls the Math wizard, which helps to insert math environments (see wizard_math).

    void kile.wizard.postscript();

- Calls the Postscript Tools wizard, which may help to manipulate or rearrange Postscript documents (see wizard_postscript).

#### Script

    String kile.script.name();

- Returns the basename of a running script (without path and extension).

    String kile.script.caption();

- Returns a string, which can be used as a caption of alert boxes. It looks like `Script: scriptname.js`.

#### File

    Object kile.file.read(String filename);

- Read the contents of a text file. It is used like

  Example: `var res = kile.file.read("path/to/file.txt");`

  The return value `res` is an object (better: a map) with three properties:

  - status: Gives the status code of the operation, which can be 0 (no error), 1 (access failed) or 2 (access denied). So, if no error occurred, the value of `res.status` or `res["status"]` will be 0.

  - result: Contains the text of the given file.

  - message: Contains an error message, if an error occurred.

    Object kile.file.read();

- The same as `read(filename)`, but no filename is given. A dialog will appear to select the file to read.

    Object kile.file.write(String filename, String text);

- Write the given text into a file. It is used like

  Example: `var res = kile.file.write("path/to/file.txt","Some text...");`

  The return value `res` is an object (better: a map) with two properties: `status` and `message` (see `read()` for more information).

    Object kile.file.write(String text);

- The same as `write(filename,text)`, but no filename is given. A dialog will appear to choose a filename.

    String kile.file.getOpenFileName(String startDir, String filter);

- Creates a modal file dialog and return the selected filename or an empty string if none is chosen. Note that with this method the user must select an existing filename.

  Parameters:

  - startDir: Starting directory of the open dialog.

  - filter: A shell glob or a mime-type-filter that specifies which files to display. Refer to the KFileDialog documentation for more information on this parameter.

  Both parameters are optional. If you omit `filter`, all files will be displayed. If additionally `startDir` is omitted, the dialog will take the current document directory as starting point.

    String kile.file.getSaveFileName(String startDir, String filter);

- Creates a modal file dialog and returns the selected filename or an empty string if none is chosen. Note that with this method the user need not select an existing filename. See `getOpenFileName()` for an explanation of the parameters.

## Examples

Some examples may help you to understand how to use the scripting API. These examples and some more are found in the scripting directory of &kile;: `KILE_APP_DIR/scripts/`. Each script contains a short description.

### Example 1: replace environment name

Replace a surrounding &latex; environment with another, where the relative cursor position will not be changed. `\begin{abc}...\end{abc}` for example can be changed to `\begin{xyz}...\end{xyz}`.

    var range = document.environmentRange(false);
    if ( range.isValid() ) {
    	var envname = kile.input.getLatexCommand("Enter Environment","New environment name:");
    	if ( envname != '' ) {
    		replaceEnvCommand(envname,range);
    	}
    }
    else {
    	kile.alert.sorry("No surrounding LaTeX environment found.");
    }

    function replaceEnvCommand(newEnv,r)
    {
    	var c = view.cursorPosition();

    	var envname = document.environmentName();

    	if ( envname != "" ) {
    		var beginRange = new Range(r.start,new Cursor(r.start.line,r.start.column+8+envname.length));
    		var endRange = new Range(new Cursor(r.end.line,r.end.column-6-envname.length),r.end);

    		document.editBegin();
    		document.replaceText(endRange,"\\end{"+newEnv+"}");
    		document.replaceText(beginRange,"\\begin{"+newEnv+"}");
    		document.editEnd();
    	}
    }

### Example 2: replace a &latex; font command

Replace a surrounding &latex; font command with another font command, when the cursor is placed inside the texgroup. The relative cursor position will not be changed. `\textbf{abc}` for example can be changed to `\textit{abc}`.

    var fontCommands = new Array("\\textbf","\\textit","\\textsl","\\texttt",
                                 "\\textsc","\\textrm","\\textsf","\\emph");

    var range = document.texgroupRange(false);
    if ( range.isValid() ) {
    	replaceFontCommand(range);
    }
    else {
    	kile.alert.sorry("No surrounding TeX group found.");
    }

    function replaceFontCommand(r)
    {
    	var c = view.cursorPosition();

    	document.editBegin();
    	view.setCursorPosition(r.start);
    	var cmd = document.latexCommand();
    	var index = fontCommands.indexOf(cmd);
    	if ( index >= 0 ) {
    		var cmdRange = document.latexCommandRange();
    		if ( cmdRange.isValid() ) {
    			var newcommand = kile.input.getListboxItem("Choose",
    			                            "Choose font command:",buildCmdList(cmd));
    			if ( newcommand != "" ) {
    				document.replaceText(cmdRange,newcommand);
    				c.column = c.column - (cmd.length - newcommand.length);
    			}
    		}
    /		view.setCursorPosition(c);
    	}
    	else {
    		kile.alert.sorry("No surrounding font command found.");
    	}
    	document.editEnd();
    }

    function buildCmdList(current)
    {
    	var result = new Array();
    	for ( i=0; i<fontCommands.length; ++i ) {
    		if ( fontCommands[i] != current ) {
    			result.push(fontCommands[i]);
    		}
    	}
    	return result;
    }

### Example 3: surround selected text

Surround selected text with a TeX command, where the relative cursor position will not be changed. `abc` for example can be changed to `\texcommand{abc}`.

    var range = view.selectionRange();

    if ( range.isValid() ) {
    	var cmd = kile.input.getLatexCommand("Choose","Choose surrounding LaTeX command:");
    	if ( cmd != "" ) {
    		surroundTexCommand("\\"+cmd,range);
    	}
    }
    else {
    	kile.alert.sorry("No selection found.");
    }

    function surroundTexCommand(cmd,r)
    {
    	var c = view.cursorPosition();

    	document.editBegin();
    	view.clearSelection();
    	document.insertText(r.end,"}");
    	document.insertText(r.start,cmd+"{");

    	c.column = c.column + cmd.length + 2;
    	view.setCursorPosition(c);
    	document.editEnd();
    }