Lua scripting plugin for the Geany IDE



The Geany module provides these functions and variables...



Editor functions System functions Dialog functions



Editor functions:
  function activate ( tab_id )
-- Focus the specified editor tab.
  function appinfo ()
-- Return information about the current Geany instance.
  function batch ( start )
-- Set a marker for a reversible group of operations.
  function byte ( [position] )
-- Get the numeric value of the character at position.
  function caret ( [position] )
-- Get or set the caret position.
  function close ( [filename]|[index] )
-- Close a document.
  function copy ( [content]|[start,stop] )
-- Copy text to the clipboard.
  function count ()
-- Get the number of open tabs.
  function cut ()
-- Cut selection to the clipboard.
  function documents ( [doc_id] )
-- Access the list of all open documents.
  function filename ()
-- Get the name of the current document.
  function fileinfo ()
-- Return some information about the current document.
  function find ( phrase, start, stop, options )
-- Search for text within the document.
  function height ()
-- Get the number of lines in the current document
  function keycmd ( command )
-- Activate a built-in Geany menu command.
  function keygrab ( [prompt] )
-- Intercept a keystroke from Geany.
  function length ()
-- Get number of characters in the current document.
  function lines ( [index] )
-- Get the text on one specific line, or all of them.
  function match ( [position] )
-- Find a matching bracket, parenthesis, etc.
  function navigate ( mode,count [,extend [,rect]])
-- Move the caret incrementally.
  function newfile ( [filename] )
-- Create a new document.
  function open ( [filename]|[index] )
-- Open or reload a file from disk.
  function paste ()
-- Paste text from the clipboard.
  function rowcol ( [pos]|[row,col] )
-- Translate between linear and rectangular locations.
  function save ( [filename]|[index] )
-- Save an open document to a disk file.
  function scintilla ( msg_id, wparam, lparam )
-- Send a message directly to the Scintilla widget.
  function select ( [[start,] stop] )
-- Get or set the selection endpoints and caret.
  function selection ( [content] )
-- Get or set the contents of the document's selection.
  function signal ( widget, signal )
-- Send a GTK signal to a Geany interface widget.
  function text ( [content] )
-- Get or set the contents of the entire document.
  function word ( [position] )
-- Get the word at the specified location.
  function xsel ( [text] )
-- Get or set the contents of the primary X selection.
  function yield ()
-- Refreshes the user interface.
 
  var caller : number
-- The index of the document that triggered an event.
  var rectsel : boolean
-- Whether or not the selection is in rectangular mode.
  var project : keyfile
-- An object representing a project configuration event.
  var script : string
-- The filename of the currently executing Lua script.
  var wordchars : string
-- The characters that are considered part of a word.



System functions:
  function basename( pathstr )
-- Extract the filename portion of a path string.
  function dirlist( path )
-- List the contents of a folder.
  function dirname( pathstr )
-- Get the directory portion of a file's path.
  function fullpath( filename )
-- Get the full path to a file.
  function launch ( program [, arg1 [, arg2, ...]] )
-- Execute an external application.
  function optimize ()
-- Run a script without the debug hook.
  function rescan ()
-- Regenerate the scripts menu.
  function stat ( filename [, lstat] )
-- Retrieve some information about a disk file.
  function timeout ( seconds )
-- Control maximum time allowed for script execution.
  function wkdir ( [folder] )
-- Get or set the current working directory.
 
  var dirsep : string
-- The default filesystem path separator, "/" or "\".



Dialog functions:
  function choose ( prompt, items ) -- Select an item from the list.
  function confirm ( title, question, default ) -- Ask a yes-or-no question.
  function input ( [prompt] [,default] ) -- Prompt to enter some text.
  function message ( [title,] message ) -- Display some information.
  function pickfile ( [mode [,path [,filter]]] ) -- Select a file from disk.
 
  var banner : string
-- The window title for all dialogs.

If you need a more advanced dialog creation API, check out the dialog module.




geany.activate ( tab_id )

Activates the document specified by tab_id.

If tab_id is a number, it activates the document at that index.   A positive number refers to the internal document array, and a negative number refers to the (absolute) GtkNotebook index.
Note that the indices begin at (1) and (-1) respectively.

