
== User-defined Tools ==[sect-user-tools]

APPNAME allows extending its functionality with user-defined
//tools//. It can be a Lua or Python (provided APPNAME has been
built with Python support) script which is executed inside APPNAME,
or a shell script which can use the text of the open document as
its input and/or output.

There are some predefined tools which you can use as
an example or to modify to suit your needs.


=== Managing tools ===[prefs-user-tools]

To create a new tool or to modify existing ones, open
//Preferences// dialog and select //Tools// in the list on the left.

Select the tool in the list or click the //New//
button to create a new one. To modify the order in which the tools
appear in the //Tools// menu (or in the document
context menu), use //Up// and //Down// buttons. To rename a tool,
click its name in the list to select it and then click again to
edit the name. Use the //Delete// button to delete a tool.

The following controls are available to modify the tools behavior:

| //Files//             | Specifies for which files the tool is going to be available. |
| //Options//           | Specifies under which conditions the tool should be enabled.
| //Command type//      | The type of the tool: a Python script, a Lua script, or a shell script.
| //Code text field//   | Here you enter the actual script text.


//Files// entry content is a comma-separated list of the following:
| ``need-doc``          | the tool needs an open document |
| ``need-file``         | the tool will not work in new unsaved documents.
| ``need-save``         | the document will be saved before the command is executed.
| ``need-save-all``     | all open documents will be saved before the command is executed.


//Options// entry content can be the following:
- a comma-separated list of file patterns, e.g. "``*.c,*.h``";
- a comma-separated list of languages prefixed with "``langs:``", e.g. "``langs: c, c++, objc``";
- a regular expression matching document filename prefixed with "``regex:``", e.g. the above
pattern list may be written as "``regex:\.[ch]$``".


Empty entry means that the tool will be available for all documents.



Shell script tools also have the following controls available:

//Input// entry specifies what text from the document should be passed to the command via its standard input:
| ``None``              | no input text. |
| ``Selected lines``    | the lines containing selection or the line containing the cursor in case when no text is selected.
| ``Selection``         | exact selected text. This will be different from "Selected lines" if selection does not span whole lines of the document, for instance if it is a single word.
| ``Whole document``    | whole document contents.


//Output// entry specifies how the standard output of the command should be redirected.
| ``None``                      | the command output will be suppressed. |
| ``None, asynchronous``        | the command output will be suppressed, and the command will be executed in background. For instance, you should use this if you need to launch some external program like a web browser.
| ``Output pane``               | the command output will be displayed in an output pane. This is useful for running programs like compilers, where you want to see the output.
| ``Insert into the document``  | output will be inserted into the current document at the cursor position. It will replace the text used as an input, if any.
| ``New document``              | new document will be created and the command output will be inserted into it.


//Filter// combo. If the output pane is used, then it can be passed through a //filter//:
the filter can match filenames and line numbers, so when you click the text in the
output pane it will open the corresponding file. This is used for compilers and similar
commands, which output locations of errors in processed files.


=== Storing tools in files ===[user-tools-files]

It is possible to create tools without using the //Preferences// dialog,
they can be stored in files in ``tools`` subfolder of the APPNAME data
folders (or ``tools-context`` for tools which appear in the document context
menu). In particular, on Unix systems you can place files into
``$HOME/.local/share/APPNAME/tools/`` folder.

Names of the files in the ``tools`` folder are used as their menu item
labels, after stripping first three characters, so you can use trhee-character
prefix to affect the order of the menu items, e.g. you can have ``00-Do Something``,
``01-Another tool`` files to have them in that order in the menu. The files
may be of three types: files with extension "``.py``", they will be used
as Python scripts; files with extension "``.lua``", they will be used
as Lua scripts; and executable files, they will be executed in the same way
as shell commands.

To set parameters for a tool, place them on the first or the second line of the file in
the following format:
```
!! @em{key}=@em{value}; @em{key}=@em{value}; ... !!
```

//key// may be one of the following:
| ``position``      | it can be ``start`` or ``end``, and defines whether the menu item will be located at the start or at the end of the menu. |
| ``id``            | the tool identificator.
| ``name``          | the tool name, i.e. the label used in the menu item. Overrides the file name.
| ``os``            | ``windows`` or ``unix``. If specified, then the tool will not be used when APPNAME is running on a different operating system.
| ``accel``         | default keyboard accelerator used to invoke this tool.
| ``menu``          | the menu to place this tool into. By default the tools are located in the Tools menu, but they can be as well put into any other menu.
| ``langs``         | comma-separated list of languages for which this tool will be enabled.
| ``file-filter``   | defines for which files this tool will be enabled. The value has the same format as in the //Preferences// dialog.
| ``options``       | same as the //Options// entry content in the //Preferences// dialog.

In addition to these, you can set input and output options for executable files:

| ``input``         | can be ``none``, ``lines``, ``selection``, or ``doc``. |
| ``output``        | can be ``none``, ``async``, ``pane``, ``insert``, or ``new-doc``.
| ``filter``        | the output filter name.


=== Python scripts ===[user-tools-python]