If tab_id is a string, the function will try to activate the notebook tab whose filename matches that string.
( The full pathname is required! )

Returns true on success, or false if the tab could not be found.




geany.appinfo ()

Returns a Lua table containing information about the currently running Geany instance.

The appinfo table contains the following fields:
 
debug -- true if Geany is running in debug mode.
configdir   -- User's local configuration folder.
datadir -- System-wide configuration folder.
docdir -- Location of the Geany help files.
scriptdir -- Top level folder for GeanyLua scripts.
tools -- Table of user-configured tools. (see below)
template -- Table of user's template information. (see below)
project -- Table of current project information. (see below)

————

The tools sub-table contains the following fields:
 
browser
term
print
grep
action

————

The template sub-table contains the following fields:
 
developer
company
mail
initial
version

————

The project sub-table *might* contain the following fields:
 
name -- Name of project.
desc -- Project description.
file -- Project filename.
base -- Base path of project files.
mask -- Semicolon-delimited list of filetypes.

* Important: The entire project sub-table will be nil if there is no open project!



geany.basename ( pathstr )

Returns the rightmost filename portion of pathstr, with the directory portion removed.




geany.batch ( start )

This function marks the beginning or ending of a group of operations
that you want the user to be able to undo in a single step.

If the start argument is true, it marks the beginning of a group of operations.

If the start argument is false, it marks the ending of a group of operations.




geany.byte ( [position] )

When called with no arguments, returns the numeric value of the character at the current caret position.

When called with a numeric position argument, returns the value of the character at that position.




geany.caret ( [position] )

When called with no arguments, returns the current caret position.

When called with a single numeric argument, moves the caret to that position.
Out-of-range values are adjusted to the nearest possible position (i.e. the start or end of the document.)




geany.close ( [filename]|[index] )

When called with no arguments, closes the currently active document.

When called with a numeric argument, closes the file of that document index.

When called with a string argument, it will close that named document.

If the document has unsaved changes, the user will be prompted to save before closing,
and will also be given the option to cancel the operation.   To avoid this, you might
want to consider using the geany.save() function beforehand.

Returns true if the document was successfully closed, or false otherwise.




geany.copy ( [content]|[start,stop] )

When called with no arguments, copies the current selection to the clipboard.

When called with a single string argument, copies the contents of that string to the clipboard.

When called with two arguments, copies the portion of the current document's text that lies between the start and stop positions. (Both positions must be positive numbers.)

Returns the number of characters copied, or nil if there is no open document.




geany.count ()

Returns the number of open documents.




geany.cut ()

Cuts the current selection to the clipboard.

Returns the number of characters cut, or nil if there is no open document.




geany.dirlist ( path )

Returns an iterator function that will be called once for each entry (file or subdirectory) in the specified folder. The iterator produces only the name of each entry, and in no particular order.

This function will generate an error dialog if the specified folder does not exist or cannot be accessed.




geany.dirname ( pathstr )

Returns the directory portion of pathstr, with the rightmost filename portion removed.




geany.documents ( [doc_id] )

When called with a numeric argument, returns the full path and filename of
the document at the index specified by doc_id.

When called with a string argument, returns the numeric index of the document with the
path/filename that matches the doc_id string.

Either of the two forms above may also return nil if the argument cannot be matched.

Note: The index here refers to the editor's internal document array, and might not be
the same as the notebook tab index, since the tabs can be re-ordered by the user.



When called with no arguments, the function returns an iterator to list the full path and filename of each document currently open in the editor.

For example:


for filename in geany.documents()
do
  print(filename)
end



geany.filename ()

Returns the full path and filename of the current Geany document.

If there is no open document, or if the current document is untitled, returns nil.




geany.fileinfo ()

Returns a Lua table containing various information about the current document.
If there is no open document, returns nil.

The returned table contains the following fields:
name -- The filename, without the path.
path -- The full path of the file's directory, including the trailing slash.
ext -- The file extension, including the dot, e.g. ".DLL" or ".txt"
type -- A one-word description of the filetype, e.g. "C" or "Python".
desc -- A longer description of the filetype, e.g. "Lua source file" or "Cascading StyleSheet".
opener -- The string used to begin a comment, e.g. "<!--".
closer -- The string used to end a comment, e.g. "-->".
action -- The action command as executed by the context menu
ftid -- The unique numeric filetype identifier, as used by Geany.
encoding -- The file's in-memory encoding. (may differ from the on-disk encoding.)
bom -- true if the file contains a Byte-Order Marker.
changed -- true if the file has unsaved changes.
readonly -- true if the in-memory document is tagged as read-only.



geany.find ( phrase, start, stop, options )

Searches within the current document for the string phrase, beginning at
the numeric start position and ending at the stop position.
( To search backwards, specify a start value greater than stop . )

The options argument is a table, each element may be one of the following strings:
  "matchcase" -- A match only occurs with text that matches the case of the search string.
  "wholeword" -- A match only occurs if the characters before and after are not word characters.
  "wordstart" -- A match only occurs if the character before is not a word character.
  "regexp" -- The search string should be interpreted as a regular expression.
  "posix" -- Use bare parentheses ( ) for tagged sections rather than the escaped \( and \).
( The empty set {} may also be specified, to search using the default options. )

If a match is found, the function returns the starting and ending positions of the match,
otherwise it returns nil.

For example, to select the first case-sensitive whole-word match of the string  'foobar'  you could use something like this:

 a,b = geany.find( "foobar", 0, geany.length(), {"wholeword","matchcase"} )
 if (a) then
   geany.select(a,b)
 else
   geany.message("Search phrase not found.")
 end



geany.fullpath ( filename )

Returns the fully canonicalized form of the path to an existing named file, or nil if the path could not be found.




geany.height ()

Returns the total number of lines in the current document.




geany.keycmd ( command )

Activates (runs) one of Geany's built-in menu commands.

The command argument should be one the string constants defined in the "glspi_keycmd.h" header from the plugin sources.   For example, to display Geany's preferences dialog, you could use:

  geany.keycmd("MENU_PREFERENCES")

This function raises an error if the command argument is invalid.




geany.keygrab ( [prompt] )

Intercepts the next keyboard key pressed, preventing the editor from receiving that keyboard event.

The function returns the value of the pressed key as a string, alphanumeric keys will return their keyboard value, such as  "a"  or  "1"  while other keys may return a string describing the key, such as "Return" or "Escape".   ( Consult the file  gdk/gdkkeysyms.h  in the GTK sources for some idea of the key names. )

It should be possible to use this function on keyboards other than US, although this hasn't been tested, and scripts written for one keyboard might not be portable to another system.

Key combinations with the modifier keys  [Ctrl]  or  [Alt]  are not supported.   Detection of the  [Shift]  key state is somewhat supported, although currently it may not be completely reliable.   Repeatedly calling this function in rapid succession (as in a loop) may also result in some "dropped" keys, so for best results its use should be confined to detecting a single "lowercase" key press.

If the optional prompt string argument is present, its text will be shown as a "calltip" near the upper left-hand area of the current document. (but only if there is a document open.)

This function was primarily intended for assigning "chained" sets of hot key options, in conjunction with user-defined keybindings.




geany.launch ( program [, arg1 [, arg2, ...]] )

Executes the external application specified by  program,  passing any additional arguments to its command line.

Returns true if the process was succesfully created, else it returns false plus an error message.

For example:
  local ok,msg = geany.launch("firefox", "http://www.yahoo.com/")
  if not ok then geany.message(msg) end

This function returns immediately, regardless of the status of the newly-created process. If you need to wait for a process to complete before returning, use Lua's built-in  os.execute()  function instead.

Note that using this function on MS-Windows might require installing the "gspawn-win32-helper.exe" program somewhere in your PATH.   ( It is included in the GTK/GLib package. )




geany.length ()

Returns the text length of the current document.




geany.lines ( [index] )

When called with one argument, returns a string containing the text at the specified line number of the current document.
It may also return nil if there is no open document, or if the specified index is outside the range of lines.

When called without any arguments, it returns an iterator that steps through each line of the current document.
So you can use it like this:

for line in geany.lines()
do
  print(line)
end



geany.match ( [position] )

Attempts to find a corresponding matching brace from the given position of one brace.
( If the position argument is omitted, the current caret position is assumed. )

The brace characters handled are:   () [] {} <>