If APPNAME is built with Python support, then Python scripts have full access to the program
internals via builtin ``moo`` module. APPNAME classes extend classes from ``pygtk``,
in particular the ``moo.edit.Edit`` class representing documents extends the
``gtk.TextView`` class, and all editing operations can be implemented using
``pygtk`` API.

Python scripts executed from inside APPNAME have ``LIBDIR/plugins/lib``
and ``USERDATADIR/plugins/lib`` directories added to ``sys.path``,
you can place there APPNAME-specific modules to be used from python tools.

Python scripts have the following variables predefined:

| ``doc``       | the current document object. |
| ``window``    | the current editor window.
| ``buffer``    | the text buffer (a ``moo.edit.TextBuffer`` instance) of the current document.
| ``editor``    | the ``moo.edit.Editor`` object representing the text editor. Use its methods to open/close files, switch between documents and windows, etc.
| ``moo``       | the ``moo`` module, already imported so you can omit ``import moo`` statement in scripts.


=== Lua scripts ===[user-tools-lua]

Lua scripts can use the standard Lua library, ``lfs`` library, and ``medit`` package
which provides some text editor API. Lua scripts have the following variables and functions available.

- ``doc``: a table with the following fields:
  | ``file``     | the document file path. |
  | ``name``     | the document file basename.
  | ``dir``      | the document file directory.
  | ``ext``      | the document filename extension including the period.
  | ``base``     | the document filename without the extension: the basename is always ``base..ext``.
- ``Cut()``, ``Copy()``, ``Paste()``: clipboard operations.
- ``Backspace()``, ``Delete()``: corresponding key actions.
- ``Up()``, ``Down()``, ``Left()``, ``Right()``: move cursor as the arrow keys do.
- ``Selection()``: returns selected text as a string. Returns ``nil`` when no text is selected.
- ``Select(n)``: selects ``n`` characters to the right if ``n`` is positive, and ``-n`` characters to the left if it is negative.
- ``Insert(...)``: inserts text at cursor. Namely, it converts each argument to a string and inserts the result into the document.
- ``NewLine()``: inserts new line character.

The following functions are provided for more advanced text manipulation. Position in the
document is denoted by the character offset from the beginning of the document, starting
from 1, so the first character is at position 1. Functions which take or return ranges use pairs of
offsets, a pair ``start``, ``end`` denotes range of text from
``start`` to ``end``, **not** including the character at offset ``end``. For instance, the
single-character range consisting of the first character in the document corresponds to the
pair ``1, 2``. Non-positive offset denotes the end of the document.

- ``InsertText(pos, ...)``: inserts text at the position ``pos``.
- ``DeleteText(start, end)``: deletes text in the range ``[start..end)``.
- ``GetInsert()``: returns position of the cursor in the document.
- ``GetSelectionBounds()``: returns positions of the selection start and end. If no text is
  selected, returns pair ``pos, pos`` where ``pos`` is the cursor position.
- ``GetLine([pos])``: returns line number of the character at the position ``pos``. If ``pos``
  is not specified, it defaults to the cursor position.
- ``GetPosAtLine(n)``: returns position at the beginning of the ``n``-th line.
- ``LineStart([pos])``: returns the position of the beginning of the line which contains character at ``pos``.
  If ``pos`` is not specified, it defaults to the cursor position.
- ``LineEnd([pos])``: returns the position of the end of the line which contains character at ``pos``.
  If ``pos`` is not specified, it defaults to the cursor position.
- ``ForwardLine([pos, [n]])``: returns the position of the beginning of the next line (or
  ``n``-th line if ``n`` is specified). ``pos`` defaults to the cursor position if not
  specified.
- ``BackwardLine([pos, [n]])``: returns the position of the beginning of the previous line
  (or ``n``-th line backwards if ``n`` is specified). ``pos`` defaults to the cursor position
  if not specified.
- ``GetText(start, end)``: returns the text in the ``[start..end)``. If ``start == end``, it
  returns an empty string, not ``nil``.


=== Shell scripts ===[user-tools-shell]

In addition to the document text passed via standard input,
shell scripts have a number of environment variables set. ``$APP_PID``
variable is set to the current process process id, so that opening a file in the
same instance of APPNAME is as simple as ``APPNAME filename`` (on the other
hand, you will have to use command line options if you need to run a new APPNAME instance).
The following environment variables are set when scripts are executed:

| ``DOC``       | the document basename. |
| ``DOC_DIR``   | the document file directory. The full file path is ``$DOC_DIR/$DOC``.
| ``DOC_BASE``  | the basename without extension.
| ``DOC_EXT``   | the document filename extension including the period. The basename is always ``$DOC_BASE$DOC_EXT``.
| ``LINE``      | the number of the line containing cursor.
| ``DATA_DIR``  | the user data directory. For example the tools are stored in ``$DATA_DIR/menu.cfg`` file and in files in the ``$DATA_DIR/tools/`` directory.

Additionally, all processes ran from inside APPNAME will have ``DATADIR/scripts``
directories in ``$PATH``, so you may place some APPNAME-specific programs
or scripts into ``USERDATADIR/scripts/`` to be used from shell script tools.