The search is forwards from an opening brace and backwards from a closing brace.
If the character at position is not a brace character, or a matching brace cannot be found,
the return value is -1. Otherwise, the return value is the position of the matching brace.




geany.navigate ( mode, count [,extend [,rect]] )

Moves the caret incrementally.

The  mode  argument must be one of the following strings:

If the numeric count argument is positive, the caret is moved forward or down by that many steps.
If it is negative, the caret is moved backward or up by that many steps.
( If it is zero there is not much point in using this function. )
There is also no point in using a magnitude greater than one for the "edge" or "body" modes.

If the optional boolean extend argument is true, the selection is expanded or contracted to the new caret position, similar to holding down the  [Shift]  key when navigating with the keyboard.

If the optional boolean rect argument is also true, the selection is treated as rectangular rather than linear.
( Rectangular selection is only supported for char, edge, line, or page modes. )




geany.newfile ( [filename] )

When called with one argument, creates a new document with the specified filename.

When called with no arguments, creates a new, untitled document.




geany.open ( [filename]|[index] )

When called with no arguments, reloads the currently active document from disk.

When called with a numeric argument, reloads the file of that document index.

When called with a string argument, it will reload that filename if it is already open, or otherwise it will open it in a new tab.
It will not create a non-existent file, for that you need to use geany.newfile()

Returns the one-based document index on success, or zero if the document could not be opened or reloaded.




geany.optimize ()

Disables the Lua interpreter's "debug hook", the thing that allows the plugin to track line number information and elapsed time.

The advantage of calling optimize() is that a lengthy, CPU-intensive script can sometimes run much faster.

The disadvantage is that you lose the line number information that helps in debugging your script, and the built-in protection against things like endless loops. For this reason you should only use this function if you really need it, and only when you are reasonably sure that your script doesn't contain any errors.

For best results this function should be called at the very beginning of the script.




geany.paste ()

Pastes the text from the clipboard into the active document at the current caret position,
replacing any current selection.

Returns nil if there is no open document, or if the document is marked read-only.

Otherwise it returns the effective change in the document's size.
( Which may actually be negative, if the clipboard content size is less than the prior selection. )




geany.rescan ()

Scans the scripts folder, rebuilds the Tools->Lua Scripts menu, and re-initializes the GTK accelerator group (keybindings) associated with the plugin.




geany.rowcol ( [position]|[line,column] )

This function translates between line/column coordinates and linear position (offset from beginning of document).

The syntax takes three forms:

Out-of-range arguments are adjusted to the nearest valid possibility.




geany.save ( [filename]|[index] )

When called with no arguments, saves the currently active document to disk.

When called with a numeric argument, saves the file of that document index.

When called with a string argument, it will save that named document ( That is, of course, if it is open. )

Returns true on success, or false if the document could not be saved.




geany.scintilla ( msg_id [, wparam [, lparam]] )

Power users only!

Sends a SCI_* message directly to the Scintilla widget of the active document.

The msg_id can be a numeric value, or a case-insensitive string with or without the "SCI_" prefix, such as "SCI_POSITIONFROMPOINT", "POSITIONFROMPOINT", or "PositionFromPoint".

The wparam, lparam, and return types depend on the particular message, based on the interface described in the  "Scintilla.iface"  file from the Scintilla sources.

For API calls which expect a pre-allocated char buffer as the lparam, the allocation is automatically managed by the GeanyLua module, your lparam is ignored, and the return value is a Lua string.  In cases where the length is specified in the wparam, the null terminator is not counted - if you ask for 3 chars, you get 3 chars.

Currently only string, numeric, and boolean types are supported, any API call that expects or returns complex types will result in an error.  This function tries hard to protect from garbage being passed to Scintilla, but ultimately you are expected to know what you're doing!




geany.select ( [[start,] stop]] )

When called with no arguments, returns the beginning and ending points of the current selection, in the form:
  start, stop = geany.select()
( Note that in Lua a single function call like the one above returns both values! )

To find out if the selection is rectangular, test the boolean variable geany.rectsel immediately after this call.


If this function is called with two arguments, it creates a new selection in the current document.
The selection is anchored at the start position, and extended to the stop position.

The boolean variable geany.rectsel can be set prior to this call to control whether this selection is created in normal or rectangular mode.


If called with one argument, the caret is moved to that position, but no selection is created,
and any existing selection is lost.


Note that in all cases, the value of stop is considered to be the end of the selection where the caret is located.

So, if stop is less than start, the caret is postioned at the beginning of the selection,
similar to a selection created by dragging the mouse backwards in the document.

Hint: To select the entire document, you can use:   geany.select( 0, geany.length() )




geany.selection ( [content] )

When called with no arguments, returns the selected text in the current Geany document as a string.
Returns the empty string if no text is selected, or nil if there is no open document.

When called with one argument, the selected text of the current document will be replaced with the specified content string.
If no text is currently selected, the text will be inserted at the current (caret) position.




geany.signal ( widget, signal )

Emits a GTK signal to a given widget in the Geany user interface.

The widget argument is a string identifying the widget by its Glade  "id"  attribute.
The signal argument is a string identifying the signal to be emitted.

This function was primarily intended for activating Geany's builtin menu commands.
For instance, to display the file open dialog you could do:
  geany.signal("menu_open1", "activate")

The function does not return a value, but may trigger an error message if the widget name is not found or the signal name is not valid for the specified widget.   Note that it is generally easier and more reliable to use the keycmd() function whenever possible.




geany.stat( filename [, lstat] )

Returns a table providing some (limited) information about the specified file.
If the information could not be obtained, the function returns nil plus an string describing the reason for failure.

If the file is a symbolic link, and the optional  lstat  argument is true, the information is returned about the link itself, otherwise the table provides information about the file that the link points to.

The returned table contains the following fields:
size -- The size of the file, in bytes.
time -- Modification time, in seconds from the epoch.
type -- A single-character string that denotes the type of file (see below)
read -- true if the effective user can read from the file.
write -- true if the effective user can modify the file.
exec -- true if the effective user can execute the file.


The type field contains one of the following values:
"b" -- a block-oriented device.
"c" -- a character-special device.
"d" -- a directory.
"f" -- a FIFO or named pipe.
"l" -- a symbolic link.
"r" -- a regular file.
"s" -- a socket.

Note that this function does not support symbolic links or ACL permissions on MS-Windows.




geany.text ( [content] )

When called with no arguments, returns the entire text of the currently active Geany document as a string.
( Returns nil if there is no open document.)

When called with one argument, the entire text of the current document is replaced with the specified content string.




geany.timeout ( seconds )

Attempts to control the maximum time allowed, in whole seconds, for the current script to finish execution.

By default, scripts are allowed 15 seconds to complete, but if your script needs more time, you can increase it here.

Note that the interpreter is only able to trigger this "timeout exceeded" error when it is actually processing instructions. This provides protection against things like accidentally creating an endless loop, but it might still be possible to create a script that hangs indefinitely. ( For instance if you call io.read() without access to a terminal. )

The internal timer is paused whenever one of the dialog box functions is called, to allow the user time to respond.

Setting the timeout to zero will disable it completely, that is, the script will never time out.




geany.wkdir ( [folder] )

When called with no arguments, returns the current working directory.

When called with one argument, tries to change into that folder, and returns true on sucess, or false plus an error message on failure.




geany.word ( [position] )

When called with no arguments, returns the word at the current caret position.

When called with one argument, returns the word at the specified position.

This function can return an empty string if the position is not touching a character that is considered to be part of a word. You can modify this set of characters in the geany.wordchars variable.




geany.xsel ( [text] )

When called with no arguments, returns the text-based contents of the primary X selection.

When called with one argument, assigns that text as the contents of the primary X selection.

This function is only valid for X-Window environments, on MS-Windows, it does nothing.




geany.yield ()

Temporarily returns control to the IDE, to allow user interface elements to be refreshed/repainted during lengthy script operations.

Since most scripts will probably have a run time of less than a couple of seconds, you will likely never need this function. But if you do, it should be used with caution, since it allows Geany's state to be changed during script execution. This could have unpleasant consequences, for instance if the user closes a document that the script is referencing.







      Dialog functions



geany.choose ( prompt, items )

Displays a dialog box to allow the user to choose from a list of items.

The prompt argument string will display a message above the list box to explain the request.

The items argument is a Lua table, each element of the table must be a string.

The function returns the selected item as a string:

If the Cancel button is clicked, or if the dialog is is dismissed by some other means, e.g. by pressing the [Escape] key, the function returns nil.




geany.confirm ( title, question, default )

Displays a simple yes-or-no style dialog box to ask the specified question.
The title argument is displayed as a bold-faced title for the dialog.

Returns true if the 'Yes' button is clicked, or false if the 'No' button is clicked.

If the dialog is dismissed by some other means, e.g. by pressing the [Escape] key,
the function will return the boolean value specified by the default argument.

All three arguments are required, but you can pass nil as the first argument to suppress the title.




geany.input ( [prompt] [,default] )

Displays an input dialog to prompt the user for some text.

The prompt argument string will display a message above the entry box to explain what input is requested.

The default argument string, if present, will add some pre-selected text into the entry area.

If the OK button is clicked, or if the [Return] key is pressed while the entry field is active, the function will return the contents of the entry field as a string.

If the Cancel button is clicked, or if the dialog is is dismissed by some other means, e.g. by pressing the [Escape] key, the function returns nil.




geany.message ( [title,] message )

When called with one argument, displays a simple dialog box containing the specified message string.

When called with two arguments, the title argument is displayed as a bold-faced title, and the message argument will be the message text.





geany.pickfile ( [mode [,path [,filter]]] )

Displays a dialog that allows the user to select a filename.

All three arguments are optional, but you can pass nil as a placeholder to use the default value for any of the arguments.

The mode argument specifies the type of dialog, and must be one of two strings, either "open" or "save".
( passing nil is the same as "open" )
In "save" mode the function will issue an overwrite confirmation prompt if the targeted file already exists.

The path string argument sets the initial directory for the dialog, or nil to use the current directory.
If the last (rightmost) element of the path is an existing directory, the path will be used as-is, otherwise the last element is assumed to be a filename (whether it actually exists on disk or not) and will be parsed off and used as the suggested filename for the dialog.

The filter argument controls which files are displayed, or it can be nil to display all files.
It is a string consisting of pairs of substrings, where each substring is separated by the pipe "|" symbol.
The first element in each pair of substrings is the human-readable description of the filetype,
and the second element of the pair is a set of semicolon-delimited shell wildcards to filter on.
For instance, a filter for web files might look like:
  "HTML files|*.html;*.htm|PHP files|*.php;*.php4|Style sheets|*.css"
( Those familiar with Borland Delphi might recognize this syntax from the TOpenDialog.Filter property. )


Note that this function does not actually open or save anything, it merely returns the full path and filename of the selected file, or nil if the user cancels the dialog.





Module level variables



geany.wordchars

This variable determines which characters are considered to be part of a word.

It is used by the geany.word() function and may also be reset by that function if its current value cannot be interpreted as a string.

The default value is:
    "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

If you need to modify this string, you may want to save a copy of the original so you can restore it later.




geany.rectsel

This variable controls and/or returns the "selection mode" of the current document.

It is used by the geany.select() function and is adjusted when the selection is queried, and examined when the selection is set.
It may also be reset if its current value cannot be interpreted as a boolean.

A value of true represents a rectangular selection and false represents the normal linear selection mode.




geany.banner

This variable controls the window title for dialogs displayed by the current script.

It may be reset by the dialog functions if its value cannot be interpreted as a string.




geany.caller

This variable stores the internal index of the document that triggered one of the event scripts.

For example, to print the filename of a file that has just been saved, you could put
this line in your ~/.geany/plugins/lua/events/saved.lua script file:

  print(geany.documents(geany.caller))

This variable is only relevant for the opened, created, activated, and saved event scripts, for all other scripts it is set to zero.




geany.dirsep

This variable returns the default filesystem path separator.
( A forward slash / for Unix or a backslash \ for MS-Windows. )




geany.project

This variable provides a reference to the GKeyFile object for the project that triggered a  proj-*  event script.

The information stored in the object can be manipulated using the keyfile module.
For example, to print the description of the project that has just been opened, you could put
this line in your ~/.geany/plugins/lua/events/proj-opened.lua script file:

  print(keyfile.value(geany.project, "project", "description"))

This variable is only relevant for the project-based event scripts, for all other scripts it is set to nil.




geany.script

This variable stores the full path and filename of the active script.






© 2007-2008 Jeff Pohlmeyer