Table Of Contents

Previous topic

13. Using GPS for Remote Development

Next topic

15. Environment

This Page

14. Customizing and Extending GPS

GPS provides several levels of customization, from simple preference dialogs to powerful scripting capability through the Python language. This chapters describes each of these capabilities.

14.1. The Preferences Dialog

_images/preferences-general.png

This dialog, available through the Edit ‣ Preferences... menu, allows you to modify GPS’s global preferences. Changes are applied as soon as you modify a setting. Confirm your changes by pressing the OK button or press the Cancel button to undo them.

A label displays the name of each preference and an editing area to modify its value. If you hover the mouse over the label, a tool tip is displayed giving on-line help for the preference.

The preferences dialog is composed of several areas, accessible through the tabs at the left. Each page contains a set of preferences. Some pages are nested (for example, to access the color configuration for editors, you must expand the Editor row on the left by clicking on its arrow, as seen in the screenshot above).

  • Themes

    Allows you to quickly change the current settings for GPS, including preferences, key bindings, and menus. See GPS Themes for more information on themes. It is only displayed when there are themes registered.

  • General

    • Default font

      The default font used in GPS. The background color you select for this preference sets the background color for all consoles and most views that display their data as trees. To change the background color of editors, see the Edit ‣ FontsColors ‣ Default preference.

    • Fixed view font

      The fixed (monospace) font used in views like such as outline view and the bookmark view. If possible, you should should use a font with fixed width for characters for better rendering.

    • Character set

      Name of the character set to use when reading or writting text files. GPS uses UTF-8 and Unicode internally, which handles any character in any language. However, your system generally will not support Unicode natively, so the contents of the files need to be translated from the file system encoding to Unicode.

      This preference indicates the file system encoding in use. It defaults to ISO-8859-1, which corresponds to Western European characters.

    • Display splash screen

      Whether a splash screen is displayed when starting GPS.

    • Display welcome window

      Whether GPS displays the welcome window to select the project to use.

    • Show text in tool bar

      Whether the tool bar shows both text and icons or only icons.

    • Auto save

      Whether unsaved files and projects are saved automatically before calling external tools (such as a build).

    • Save desktop on exit

      Whether the desktop (size and positions of all windows) is saved when exiting. If you are working with a project created automatically by GPS, the desktop is never saved.

    • Save editor in desktop

      Determines when source editors are saved in the desktop: Never, Always, or when a source file is associated with the current project (From_Project).

    • Default builder

      The default builder used by GPS.

      • Auto to use gnatmake for Ada-only projects and gprbuild otherwise (for multi-language and non Ada projects).
      • Gnatmake to always use gnatmake for builds, even for projects containing sources in other languages. This disables support for building non-Ada projects.
      • Gprbuild to always use gprbuild for builds, even for Ada-only projects.
    • Hyper links

      Whether to display hyper links in the editors when the Control key is pressed. See Navigating with hyperlinks.

    • Clipboard size

      Controls the size of the list where all the entries copied into the clipboard through the Edit ‣ Copy and Edit ‣ Cut menus are saved. Navigate this list using the Edit ‣ Paste and Edit ‣ Paste Previous menus, as described earlier in this manual.

    • Show status bar

      Whether the status bar at the bottom of the GPS window is displayed. The status bar contains one or more progress bars while GPS is executing long actions like a build or a search. You can use these progress bars to monitor the progress of those actions.

      You can hide this status bar to save vertical screen space. The progress bars will no longer be visible. Instead, you can display the Task Manager through the Tools ‣ Views ‣ Tasks menu to get similar information. You can put the manager on the right or left side of the GPS window, for example just below the Project view.

    • Remove policy when fixing code

      The prefered way to fix code when parts have to be removed. Always_Remove requsts GPS to remove the code. Always_Comment requests GPS to comment out the code. Propose_Both_Choices proposes a menu with both choices.

    • Tip of the Day

      Whether GPS displays a Tip of the Day at start up.

  • Windows

    This section selects preferences for the multiple document interface described in Multiple Document Interface.

    • Opaque

      Items are resized or moved opaquely when not maximized.

    • Destroy floats

      If false, closing the window associated with a floating item puts the item back in the main GPS window, but does not destroy it. If true, the window is destroyed.

    • All floating

      All windows are floating by default and are under the control of your system (on Windows) or window manager (on Unix machines). This replaces the MDI.

    • Short titles for floats

      All floating windows have a short title. In particular, base file names are used for editors instead of full names.

    • Background color

      Color to use for the background of the MDI.

    • Title bar color

      Color to use for the title bar of unselected items.

    • Selected title bar color

      Color to use for the title bar of selected items.

    • Show title bars

      If Always, each window in GPS has its own title, displaying information such as the name of the file and buttons to iconify, maximize or close the window. The title bar is highlighted when the window is currently selected.

      If Never, the title bar is not displayed to save space on the screen. Instead, the tabs of notebooks are highlighted.

      If Central Only, only the windows in the central area (i.e., the part that gets preserved when switching perspectives, which are mostly editors) have a title bar. This is often a good way to save space on the screen; the title bar is useful for editors since it gives the full name of the file as well as providing an easy handle for drag operations, but the other views do not change position often and it may be better to save space on the screen by not displaying their title bars.

    • Notebook tabs policy

      When notebook tabs are displayed. If Never, you must select the window in the Window menu or through the keyboard. If Automatic, tabs are shown when two or more windows are contained in the notebook.

    • Notebook tabs position

      Where the notebook tabs are displayed by default. Select the position of tabs for each notebook individually by right-clicking in any of their tabs and chosing a new position in the contextual menu. This position is saved as part of the desktop and restored the next time you restart GPS. However, if you change the value of this preference, the position of tabs in all notebooks resets to match the new value of the preference.

  • Editor

    • General

      • Strip blanks

        Whether editors remove trailing blanks when saving a file.

      • Line terminator

        The style of line terminators used when saving files. Unchanged uses the original line terminator, Unix uses LF line terminators, and Windows uses CRLF line terminators.

      • Display line numbers

        Whether editors display line numbers.

      • Auto indent on paste

        Whether content pasted in the source editors should be auto indented.

      • Display subprogram names

        Whether the editor’s status bar displays the subprogram name.

      • Tooltips

        Whether tool tips are displayed automatically.

      • Tooltips timeout

        Time (in milliseconds) before displaying tooltips.

      • Highlight delimiters

        Whether the delimiter matching the character following the cursor is highlighted. The list of delimiters includes: {}[]().

      • Autosave delay

        The period (in seconds) after which an editor is automatically saved, 0 if never automatically saves.

        Each modified file is saved under a file called .#filename#, which is removed on the next explicit save operation.

      • Right margin

        The right margin to highlight, 0 if none. This value is also used to implement the Edit ‣ Refill menu.

      • Block highlighting

        Whether the editor highlights the current block. The current block depends on the programming language, and includes procedures, loops, if statements, and other similar structure.

      • Block folding

        Whether the editor provides the ability to fold and unfold blocks.

      • Speed Column Policy

        When the Speed Column is shown on the side of the editors:

        • Never

        • Always

        • Automatic

          Shown whenever lines are highlighted in the editor, for example to show the current execution point or lines containing compilation errors. It disappears when no lines are highlighted.

      • Use Windows ACL

        A Windows-specific preference, disabled by default. When enabled, GPS uses the ACL to change the file’s write permission. Note that ACL’s cannot be used on network drives.

      • External editor

        The default external editor to use.

      • Custom editor command

        The command line used to launch a custom editor. GPS assumes the command creates a new window or terminal as needed. If the editor itself does not provide this capability (such as vi or pico on Unix systems), you can use an external terminal command such as:

        xterm -geo 80x50 -exe vi +%l %f
        

        GPS performs the following substitutions:

        • %l line to display
        • %c column to display
        • %f full pathname of file to edit
        • %e extended lisp inline command
        • %p top level project file name
        • %% a literal percent sign (‘%’)
      • Always use external editor

        True if all editing is done with the external editor, which completely deactivates the internal editor. False if the external editor is only explicitly called by the user.

      • Smart completion

        When enabled, GPS loads all the information needed for the Smart completion to work on startup.

      • Smart completion timeout

        The timeout, milliseconds, after which the Smart Completion window appears automatically after entering a triggering character, such as ”.”.

    • Fonts & Colors

      • Default

        The default font, default foreground and default background colors used in the source editor.

      • Blocks

        Font variant and colors used to highlight blocks (such as subprograms, task, and entries) in declarations.

      • Types

        Font variant and colors used to highlight types in declarations.

      • Keywords

        Font variant and colors used to highlight keywords.

      • Comments

        Font variant and colors used to highlight comments. Setting the color to white sets the color as transparent.

      • SPARK Annotations

        Font variant and colors used to highlight SPARK annotations within Ada comments (Starting with –#). Setting the color to white sets the color as transparent.

      • Ada/SPARK Aspects

        Font variant and colors used to highlight Ada 2012 and SPARK 2014 aspects. Setting the color to white sets the color as transparent.

      • Strings

        Font variant and colors used to highlight strings. Setting the color to white sets the color as transparent.

      • Numbers

        Font variant and colors used to highlight numbers. Setting the color to white sets the color as transparent.

      • Current line color

        Color for highlighting the current line. Leave it blank for no highlighting. Setting the color to white sets the color as transparent.

      • Draw current line as a thin line

        Whether to use a thin line rather than full background highlighting on the current line.

      • Current block color

        Color for highlighting the current source block.

      • Delimiter highlighting color

        Color for highlighting delimiters.

      • Search results highlighting

        Color for highlighting the search results within the text of editors.

    • Ada

      • Auto indentation

        How the editor should indent Ada sources. None means no indentation; Simple means use indentation from the previous line; Extended means use a language specific parser.

      • Use tabulations

        Use tab characters when indenting. This preference does not modify the Tab key, which still inserts tab characters. You can also map the Edit ‣ Insert Tab With Spaces key shortcut to, e.g., Tab via The Key Manager Dialog. You can also reconfigure the default key binding for the automatic indentation action: by default, it is mapped to Tab, but you can change it to Tab by modifying the Edit ‣ Format Selection action from The Key Manager Dialog.

      • Default indentation

        Number of spaces for the default Ada indentation.

      • Continuation lines

        Number of extra spaces for continuation lines.

      • Declaration lines

        Number of extra spaces for multiple line declarations. For example, if you specify a value of 4, here is how the following code would be indented:

        variable1,
            variable2,
            variable3 : Integer;
        
      • Conditional continuation lines

        Number of extra spaces used to indent multiple-line conditionals within parentheses.

        For example, when set to 1 (the default), continuation lines are indented from the previous parenthesis by one space:

        if (Condition1
            and then Condition2)
        then
        

        When this preference is set to 3, you get:

        if (Condition1
              and then Condition2)
        then
        
      • Record indentation

        Number of extra spaces for record definitions, when the record keyword is on its own line.

        For example, when set to 3 (the default), the following sample will be indented as:

        type T is
           record
              F : Integer;
           end record;
        

        When set to 1, you get:

        type T is
         record
            F : Integer;
         end record;
        
      • Case indentation

        Whether GPS should indent case statements an extra level, as done in the Ada Reference Manual, e.g:

        case Value is
           when others =>
              null;
        end case;
        

        If set to Non_Rm_Style, this is indented as:

        case Value is
        when others =>
           null;
        end case;
        

        By default (Automatic), GPS decides whether to indent an extra level based on the first when construct: if that construct is indented an extra level, the whole case statement is indented following the RM style.

      • Casing policy

        The way the editor handles auto-casing:

        • Disabled

          No auto-casing is done.

        • End_Of_Line

          Auto-casing done when pressing the Enter key.

        • End_Of_Word

          Auto-casing is done word-by-word while typing.

        • On_The_Fly

          Auto-casing is done character-by-character while typing.

        For the End_Of_Line, End_Of_Word, and On_The_Fly policies you can force auto-casing of the current line by pressing the indentation key (by default, Tab).

        You can also disable auto-casing for a single character (action No Casing/indentation on Next Key, by default Ctrl-Q) or temporarily (action Toggle Auto Casing/indentation, by default Alt-Q).

      • Reserved word casing

        How the editor handles the casing of reserved words.

        • Unchanged

          Keeps casing as-is.

        • Upper

          Changes the casing of all reserved words to upper case.

        • Lower

          Changes to lower case.

        • Mixed

          Changes to mixed case (all characters to lower case except first character and characters after an underscore which are made upper case).

        • Smart_Mixed

          Like Mixed, but do not force upper case characters to lower case.

      • Identifier casing

        How the editor handles the casing of identifiers. The values are the same as for the Reserved word casing preference.

      • Format operators/delimiters

        Whether the editor adds extra spaces around operators and delimiters, if needed. If enabled, an extra space is added in the following cases: before an opening parenthesis; after a closing parenthesis, comma, semicolon and around all Ada operators (e.g. <=, :=, =>).

      • Align colons in declarations

        Whether the editor automatically aligns colons in declarations and parameter lists. The alignment is computed by looking at the editor up to the current line (or end of the current selection), so if declarations continue beyond that point, you must select the declarations lines and hit the reformat key.

      • Align associations on arrows

        Whether the editor automatically aligns arrows in associations (e.g. aggregates or function calls). See also the previous preference.

    • Align declarations after colon

      Whether the editor aligns continuation lines in variable declarations based on the colon character.

      Consider the following code:

      Variable : constant String :=
        "a string";
      

      If enabled, the code is indented as follows:

      Variable : constant String :=
                   "a string";
      
    • Indent comments

      Whether to indent lines containing only comments and blanks or to keep these lines unchanged.

    • Align comments on keywords

      Whether to align comment lines following record and is keywords with no extra space.

      When enabled, the following code is indented as:

      package P is
      --  Comment
      
         [...]
      end P;
      

      When disabled, it is indented as:

      package P is
         --  Comment
      
         [...]
      end P;
      
    • C & C++

      • Auto indentation

        How the editor should indent C/C++ sources. None is no indentation, Simple uses indentation from the previous line for the next line, and Extended uses a language specific parser to indent sources.

      • Use tabulations

        Use tab characters when indenting. If True, the editor replaces each occurrence of eight characters by a tab character.

      • Default indentation

        Number of spaces for the default indentation.

      • Extra indentation

        Whether to indent loops, if and switch statements an extra level. If enabled, the following layout is generated:

        if (condition)
          {
            int x;
          }
        

        If disabled, the same code is indented as:

        if (condition)
        {
          int x;
        }
        
      • Indent comments

        Whether to indent lines containing only comments and blanks or keep these lines unchanged.

  • Debugger

    • Preserve State on Exit

      If enabled, the debugger automatically saves breakpoints when it exits and restores them the next time the it debugs the same executable. This is a convenient way to work when the typical usage alternates between compile and debug operations.

      When enabled, the debugger also preserves the contents of the data window whenever it is closed. Reopening the window, either during the same debugger session or automatically when you start a new debugger on the same executable, recreates the same boxes within the data window.

    • Debugger Windows

      Controls what happens to debugger-related windows, such the call stack, data window, and tasks view when the debugger terminates. There are three possibilities.

      • Close Windows

        All those windows are closed. This saves memory and space on your screen, but you must explicitly reopen them and put them in the desired location on the desktop the next time you start a debugger session.

    • Keep Windows

      The windows are cleared but kept on the desktop. When you start a new debugger session, the windows are automatically reused. This ensures you will not have to reopen and reposition them but takes up space on your screen.

    • Hide Windows

      The windows are cleared and hidden. When you start a new debugger session, they are automatically reused and made visible again. This option also ensures you will not have to reopen and reposition them but requires some memory. Note that if you move other windows around while these are hidden, they might reappear in unexpected locations.

    • Break on exceptions

      Specifies whether a breakpoint on all exceptions should be set by default when loading a program. This setup is only taken into account when a new debugger is initialized, and will not modify a running debugger (use the breakpoint editor for running debuggers).

    • Execution window

      Whether the debugger should create a separate execution window for the program being debugged. This preference does not apply to the current debug session; to change the current debug session, you need to terminate it and start a new one.

      If enabled, a separate console is created. On Unix systems, this console is another window in the bottom part of the main window and on Windows, it is a separate window created by the underlying gdb, since Windows does not have the notion of separate terminals (ttys).

      If using this mode under Windows, the Debug ‣ Interrupt menu is only able to interrupt the debugged program with recent versions of gdb. If you are using older versions, you need to hit Ctrl-C in the separate execution window to interrupt it. This separate execution window uses the default system-wide console properties (such as the size of the window and its color). You can change those properties using the default console menu (top-left of the console).

      If this preference is disabled, GPS does not created an execution window. The debugger assumes the program being debugged either does not require input or that input is handled outside GPS. For example, when you attach to a running process, this process already has an associated terminal.

    • Show lines with code

      Whether the source editor displays blue dots for lines containing code. If disabled, gray dots are instead displayed on each line, permitting breakpoint on any line, which is faster since GPS does not need to ask the debugger which lines contain code.

    • Detect aliases

      If enabled, do not create new items when an item with the same address is already present on the canvas.

    • Assembly range size

      Number of assember lines to display in the initial display of the assembler window. If 0, the whole subprogram is displayed, which can take a long time on slow machines.

    • Current assembly line

      Color used to highlight the assembly code for the current line.

    • Color highlighting

      Color used for highlighting in the debugger console.

    • Clickable item

      Color used for clickable items (e.g pointers).

    • Changed data

      Color used to highlight fields in the data window that have changed since the last update.

    • Memory color

      Default color for the memory view window.

    • Memory highlighting

      Color used for highlighted items in the memory view.

    • Memory selection

      Color used for selected items in the memory view.

    • Item name

      Font used for the name of each item in the data window.

    • Item type

      Font used to display the type of each item in the data window.

    • Max item width

      Maximum width of an item.

    • Max item height

      Maximum height of an item.

  • External Commands

    These preferences specify the names of the commands that GPS uses to perform various operations.

    • List processes

      List processes running on the machine.

    • Remote shell

      Run a process on a remote machine. You can specify arguments, for example, rsh -l user.

    • Remote copy

      Copy a file from a remote machine. You can specify arguments, for example rcp -l user.

    • Execute command

      Execute commands externally.

    • HTML Browser

      View HTML files, for example the documentation. Not relevant under Windows, where the default HTML browser is used. Not specified by default, which means GPS tries to find a suitable HTML browser. Only change this value if GPS cannot find a HTML browser, or if the browser found is not the one you prefer.

  • Search

    • Confirmation for “Replace all”

      Enable or disable the confirmation popup for the replace all action.

    • Close on Match

      If enabled, GPS closes the search window when a match is found.

    • Select on Match

      If enabled, the focus is be given to the editor when a match is found.

    • Preserve Search Context

      If enabled, the contents of the Look in: field is preserved between consecutive file searches.

  • Browsers

    • General

      • Selected item color

        Color of selected items.

      • Background color

        Color of browser background.

      • Hyper link color

        Color of hyperlinks between items.

      • Selected link color

        Color of links between selected items.

      • Default link color

        Color of links between non-selected items.

      • Ancestor items color

        Color of background of items linked to selected items.

      • Offspring items color

        Color of background of items linked from selected items.

      • Vertical layout

        Whether the layout of the graph should be vertical or horizontal. This setting applies to most browsers (such as the call graph), but does not apply to the entity browsers.

      • Show elaboration cycles

        Display a elaboration graph after each compilation showing an elaboration cycle.

  • VCS

    • Implicit status

      Whether GPS is allowed to launch a status action (such as getting revision numbers) as part of another action (such as an update command). If the network connection with the repository is slow, disabling this preference can speed up the VCS actions.

    • Default VCS

      The default VCS.

  • Visual diff

    In order to perform visual comparison between files, GPS needs to call external tools that are not distributed with GPS such as diff or patch. These tools are usually found on most Unix systems but may not be available by default on other OSes. Under Windows, you can download them from one of the available Unix toolsets, such as msys (http://www.mingw.org) and cygwin (http://www.cygwin.com).

    • mode

      How GPS visually displays the difference between two files:

      • Side_By_Side

        Editors are displayed side-by-side; new editors are created as needed.

      • Unified

        No new editor is created; changes are displayed directly in the existing editor.

    • Diff command

      Command used to compute differences between two files. You can also specify arguments. The visual diff support expects a standard diff output with no context (that is, no -c or -u switches). You may wish to include some of the following switches depending on the version of diff you specify:

      • -b

        Ignore changes in the amount of white space.

      • -B

        Ignore changes that only insert or delete blank lines.

      • -i

        Ignore changes in case; consider upper and lower case letters equivalent.

      • -w

        Ignore all white space when comparing lines.

    • Patch command

      Command used to apply a patch. You can also specify arguments. GPS used this command internally to perform the visual comparison on files in a VCS. This command should be compatible with the GNU patch command.

    • Use old diff

      Use the old version of the visual comparison. The remianing preferences are not displayed if this preference is enabled.

    • Diff3 command

      Command used to query a 3-way diff. See Diff command for a description of the parameters.

    • Default color

      Color in the reference editor indicating lines on which there is a difference.

    • Old color

      Color for space used by lines not present in one of the editors in a 3-way diff.

    • Append color

      Color indicating lines present in an editor but not in the reference editor.

    • Remove color

      Color indicating lines present in the reference editor but not in other editors.

    • Change color

      Color indicating lines changed between the reference editor and other editors.

    • Fine change color

      Color indicating detailed differences within a modified line.

    • Context length

      Number of lines displayed before and after each chunk of differences. Specifying -1 displays the whole file.

  • Messages

    • Color highlighting

      Color of highlighted text in the Messages view.

    • Errors highlighting

      Color used in a source editor for lines that cause compilation errors. If white, the errors are not highlighted. (See Compilation/Build)

    • Warnings highlighting

      Color used in a source editor for lines that cause compilation warnings. If white, the warnings are not highlighted. (See Compilation/Build)

    • Style errors highlighting

      Color used in a source editor for lines that cause style errors. If white, the style errors are not highlighted. (See Compilation/Build)

    • Compiler info highlighting

      Color used in a source editor to highlight lines containing compiler information. If white, the information is not highlighted.

    • File pattern

      Pattern used to parse file locations and message type from lines outputed to the Messages view. This is particularly useful when using an external tool such as a compiler or a search tool so GPS highlights and allows navigation through source locations. The pattern is a standard System V regular expression containing from two to five parenthesized subexpressions corresponding to the file, line, column, warnings or style error patterns.

    • File index

      Index of the filename in the expressions in the File pattern.

    • Line index

      Index of the line number in the expressions in the File pattern.

    • Column index

      Index of the column number in the expressions in the File pattern.

    • Warning index

      Index of the warning identifier in the expressions in the File pattern.

    • Style index

      Index of the style error identifier in the expressions in the File pattern.

    • Info index

      Index of the compiler info identifier in the expressions in the File pattern.

    • Secondary File pattern

      Pattern used to parse additional file locations from lines in the Messages view. This is a standard System V regular expression containing two or three parenthesized subexpressions corresponding to the file, line, and column patterns.

    • Secondary File index

      Index of the filename in the expressions in the Secondary File pattern.

    • Secondary Line index

      Index of the line number in the expressions in the Secondary File pattern.

    • Secondary Column index

      Index of the column number in the expressions in the Secondary File pattern. Index of the column number in the file pattern.

    • Alternate Secondary File pattern

      Pattern used to parse additional file locations in alternate form from lines in the Messages view. This is a standard System V regular expression containing one parenthesized subexpression.

    • Alternate Secondary Line index

      Index of the line number in the expressions in the Alternate Secondary File pattern.

  • Project

    • Relative project paths

      Whether paths should be absolute or relative when GPS modifies a project file.

    • Fast Project Loading

      If the project contains a number of restrictions, this preference significantly speeds up loading time when GPS parses the project. This is especially noticeable if the source files are on a network drive.

      GPS assumes the following restrictions are true when this preference is enabled. If any are false, no error is reported and there be only minor effects in GPS. For example, it will not be able to detect that two files are the same if one of them is a symbolic link, although GPS still warns if you are trying to overwrite a file modified on the disk.

      The restrictions are the following:

      • Symbolic links should not be used in the project.

        More precisely, you can only have symbolic links that point to files outside of the project, but not to another file in the project

      • Directories cannot have source names.

        No directory name should match the naming scheme defined in the project. For example, if you are using the default GNAT naming scheme, you cannot have directories with names ending in .ads or .adb.

    • Hidden directories pattern

      A regular expression used to match hidden directories which are not displayed by default in the project view, nor taken into account by VCS operations on directories.

  • Documentation

    This section specifies preferences that apply to the documentation generator. See Documentation Generation for more information.

    • Process body files

      Body (implementation) files are processed. Otherwise, only the specification files are processed.

    • Show private entities

      By default, no documentation is generated for private entities. Enabling this preference produces that documentation.

    • Call graph

      The documentation computes and take advantages of source references to generate call graph information. Activating this option slows down the documentation generation process.

    • Up-to-date files only

      Only files having up-to-date cross references information are documented.

    • Comments filter regexp

      A regular expression used to filter to comments found in the source code before using them for documentation. For example “^!.*” ignores all comments starting with ‘!’.

    • Spawn a browser

      A browser is spawned after documentation is generated to view the generated files.

    • Find xrefs in comments

      Tries to find references to entities in comments and generate links to them when generating the documentation.

  • Coverage Analysis

    • Coverage toolchain

      Select which coverage toolchain (gcov or xcov) to use from the Tools ‣ Coverage menu.

14.2. GPS Themes

GPS include extensive support for themes, which are predefined sets of values for preferences, key bindings, and other configurable aspects of GPS.

For example, color themes are a convenient way to change all colors in GPS simultaneously to predefined choices such as strongly contrasted colors or monochrome. You can also have key themes defining a set of key bindings that, for example, emulate other editors.

You can activate any number of themes simultaneously via the preferences dialog (Edit ‣ Preferences), which contains a list of all themes supported by GPS, organized into categories. Click on the buttons on the left of each theme name to activate that theme. This immediately changes the current preferences settings. For example, if the theme you selected changes the colors in the editor, these are changed immediately in the Editor ‣ Fonts & Colors menu. Press Cancel to return to your previous settings

If multiple themes are active and you try to set the same preference, the last theme loaded by GPS overrides all previously loaded themes. However, there is no predefined order in which the themes are loaded, so you should not depend on this behavior.

14.3. The Key Manager Dialog

Access the key manager dialog through the Edit ‣ Key Shortcuts menu. This dialog provides an easy way to associate key shortcuts with actions. Actions are either predefined in GPS or defined in your own customization files, as documented in Customizing through XML and Python files. It also provides an easy way to redefine menu shortcuts.

_images/key-shortcuts.jpg

Actions are referenced by their name and grouped into categories indicating when the action applies. For example, the indentation command applies only in source editors while the command to change the current window applies anywhere in GPS. Specify the category when you create your own actions through XML files (see Defining Actions).

As an example, you can use the key manager to define key bindings similar to what Emacs uses (such as Ctrl-x followed by Ctrl-k). To register such key bindings, press the Grab button and type the shortcut. Recording of the key binding stops shortly after you press the last key.

If you define complex shortcuts for menus, they will not appear next to the menu name when you select it with the mouse due to technical limitations in the graphical toolkit that GPS uses.

Assigning a new shortcut to an action causes the following:

  • All actions and menus currently associated with key are no longer executed when the key is pressed.
  • All key shortcuts defined for this action are replaced by the new one; the action is only executable through this new shortcut.

14.4. The Plug-ins Editor

You can extensively customize GPS through external plug-ins, either ones you write (see Customization files and plugins) or using one of the plug-ins in GPS’s own collection.

Some plug-ins are loaded by default when GPS starts (such as support for the CVS version management system and support for highlighting in various programming languages) and others are available but not loaded automatically, such as Emacs emulation mode.

Some plug-ins provided with GPS are:

  • Emacs emulation

    Several plug-ins emulate many functions provided by Emacs, such as the interactive search, manipulation of rectangles, navigation, and the usual Emacs key shortcuts. Activate it by loading the emacs.xml plug-in.

  • Makefile support

    A plug-in that parses a Makefile and creates menus for each of its targets so you can easily start a make command.

  • Cross-references enhancements

    Some plug-ins take advantage of GPS’s cross-references information to create additional menus for navigation such as jumping to the primitive operations of Ada tagged types and to the body of Ada separate entities.

  • Text manipulation

    Several plug-ins provide support for advanced text manipulation in the editors, for example to align a set of lines based on various criteria or to manipulate a rectangular selection of text.

To graphically choose which plug-ins are loaded on startup, select the Tools ‣ Plug-ins menu. This brings up a new window, containing two parts:

  • A list of all known plug-ins on the left.

    This list indicates the name of the plug-in, and whether it is loaded in this GPS session (when the toggle button is checked).

    As described in Customization files and plugins, GPS searches for plug-ins in various directories and, based on these directories, decides whether to automatically load the plug-in on startup.

  • Details for the selected plug-in on the right.

    This window is a notebook with two pages: the first contains the exact location of the plug-in, the reason it was either loaded or not loaded, and the source of the plug-in. By convention, each plug-in starts with a comment indicating the purpose of this plug-in and more detailed documentation on its usage. This also contains the plug-in itself, so it can act as an example you can use to create your own customization script. The list of plug-ins to load are stored in the file HOME/.gps/startup.xml.

    If you have modified anything through this dialog (such as the list of plug-ins to load or unload), you need to restart GPS, since it cannot unload a module due to such an action having too many possible effects on GPS, so a dialog is displayed asking you whether you would like to exit GPS. Doing so saves your files.

14.5. Customizing through XML and Python files

14.5.1. Customization files and plugins

You can customize many capabilities in GPS using files it loads at startup. For example, you can add items to the menu and tool bars as well as defining new key bindings, languages, and tools. Using Python as a programming language, you can also add new facilities and integrate your own tools into the GPS platform.

GPS searches for these customization files at startup in several different directories. Depending on where they are found, they are either automatically loaded by GPS (and thus can immediately modify things in GPS) or may only be made visible in the Plug-ins editor (see The Plug-ins Editor).

GPS searches these directories in the order given below. Any script loaded later can override operations performed by previously loaded scripts. For example, they can override a key shortcut, remove a menu, or redefine a GPS action.

In each directory name below, INSTALL is the name of the directory in which you have installed GPS. HOME is your home directory, either by default or as overriden by the GPS_HOME environment variable. In each directory, only files with .xml or .py extensions are used. Other files are ignored, although for compatibility with future versions of GPS you should not have keep other files in these directories.

  • Automatically-loaded, global modules

    The INSTALL/share/gps/plug-ins directory contains the files GPS automatically loads by default (unless overriden by the user via the Plug-ins Editor). These plug-ins are visible to any user on the system using the same GPS installation. Reserve this directory for critical plug-ins that almost everyone will use.

  • Not automatically-loaded, global modules

    The INSTALL/share/gps/library directory contain files GPS displays in the Plug-ins editor but does not load automatically. Typically, these files add optional capabilities to GPS, for example an emacs emulation mode or additional editor capabilities that many of users generally will not use.

  • GPS_CUSTOM_PATH

    Set this environment variable before launching GPS to be a list of directories, separated by semicolons (‘;’) on Windows systems and colons (‘:’) on Unix systems. All files in these directories with the appropriate extensions are automatically loaded by default by GPS, unless overriden by the user through the Plug-ins editor.

    This is a convenient way to have project-specific customization files. You can, for example, create scripts or icons that set the appropriate value for the variable and then start GPS. Depending on your project, this allows you to load specific aliases which do not make sense for other projects.

  • Automatically loaded user directory

    The directory HOME/.gps/plug-ins is searched last. Any script in it is loaded automatically unless overriden in the Plug-ins editor.

    This is a convenient way for you to create your own plug-ins or test them before you make them available to all GPS users by copying them to one of the other directories.

Any script loaded by GPS can contain customization for various aspects of GPS, such as aliases, new languages or menus, in a single file.

14.5.1.1. Python files

You can format the Python plug-in in any way you want (as long as it can be executed by Python, of course), the following formatting is suggested. These plug-ins are visible in the Plug-ins editor, so having a common format makes it easier for users to understand each plug-in:

  • Comment

    Your script should start with a comment on its goal and usage. This comment should use Python’s triple-quote convention, rather than the start-of-line hash (‘#’) signs. The first line of the comment should be a one line explanation of the goal of the script, separated by a blank line from the rest of the comment.

  • Customization variables

    If a user can configure your script by changing some global variables, they should be listed next and fully documented. The user can use the Tools ‣ Plug-ins menu to change the value of those variables.

  • Implementation

    Separate the implementation from the initial comment by a form-feed (control-L); the startup scripts editor only displays the first page of the script in the first page of the editor.

    If possible, scripts should avoid executing code when they are loaded. This gives the user a chance to change the value of global variables or override functions before the script is actually launched. Instead, you should to connect to the “gps_started” hook, as in:

    ^L
    ###########################################################
    ## No user customization below this line
    ###########################################################
    
    import GPS
    
    def on_gps_started (hook_name):
       ... launch the script
    
    GPS.Hook ("gps_started").add (on_gps_started)
    

14.5.1.2. XML files

XML files must be UTF8-encoded by default. In addition, you can specify any specific encoding through the standard command:<?xml encoding=”...” ?> declaration, as in the following example:

<?xml version="1.0" encoding="iso-8859-1"?>
<!--  general description -->
<submenu>
  <title>encoded text</title>
</submenu>

These files must be valid XML files, i.e. must start with the <?xml?> tag and contain a single root XML node, the name of which is arbitrary. The format is therefore:

<?xml version="1.0" ?>
<root_node>
   ...
</root_node>

The first line after the <?xml?> tag should contain a comment describing the purpose and usage of the script. This comment is made visible in the Plug-ins editor. The list of valid XML nodes that you can specify under <root> is described in later sections. It includes:

14.5.2. Defining Actions

This mechanism links actions to their associated menus or key bindings. Actions can take several forms: external commands, shell commands and predefined commands, each explained in more detail below.

Define new actions using the <action> tag. This tag accepts the following attributes:

  • name (required)

    The name by which the action is referenced elsewhere in the customization files, for example when it is associated with a menu or toolbar button. It can contain any character, although you should avoid XML special characters and it cannot start with a ‘/’.

  • output (optional)

    Where the output of the commands are sent by default. You can override this for each command using the same attribute for <shell> and <external> tags. See Redirecting the command output.

  • show-command (optional, default true)

    Whether the text of the command itself should be displayed in the same place as its output. Neither are displayed if the output is hidden. The default shows the command along with its output. You can override this attribute for each command.

  • show-task-manager (optional, default false)

    Whether an entry is in the task manager to show this command. The progress bar indicaton is associated with this entry so if you hide the entry, no progress bar is shown. Alternatively, several progress bars may displayed for your action if this is enabled, which might be an issue depending on the context. You can override this attribute for each external command.

  • category (optional, default General)

    The category in the keybindings editor (Edit ‣ Key bindings menu) in which the action is displayed. If you specify an empty string, the action is considered part of the implementation and not displayed in the editor and the user will not be able to assign it a keybinding through the graphical user interface (although this can still be done via XML commands).

If you define the same action multiple times, the last definition is used. However, items such as menus and buttons that reference the action keep their existing semantics: the new definition is only used for items created after it is defined.

The <action> tag can have one or several children, all of which specify a command to execute. All commands are executed sequentially unless one fails, in which case the following commands are ignored.

The valid children of <action> are the following XML tags:

  • <external>

    Defines a system command (i.e. a standard Unix or Windows command).

    • server (optional)

      Execute the external command on a remote server. The values are gps_server (default), build_server, execution_server, debug_server, and tools_server. See Remote operations for information on what each of these servers are.

    • check-password (optional)

      Tell GPS to check for and handle password prompts from the external command. The values are false (default) and true.

    • show-command (optional)

    • output (optional)

      Override the value of the attribute of the same name specified in the <action> tag.

    • progress-regexp (optional)

    • progress-current (optional, default 1)

    • progress-final (optional, default 2)

      progress-regexp is a regular expression that GPS matches the output of the command against. When the regular expression matches, it must provide two subexpressions whose numeric values represent the current and total number of steps to perform, which are used to display the progress indicators at the bottom-right corner of the GPS window. progress-current is the ordinal of the subexpression containing the current step, and progress-final is the ordinal of the subexpression containing the total number of steps, which grows as needed. For example, gnatmake outputs the number of the file it is currently compiling and the total number of files to be compiled. However, that last number may increase, since compiling a new file may cause additional files to be compiled.

      The name of the action is printed in the progress bar while the action is executing. Here is an example:

      <?xml version="1.0" ?>
      <progress_action>
        <action name="progress" >
          <external
            progress-regexp="(\\d+) out of (\\d+).*$"
            progress-current="1"
            progress-final="2"
            progress-hide="true">gnatmake foo.adb
          </external>
        </action>
      </progress_action>
      
    • progress-hide (optional, default true)

      If true, all lines matching progress-regexp and are used to compute the progress are not displayed in the output console. Otherwise, those lines are displayed with the rest of the output.

    • show-task-manager (optional, default inherited from <action>)

      Whether an entry is created in the task manager to show this command. The progress bar indicator is associated with this entry, so if you hide the entry, no progress is shown. Alternatively, several progress bars may be displayed for your action if this is enabled, which might be an issue depending on the context.

      If set a value for progress-regexp, this attribute is automatically set to true so the progress bar is displayed in the task manager.

    Note for Windows users: like Unix, scripts can be called from a custom menu. To allow that, you need to write your script in a .bat or .cmd file and call this file. So the external tag would look like:

    <?xml version="1.0" ?>
    <external_example>
      <action name="my_command">
        <external>c:\\.gps\\my_scripts\\my_cmd.cmd</external>
      </action>
    </external_example>
    
  • on-failure

    Specifies a command or group of commands to be executed if the previous external command fails. Typically, this is used to parse the output of the command and fill the Locations view appropriately (see Processing the tool output).

    For example, the following action spawns an external tool and parses its output to the Locations view. It calls the automatic fixing tool if the external tool fails.

    You can use the %... and $... macros in this group of commands (see Macro arguments):

    <?xml version="1.0" ?>
    <action_launch_to_location>
      <action name="launch tool to location" >
        <external>tool-path</external>
        <on-failure>
          <shell>Locations.parse "%1" category<shell>
          <external>echo the error message is "%2"</external>
        </on-failure>
        <external>echo the tool succeeded with message %1</external>
      </action>
    </action_launch_to_location>
    
  • shell

    You can use custom menu items to invoke GPS commands using the shell tag. These are written in one of the shell scripts supported by GPS.

    This tag supports the same show-command and output attributes as the <action> tag.

    The following example shows how to create two actions to invoke the help interactive command and open the file main.c:

    <?xml version="1.0" ?>
    <help>
      <action name="help">
        <shell>help</shell>
      </action>
      <action name="edit">
        <shell>edit main.c</shell>
      </action>
    </help>
    

    By default, commands are written in the GPS shell language. However, you can specify the language through the lang attribute, whose default value is “shell”. You can also specify “python”.

    When programming with the GPS shell, execute multiple commands by separating them with semicolons. Therefore, the following example adds a menu that lists all the files used by the current file in a Project browser:

    <?xml version="1.0" ?>
    <current_file_uses>
      <action name="current file uses">
        <shell lang="shell">File %f</shell>
        <shell lang="shell">File.uses %1</shell>
      </action>
    </current_file_uses>
    
  • <description>

    A description of the command, which is used in the graphical editor for the key manager. See The Key Manager Dialog.

  • <filter>, <filter_and>, <filter_or>

    The context in which the action can be executed. See Filtering actions.

You can mix both shell commands and external commands. For example, the following command opens an :program`xterm` (on Unix systems only) in the current directory, which depends on the context:

<?xml version="1.0" ?>
<xterm_directory>
  <action name="xterm in current directory">
    <shell lang="shell">cd %d</shell>
    <external>xterm</external>
  </action>
</xterm_directory>

As you can see in some of the examples above, some special strings are expanded by GPS just prior to executing the command, for example “%f” and “%d”. See below for a full list.

More information on chaining commands is provided in Chaining commands.

Some actions are also predefined in GPS itself. This includes, for example, aliases expansion and manipulating MDI windows. You can display all known actions (both predefined and the ones you defined in your own customization files) by opening the key shortcut editor using the Edit ‣ Key shortcuts menu.

14.5.3. Macro arguments

You use macro arguments to pass parameters to shell or external commands in any actions you define. Macro arguments are special parameters that are transformed every time the command is executed. The macro arguments below are provided by GPS. The equivalent Python code is given for some arguments. This code is useful when you are writing a full python script.

  • %a

    If the user clicked inside the Locations view, name of the current line’s category.

  • %builder

    Replaced by the default builder configured in GPS. This can be gnatmake if your project contains only Ada code, or gprbuild for non-Ada or multi-language projects. This macro is only available in commands defined in the Build Manager and Build Launcher dialogs.

  • %c

    The column number on which the user clicked. Python equivalent:

    GPS.current_context().column()
    
  • %d

    Current directory. Python equivalent:

    GPS.current_context().directory()
    
  • %dk

    Krunched name of the current directory.

  • %e

    Name of the entity the user clicked on. Python equivalent:

    GPS.current_context().entity().name()
    
  • %ef

    Name of the entity the user clicked on, possibly followed by “(best guess)” if there is an ambiguity, which may, for example, be due to cross-reference information not being up-to-date.

  • %E

    Full path to the executable name corresponding to the target.

  • %ek

    Krunched name of the entity the user clicked on. Like %e, except long names are shorted as in %fk.

  • %eL

    Either an empty string or -eL, depending on whether the Fast Project Loading preference if set. -eL is used by GNAT tools to specify whether symbolink links should be followed when parsing projects. This macro is only available in commands defined in the Build Manager and the Build Launcher dialogs.

  • %external

    Command line specified in the External Commands ‣ Execute command preference.

  • %f

    Base name of the currently selected file. Python equivalent:

    import os.path
    os.path.basename (GPS.current_context().file().name())
    
  • %F

    Absolute name of the currently opened file. Python equivalent:

    GPS.current_context().file().name()
    
  • %fk

    Krunched base name of the currently selected file. This is the same as %f except that long names are shortened with some letters replaced by “[...]”. Use this in menu labels to keep the menus narrow.

  • %fp

    Base name of the currently selected file. If the file is not part of the project tree or no file is selected, generate an error in the Messages view. This macro is only available in commands defined in the Build Manager and Build Launcher dialogs.

  • %gnatmake

    The gnatmake executable configured in your project file.

  • %gprbuild

    The gprbuild command line configured in your project file.

  • %gprclean

    Default cleaner configured in GPS. This can be, for example, gnat clean or gprclean. This macro is only available in commands defined in the Build Manager and Build Launcher dialogs.

  • %GPS

    GPS’s home directory (i.e., the .gps directory in which GPS stores its configuration files).

  • %i

    If the user clicked inside the Project view, name of the parent project, i.e., the one that is importing the one clicked on. With this definition of parent project, a given project may have multiple parents, but the one here is the one from the Project view..

  • %l

    Number of the line in which the user clicked. Python equivalent:

    GPS.current_context().line()
    
  • %o

    Object directory of the current project.

  • %O

    Object directory of the root project.

  • %system_bin_dir

    The directory containing the GPS executable.

  • %p

    Name of the current projec (not the project file). The .gpr extension is not included and the casing is the one in the project file not that of the file name itself. If the current context is an editor, the name of the project to which the source file belongs. Python equivalent:

    GPS.current_context().project().name()
    
  • %P

    Name of root project. Python equivalent:

    GPS.Project.root().name()
    
  • %Pb

    Basename of the root project file.

  • %Pl

    Name of the root project converted to lower case.

  • %pp

    Current project file pathname. If a file is selected, the project file to which the source file belongs. Python equivalent:

    GPS.current_context().project().file().name()
    
  • %PP

    Root project pathname. Python equivalent:

    GPS.Project.root().file().name()
    
  • %pps

    Similar to %pp, except it returns the project name prepended with -P or an empty string if there is no project file selected and the current source file does not belong to any project. This is intended mostly for use with the GNAT command line tools. GPS quotes the project name if it contains spaces. Python equivalent:

    if GPS.current_context().project():
       return "-P" & GPS.current_context().project().file().name()
    
  • %PPs

    Similar to :;file:%PP, except it returns the project name prepended with -P, or an empty string if the root project is the default project. This is intended mostly for use with the GNAT command line tools.

  • %(p|P)[r](d|s)[f]

    Replaced by the list of sources or directories of a project. This list is space-separated with all names surrounded by double quotes for proper handling of spaces in directories or file names. The first letter specifies the project and successive letters which files are in the list and related options:

    • P

      root project.

    • p

      The selected project or the root project if project is selected.

    • r

      Recurse through the projects, including all subprojects.

    • d

      List source directories. Python equivalent:

      GPS.current_context().project().source_dirs()
      
    • s

      List source files. Python equivalent:

      GPS.current_context().project().sources()
      
    • f

      Write the list into a file and replace the parameter with the name of the file. This file is never deleted by GPS; you must do so manually in the plugin when you no longer need it.

    Examples:

    • %Ps

      List of source files in the root project.

    • %prs

      List of files in the current project and all imported sub projects, recursively.

    • %prdf

      Name of a file containing a list of source directories in the current project and all imported sub projects, recursively.

  • %s

    Text selected by the user, if a single line was selected. If multiple lines are selected, returns the empty string

  • %S

    Text selected by the user or the current entity if no selection. If the entity is part of an expression (“A.B.C”), the whole expression is returned instead of the entity name.

  • %switches(tool)

    Value of IDE’Default_Switches (tool). If you have a tool whose switches are defined via an XML file in GPS, they are stored as Default_Switches (xxx) in the IDE package, and you can retrieve them using this macro. The result is a list of switches, or an empty list if none.

    This macro is only available in the commands defined in the Build Manager and Build Launcher dialogs.

  • %T

    Subtarget being considered for building. Depending on the context, this can correspond to such things as the base filename of a main source or makefile targets. This macro is only available in the commands defined in the Build Manager and Build Launcher dialogs.

  • %TT

    Like %TT, but the full path to main sources rather than the base filename.

  • %attr(Package'Name[,default])

    Project attribute Package’Name`L: the attribute :file:`Name from the package Package. You can omit Package' if Name is a top level attribute (e.g. Object_Dir). If the attribute is not defined in the project, an optional default value is returned, or an empty string if none is specified.

    This macro is only available in the commands defined in the Build Manager and Build Launcher dialogs and only supports attributes that return a single string, not those returning lists.

  • %dirattr(Package'Name[,default])

    Like %attr, but the directory part of an attribute value.

  • %baseattr(Package'Name[,default])

    Like %attr, but the base name an attribute value.

  • %vars

    List of switches of the form variable=value, where variable is the name of a scenario variable and value its current value, as configured in the Scenario view. All scenario variables defined in the current project tree are listed. You can also use %vars(-D) to generate a list of switches of the form -Dvariable=value. This macro is only available in the commands defined in the Build Manager and Build Launcher dialogs.

  • %X

    List of switches of the form -Xvariable=value, where variable is the name of a scenario variable and value its current value, as configured in the Scenario view. All the scenario variables defined in the current project tree are listed. This macro is only available in the commands defined in the Build Manager and Build Launcher dialogs.

  • %target

    The string --target=t where t is the build target, as determinted by the current toolchain.

  • %%

    The literal % character.

Another type of macros are expanded before commands are executed: they start with the $ character and represent parameters passed to the action by its caller. Depending on the context, GPS passes zero, one or many arguments to a action. You will commonly use these macros when you define your own VCS system. Also see the shell function execute_action, which executes an action and passes it arguments.

These macros are the following

  • $1, $2, ... $n

    Where n is a number. These are the argument with the corresponding number that was passed to the action.

  • $1-, $2-, ... $n-*

    Likewise, but a string concatenating the specified argument and all subsequent arguments.

  • $*

    String concatenating all arguments passed to the action.

  • $repeat

    Number of times the action has been consequtively executed. This is 1 (the first execution of the action) unless the user invoked the Repeat Next action.

    By default, when Repeat Next is invoked by the user, it repeats the following action the number of times the user specified. However, in some cases, either for efficiency reasons or for other technical reasons, you may want to handle the repeat yourself. Do this with the following action declaration:

    <action name="my_action">
       <shell lang="python">if $repeat==1: my_function($remaining + 1)</shell>
    </action>
    
    def my_function (count):
       """Perform an action count times"""
       ...
    

    The idea here is to do something only the first time the action is called (the if statement), but pass your shell function the number of times it should repeat (the $remaining parameter).

  • $remaining

    Like $repeat, but indicates the number of times the action remains to be executed. This is 0 unless the user invoked the Repeat Next action.

14.5.4. Filtering actions

By default, an action can execute in any context in GPS. When the user selects the menu or key, GPS executes the action. You can restrict when an action is permitted. If the current context does not permit the action, GPS displays an error message.

You can use one of several types of restrictions:

  • Using macro arguments (see Macro arguments).

    If an action uses one of the macro arguments defined in the previous section, GPS checks that the information is available. If not, it will not run any of the shell commands or external commands for that action.

    For example, if you specified %F as a parameter to a command, GPS checks there is a current file such as a currently selected file editor or a file node selected inside the Project view. This filtering is automatic: you do not have to do anything else.

    However, the current context may contain more information than you expect. For example, if a user clicks on a file name in the Project view, the current context contains a file (and hence satisfies %F) and also a project (and hence satisfies %p and similar macros).

  • Defining explicit filters

    You can also specify explicit restrictions in the customization files by using the <filter>, <filter_and> and <filter_or> tags. Use these tags to further restrict when the command is valid. For example, you can use them to specify that the command only applies to Ada files, or only if a source editor is currently selected.

14.5.4.1. The filters tags

You can define filters in one of two places in the customization files:

  • At the toplevel.

    You can define named filters at the same level as other tags such as <action>, <menu> or <button> tags. These are global filters that can be referenced elsewhere.

  • As a child of the <action> tag.

    These filters are anonymous, although they provide exactly the same capabilities as the ones above. These are intended for simple filters or filters that you use only once.

There are three different kinds of tags representing filters:

  • <filter>

    A simple filter. This tag has no child tag.

  • <filter_and>

    All the children of this tag are merged to form a compound filter. they are each evaluated in turn and if one of them fails, the whole filter fails. Children of this tag can be of type <filter>, <filter_and> or :file: <filter_or>.

  • <filter_or>

    Like <filter_and>, but as soon as one child filter succeeds, the whole filter succeeds.

If several filter tags are found under an <action> tag, they act as if they were all under a single <filter_or> tag.

The <filter>, <filter_and>, and <filter_or> tags all accept the following common attributes:

  • name (optional)

    Used to create named filters that can be reused, via the id attribute, elsewhere in actions or compound filters. The name can have any form.

  • error (optional)

    Error message GPS will display if the filter does not match and hence the action cannot be executed. If you are using the <filter_and> or <filter_or> tag, GPS will only display the error message of that filter.

In addition, the <filter> tag has the following specific attributes:

  • id (optional)

    If this attribute is specified, all other attributes are ignored. Use this to reference a named filter previously defined. Here is how you can make an action depend on a named filter:

    <?xml version="1.0" ?>
    <test_filter>
      <filter name="Test filter" language="ada" />
      <action name="Test action" >
         <filter id="Test filter" />
         <shell>pwd</shell>
      </action>
    </test_filter>
    

    GPS contains a number of predefined filters:

    • Source editor

      Match if the currently selected window in GPS is an editor.

    • Explorer_Project_Node

      Match if clicking on a project node in the Project view.

    • Explorer_Directory_Node

      Match if clicking on a directory node in the Project view.

    • Explorer_File_Node

      Match if clicking on a file node in the Project view.

    • Explorer_Entity_Node

      Match if clicking on an entity node in the Project view.

    • File

      Match if the current context contains a file (for example the focus is on a source editor or the focus is on the Project view and the currently selected line contains file information).

  • language (optional)

    Name of the language that must be associated with the current file in order for the filter to match. For example, if you specify ada, the user must have an Ada file selected for the action to execute. GPS determines the language for a file by using several methods such as looking at file extensions in conjunction with the naming scheme defined in the project files.

  • shell_cmd (optional)

    Shell command to execute. The output of this command is used to find if the filter matches: if it returns “1” or “true”, the filter matches. In any other case, the filter fails.

    Macro arguments (such as %f and %p) may be used in the text of the command to execute.

  • shell_lang (optional)

    Which language the command in shell_cmd is written. The default if that the command is written for the GPS shell.

  • module (optional)

    The filter only matches if the current window was created by this specific GPS module. For example, if you specify Source_Editor, the filter only matches if the active window is a source editor.

    You can obtain the list of module names by typing lsmod in the shell console at the bottom of the GPS window.

    This attribute is useful mostly when creating new contextual menus.

When several attributes are specified for a <filter> node (which cannot be combined with id), they must all match for the action to be executed:

<?xml version="1.0" ?>
<!-- The following filter only matches if the currently selected
     window is a text editor editing an Ada source file -->
<ada_editor>
  <filter_and name="Source editor in Ada" >
    <filter language="ada" />
    <filter id="Source editor" />
  </filter_and>

  <!-- The following action is only executed for such an editor -->

  <action name="Test Ada action" >
     <filter id="Source editor in Ada" />
     <shell>pwd</shell>
  </action>

  <!--  An action with an anonymous filter. it is executed if the
        selected file is in Ada even if the file was selected through
        the project view  -->

  <action name="Test for Ada files" >
      <filter language="ada" />
      <shell>pwd</shell>
  </action>
</ada_editor>

14.5.5. Adding new menus

Actions can be associated with menus, tool bar buttons, and keys, all using similar syntax.

Each menu item has an associated path, which it behaves like a UNIX path, except it references menus, starting from the menu bar itself. The first character of this path must be /. The last part is the name of the menu item. For example, specifying /Parent1/Parent2/Item as a menu path is a reference to a Parent1 ‣ Parent2 -> Item menu. If you are creating a new menu item, GPS creates any parent menus that do not already exist.

You bind a menu item to an action through the <menu> and <submenu> tags. The <menu> tag can have the following attributes:

  • action (required)

    Action to execute when the item is selected by the user. If no action by this name is defined, GPS does not add a new menu. If the action name starts with a ‘/’, it represents the absolute path to an action.

    Omit this attribute only when no title is specified for the menu. Doing that makes it a separator (see below).

    If you associate a filter with the action via the <filter> tag, the menu is greyed out when the filter does not match.

  • before (optional)

    Name of another menu item before which the new menu should be inserted. If that item has not been previously created, the new menu is inserted at the end. Use this attribute to control precisely where the item menu is displayed.

  • after (optional)

    Like before, but with a lower priority. If specified and there is no before attribute, it specifies an item after which the new item should be inserted.

The <menu> tag should have one XML child called <title>, which specifies the label of the menu. This label is actually a path to a menu, so you can define submenus.

You can define the accelerator keys for your menus using underscores in the title to designate the accelerator key. For example, if you want an accelerator on the first letter in a menu named File, set its title to _File.

The <submenu> tag accepts the before and after attributes, which operate the same way as for the <menu> tag. It accepts several children, such as <title> (which can present at most once), <submenu> (for nested menus), and <menu>.

<submenu> does not accept the action attribute. Use <menu> for clickable items that result in an action and <submenu> to define several menus with the same path.

Specify which menu the new item is added to in one of two ways:

  • Specify a path in the title attribute of <menu>
  • Put the <menu> as a child of a <submenu> node. This requires more typing, but allows you to specify the exact location, at each level, of the parent menu.

For example, this adds an item named mymenu to the standard Edit menu:

<?xml version="1.0" ?>
<test>
  <submenu>
    <title>Edit</title>
    <menu action="current file uses">
       <title>mymenu</title>
    </menu>
  </submenu>
</test>

The following has exactly the same effect:

<?xml version="1.0" ?>
<test>
  <menu action="current file uses">
    <title>Edit/mymenu</title>
  </menu>
</test>

The following adds a new item stats to the unit testing submenu in my_tools:

<?xml version="1.0" ?>
<test>
  <menu action="execute my stats">
     <title>/My_Tools/unit testing/stats</title>
  </menu>
</test>

The previous method is shorter but less flexible than the following, where we also create the My_Tools menu, if it does not already exist, to appear after the File menu. This cannot be done by using only <menu> tags. We also insert several items in that new menu:

<?xml version="1.0" ?>
<test>
  <submenu after="File">
    <title>My_Tools</title>
    <menu action="execute my stats">
       <title>unit testing/stats</title>
    </menu>
    <menu action="execute my stats2">
       <title>unit testing/stats2</title>
    </menu>
  </submenu>
</test>

If you add an item with an empty title or no title at all, GPS inserts a menu separator. For example, the following example will insert a separator followed by a File ‣ Custom menu:

<?xml version="1.0" ?>
<menus>
  <action name="execute my stats" />
  <submenu>
     <title>File</title>
     <menu><title/></menu>
     <menu action="execute my stats">
         <title>Custom</title>
     </menu>
  </submenu>
</menus>

14.5.6. Adding contextual menus

You can also add actions as new items in contextual menus anywhere in GPS. Contextual menus are displayed when the user right clicks and only show actions relevant to the current context.

Add an item using the <contextual> tag, which takes the following attributes:

  • action (required)

    Name of action to execute, which must be defined elsewhere in one of the customization files.

    If set to an empty string, a separator is inserted in the contextual menu. If you specify an item using the before or after attribute, the separator is displayed only when the specified item is.

  • before (optional)

    Name of another contextual menu item before which the new item should appear. You can find the list of names of predefined contextual menus by looking at the output of Contextual.list in the GPS shell console. The name of your contextual menu item is the value of the <title> child.

    There is no guarantee the new menu item will appear just before the specified item. For example, it will not if the new item is created before the specified menu item or if a later contextual menu item also specified it must be displayed before the same item.

  • after (optional)

    Like before, except it indicates the new menu item should appear after the specified item.

    If you specify both after and before, only the latter is honored.

  • group (optional, default 0)

    Allows you to create groups of contextual menus that are put next to each other. Items with the same group number appear before all items with a larger group number.

The <contextual> tag accepts one child tag, <Title>, which specifies the name of the menu item. If not specified, the menu item uses the name of the action. The title is the full path to the new menu item, like in the <menu> tag. You can create submenus by using a title of the form Parent1/Parent2/Menu. You can use macro arguments in the title, which are expended based on the current context. See Macro arguments.

GPS only displays the new contextual menu item if the filters associated with the action match the current context.

For example, the following example inserts a new contextual menu item that displays the name of the current file in the GPS console. This contextual menu is only displayed in source editors. This contextual menu entry is followed by a separator line, displayed when the menu item is:

<?xml version="1.0" ?>
<print>
  <action name="print current file name" >
    <filter module="Source_Editor" />
    <shell>echo %f</shell>
  </action>

  <contextual action="print current file name" >
    <Title>Print Current File Name</Title>
  </contextual>
  <contextual action="" after="Print Current File Name" />
</print>

14.5.7. Adding tool bar buttons

As an alternative to creating new menu items, you can create new buttons on the tool bar, by using the <button> tag. Like the <menu> tag, it requires an action attribute, which specifies what should be done when the button is pressed. The button is not created if the action action does not exist.

This tag accepts one optional attribute, stock which you can use to override the default image registered for the action or set one if the action no image. The value for this attribute is an icon specified by a <stock> node (which you can use to provide a label for the button or several sizes of the images for better rendering). (The stock attribute replaces the old <pixmap> child, which is no longer supported.)

The following example defines a new button:

<?xml version="1.0" ?>
<stats>
  <button action="undo" />   <!--  use default icon -->
  <button action="execute my stats" stock='my-image' />
</stats>

Use the <button> tag to create a simple button that the user can press to start an action. GPS also supports another type of button, a combo box, from which the user can choose among a list of choices. Create a combo box with the <entry> tag, which accepts the following attributes:

  • id (required)

    Unique id for this combo box, used later on to refer it, specifically from the scripting languages. It can be any string.

  • label (default)

    Text of a label to display on the left of the combo box. If not specified, no text is displayed

  • on-changed (default)

    Name of a GPS action to execute whenever the user selects a new value in the combo box. This action is called with two parameters: the unique id of the combo box and the newly selected text.

It also accepts any number of <choice> tags, each of which defines one value the user can choose from. These tags accept one optional attribute, on-selected, which is the name of a GPS action to call when that value is selected:

<action name="animal_changed">
   <shell>echo A new animal was selected in combo $1: animal is $2</shell>
</action>
<action name="gnu-selected">
   <shell>echo Congratulations on choosing a Gnu</shell>
</action>
<entry id="foo" label="Animal" on-changed="animal_changed">
   <choice>Elephant</choice>
   <choice on-selected="gnu-selected">Gnu</choice>
</entry>

GPS provides a more convenient interface for Python, the GPS.Toolbar class, which provides the same flexibility as above, but also gives you dynamic control over the entry and allows placement of buttons at arbitrary positions in the toolbar. See the Python documentation.

14.5.8. Binding actions to keys

All actions can be bound to specific key shortcuts through the <key> tag. It requires one action attribute to specify what to do when the key is pressed. The name of the action can start with a ‘/’ to indicate that a menu should be executed instead of a user-defined action. If the action is specified as an empty string, the key is no longer bound to any action.

This tag does not contain any child tags. Instead, its text contents specifies the keyboard shortcut. The name of the key can be prefixed by control-, alt-, shift- or any combination of these to specify the key modifiers to apply.

You can also define multiple key bindings similar to Emacs’ by separating them by a space. For example, control-x control-k means the user should press Ctrl-x, followed by a Ctrl-k to activate the corresponding action. This only works if the first key is not already bound to an action. If it is, you must first unbind it by passing an empty action to <key>.

Use an empty string as the key binding if you wish to deactivate a preexisting binding. The second example below deactivates the standard binding:

<?xml version="1.0" ?>
<keys>
  <key action="expand alias">control-o</key>
  <key action="Jump to matching delimiter" />

  <!--  Bind a key to a menu -->
  <key action="/Window/Close">control-x control-w</key>
</key>

If you bind multiple actions to the same key binding, they are executed sequentually, followed by any menu for which this key is an accelerator.

When GPS processes a <key> tag, it does the following:

  • Removes all actions bound to that key. This ensures that any action previously associated with it, either by default in GPS or in some other XML file, is no longer executed.
  • Adds the new key to the list of shortcuts that can execute the action. Any existing shortcut for the action is preserved, allowing multiple shortcuts for the action.

14.5.9. Configuring preferences

14.5.9.1. Creating new preferences

GPS contains a number of predefined preferences to configure its behavior and appearance, which are all customizable through the Edit ‣ Preferences menu.

You can add preferences for your extension modules through the usual GPS customization files. Preferences are different from project attributes (see Defining project attributes); the latter varies depending on which project is loaded by the user, while preferences are always set to the same value independent of what project is loaded.

You create your own preferences with the <preference> tag, which accepts the following attributes:

  • name (required)

    Name of the preference, used both when the preference is saved by GPS in the $HOME/.gps/preferences file and to query the value of a preference interactively through the GPS.Preference class in the GPS shell or Python. These names cannot contain spaces or underscore characters: use minus signs instead of the latter.

  • page (optional, default General)

    Name of the page in the preferences editor where the preference are edited. If the page does not already exist, GPS automatically creates it. If this is the empty string, the preference is not editable interactively. Use this to save a value from one session of GPS to the next without allowing the user to change it. Subpages are reference by separating pages name with colons (:).

  • default (optional, default depends on type of the preference)

    Default value of the preference. If not specified, this is 0 for integer preferences, the empty string for string preferences, True for boolean preferences, and the first possible choice for choice preferences.

  • tip (optional)

    Text of the tooltip that appears in the preferences editor dialog.

  • label (required)

    Name of the preference as it appears in the preferences editor dialog

  • minimum (optional, default 0), maximum (default 10)

    Minimum and maximum values for integer preferences.

  • type (required)

    Type of the preference. Must be one of:

    • boolean

    • integer

    • string

    • font

    • color

      A color name, in the format of a named color such as “yellow”, or a string like “#RRGGBB”, where RR is the red component, GG is the green component, and BB is the blue component.

    • choices

      The preference is a string whose value is chosen among a static list of possible values, each of which is defined in by a <choice> child of the <preference> node.

Here is an example that defines a few new preferences:

<?xml version="1.0"?>
<custom>
   <preference name="my-int"
               page="Editor"
               label="My Integer"
               default="30"
               minimum="20"
               maximum="35"
               page="Manu"
               type="integer" />

   <preference name="my-enum"
               page="Editor:Fonts &amp; Colors"
               label="My Enum"
               default="1"
               type="choices" >
     <choice>Choice1</choice>
     <choice>Choice2</choice>  <!--  The default choice -->
     <choice>Choice3</choice>
   </preference>
</custom>

The values of the above preferences can be queried in the scripting languages:

  • GPS shell:

    Preference "my-enum"
    Preference.get %1
    
  • Python:

    val = GPS.Preference ("my-enum").get ()
    val2 = GPS.Preference ("my-int").get ()
    

14.5.9.2. Setting preferences values

You can force specific default values for the preferences in the customization files through the <pref> tag. This is the same tag used by GPS itself when it saves the preferences edited via the preferences dialog.

This tag requires one attribute, name, the name of the preference for which you are setting a default value. These names are defined when the preference is registered in GPS. You can find them by looking at the $HOME/.gps/preferences file for each user or by looking at one of the predefined GPS themes.

It accepts no child tags, but the value of the <pref> tag defines the default value of the preference, which is used unless the user has overridden it in his own preferences file.

Any setting you defined in the customization files is overridden by a specification of that preference in the user’s preferences file.

The <pref> tag is mostly intended for use in themes (see Creating themes).

14.5.10. Creating themes

You can create your own themes and share them between users and then selectively chose which themes each user want to activate through the preferences dialog (see GPS Themes).

You create new themes in the customization files using the <theme> tag.

This tag accepts the following attributes:

  • name (required)

    Name of the theme as it appears in the preferences dialog

  • description (optional)

    This text should explain what the theme does. It appears in the preferences dialog when the user selects that theme.

  • category (optional, default General)

    Name of the category in which the theme should be presented in the preferences dialog. Categories are currently only used to organize themes graphically. GPS creates a category automatically if you choose one that has not previously been created.

This tag accepts any other customization tags including setting preferences (<pref>), defining key bindings (<key), and defining menus (<menu>).

If you define the same theme in multiple locations (either multiple times in the same customization file or in different files), the customizations in each are merged. The first definition of the theme seen by GPS sets the description and category for the theme.

All child tags of the theme are executed when the user activates the theme in the preferences dialog. There is no strict ordering of the child tags. The default order is the same as for the customization files themselves: first the predefined themes of GPS, then the ones defined in customization files found through the GPS_CUSTOM_PATH directories, and finally the ones defined in files found in the user’s own GPS directory.

Here is an example of a theme:

<?xml version="1.0" ?>
<my-plug-in>
   <theme name="my theme" description="Create a new menu">
       <menu action="my action"><title>/Edit/My Theme Menu</title></menu>
   </theme>
</my-plug-in>

14.5.11. Defining new search patterns

The search dialog contains a number of predefined search patterns for Ada, C, and C++. These are generally complex regular expressions, presented in the dialog with a more descriptive name. For example, Ada assignment.

Define your own search patterns in the customization files using the <vsearch-pattern> tag. This tag can have the following child tags:

  • <name>

    String displayed in the search dialog to represent the new pattern. This is the text the user sees (instead of the often hard-to-understand regular expression)

  • <regexp>

    Regular expression to use when the pattern is selected by the user. Be careful to protect reserved XML characters such as < and replace them by their equivalent expansion (&lt; in that case).

    This tag accepts one optional attribute, case-sensitive a boolean that specifies whether the search should distinguish lower case and upper case letters. The default is false.

  • <string>

    A constant string that should be searched. Provide either <regexp> or <string>, but not both. If both are provided, the first <regexp> child found is used. The tag accepts the same optional attribute case-sensitive as above.

Here is a short example, showing how the Ada assignment pattern is defined:

<?xml version="1.0" ?>
<search>
  <vsearch-pattern>
    <name>Ada: assignment</name>
    <regexp case-sensitive="false">\\b(\\w+)\\s*:=</regexp>
  </vsearch-pattern>
</search>

14.5.12. Adding support for new languages

Define new languages in a custom file by using the <Language> tag. Defining languages gives GPS the ability to perform language-specific operations such as highlighting the syntax of a file, exploring a file using the Project view, and finding files associated with that language.

The following child tags are available:

  • <Name>

    Short string giving the name of the language.

  • <Parent>

    Optional name of language that provides default values for all properties not explicitly set.

  • <Spec_Suffix>

    String identifying the filetype (including the ‘.’ character) of spec (definition) files for this language. If the language does not have the notion of spec or definition file, you should use the <Extension> tag instead. Only one such tag is permitted for each language.

  • <Body_Suffix>

    String identifying the filetype of body (implementation) files for this language. Only one such tag is permitted for each language.

  • <Obj_Suffix>

    String identifying the extension for object files for this language. For example, it is .o for C or Ada and .pyc for Python. The default is -, which indicates there are no object files.

  • <Extension>

    String identifying one of the valid filetypes for this language. You can specify several such children.

  • <Keywords>

    Regular expression for recognizing and highlighting keywords. You can specify multiple such tags, which will all be concatenated into a single regular expression. If the regular expression needs to match characters other than letters and underscore, you must also edit the <Wordchars> tag. If you specified a parent language, you can append to the parent <Keywords> by providing a mode attribute set to append (the default for mode is override, where the <Keywords> definition replaces the one from the parent).

    You can find the full grammar for regular expression in the spec of the file g-regpat.ads in the GNAT run time.

  • <Wordchars>

    Most languages have keywords that only contain letters, digits, and underscore characters. If you want to also include other special characters (for example < and > in XML), use this tag. The value of this tag is a string consisting of all the special characters that may be present in keywords. You need not include letters, digits or underscores.

  • <Context>

    Information that GPS uses to determine the syntax of a file for highlighting purposes. The following child tags are defined:

    • <Comment_Start>, <Comment End>

      Strings that determine the start and end of a multiple-line comment.

    • <New_Line_Comment_Start>

      A regular expression defining the beginning of a single line comment that ends at the next end of line. This regular expression may contain multiple possibilities, such as ;|# for comments starting after a semicolon or after the pound sign. If you specified a parent language, you can append to the parent’s <New_Line_Comment_Start> by including a mode attribute with a value of append (the default is override, meaning the <New_Line_Comment_Start> definition replaces the one in the parent).

    • <String_Delimiter>

      Character defining the string delimiter.

    • <Quote_Character>

      Character defining the quote (also called escape) character, used to include the string delimited inside a string (\ in C).

    • <Constant_Character>

      Character defining the beginning of a character literal, in languages that support such literals (e.g., C).

    • <Can_Indent>

      Boolean indicating whether indentation is enabled. The indentation mechanism is the same for all languages: the number of spaces at the beginning of the current line is used when indenting the next line.

    • <Syntax_Highlighting>

      Boolean indicating whether the language syntax should be highlighted and colorized.

    • <Case_Sensitive>

      Boolean indicating whether the language (in particular the identifiers and keywords) is case sensitive.

    • <Accurate_Xref>

      Boolean indicating whether cross reference information for this language is fully accurate or whether it is either an approximation or not present). Default is False.

    • <Use_Semicolon>

      Boolean indicating whether semicolons are expected in sources and can be used as a delimiter for syntax highlighting purposes. Default is False.

  • <Categories>

    Optional tag to describe the categories supported by the Project view. This tag contains a list of <Category> tags, each describing the characteristics of a single category, with the following child tags:

    • <Name>

      Name of the category, either one of the predefined categories or a new name, in which case GPS will create a new category.

      The predefined categories are package, namespace, procedure, function, task, method, constructor, destructor, protected, entry, class, structure, union, type, subtype, variable, local_variable, representation_clause, with, use, include, loop_statement, case_statement, if_statement, select_statement, accept_statement, declare_block, simple_block, and exception_handler.

    • <Pattern>

      Regular expression to select a language category. Like <Keywords> tags, if you specify multiple <Pattern> tags, GPS will concatenate them into a single regular expression.

    • <Index>

      Index of the subexpression in the pattern that extracts the name of the entity in this category.

    • <End_Index>

      Optional tag providing the index of the subexpression used to start the next search. The default is the end of the pattern.

    • <Icon>

      Name of a stock icon for that category (see Adding stock icons). This tag is currently ignored and reserved for future use.

  • <Project_Field>

    Information about the tools used to support this language. The name of these tools is stored in the project files so you can specify only a limited number of tools. This tag is currently only used by the project properties and wizard and not by other components of GPS.

    This tag two attributes:

    • Name

      Name of the attribute in the project file. Currently, you can only specify compiler_command.

    • Index

      If present, specifies the index to use for the attribute in the project file. The line defining this attribute looks like:

      for Name ("Index") use "value";
      

      e.g:

      for Compiler_Command ("my_language") use "my_compiler";
      

      The value of the index should be either the empty string or the name of the language.

    The value of this attribubte is the string to use in the project properties editor when editing this project field.

here is an example of a language definition for the GPS project files:

<?xml version="1.0"?>
<Custom>
  <Language>
    <Name>Project File</Name>
    <Spec_Suffix>.gpr</Spec_Suffix>
    <Keywords>^(case|e(nd|xte(nds|rnal))|for|is|</Keywords>
    <Keywords>limited|null|others|</Keywords>
    <Keywords>p(ackage|roject)|renames|type|use|w(hen|ith))\\b</Keywords>

    <Context>
      <New_Line_Comment_Start>--</New_Line_Comment_Start>
      <String_Delimiter>&quot;</String_Delimiter>
      <Constant_Character>&apos;</Constant_Character>
      <Can_Indent>True</Can_Indent>
      <Syntax_Highlighting>True</Syntax_Highlighting>
      <Case_Sensitive>False</Case_Sensitive>
    </Context>

    <Categories>
      <Category>
        <Name>package</Name>
        <Pattern>^[ \\t]*package[ \\t]+((\\w|\\.)+)</Pattern>
        <Index>1</Index>
      </Category>
      <Category>
        <Name>type</Name>
        <Pattern>^[ \\t]*type[ \\t]+(\\w+)</Pattern>
        <Index>1</Index>
      </Category>
    </Categories>
  </Language>
</Custom>

14.5.13. Defining text aliases

GPS provides a mechanism known as “aliases”. The user can define these using the Edit->Aliases menu.

Each alias has a name, generally a short string of characters. When you type that string in any textual entry in GPS (usually a source editor, but also entry fields anywhere, such as in a file selector) and press the special activation key (by default Ctrl-o, but controlled by a preference), GPS replaces the string by the text you have associated with it.

Alias names can contain any character except newline but must start with a letter. GPS looks backward to the start of the word before the current cursor position, and if the characters between there and the cursor position is an alias name (using a case insensitive comparison), it expands the alias.

_images/aliases.jpg

The alias editor is divided into three main parts. The left shows the list of currently defined aliases. Clicking on any of them displays its replacement text. If you click a second time, GPS displays a text entry allowing you to rename that alias. A checkbox at the bottom determines whether the editor displays read-only aliases (i.e., system-wide aliases).

The second part displays the expansion text for the alias, at the bottom right corner. This text can span multiple lines and contain macros, which are displayed in a different color. You can insert these macros either by typing their symbols (as shown below) or by right-clicking in the editor and selecting the entity in the contextual menu.

The alias editor supports the following macros:

  • %_

    Position in the replacement text where the cursor is placed.

  • %name

    Name of a parameter. name can contain any characters except closing parenthesis. See below for more information on parameters.

  • %D

    Current date, in ISO format. The year is displayed first, then the month and day.

  • %H

    Current time (hour, minutes, and seconds).

  • %O

    For recursive aliases expansion. This macro expands the text before it in the current replacement of the parameters and possibly other recursive expansions. This is similar to pressing Ctrl-o in the expansion of the alias.

    You cannot expand an alias recursively when already expanding that alias. If the alias expansion for, e.g., procedure contains procedure%O, the inner procedure is not expanded.

  • %%

    A percent sign.

The remaining macros are only expanded if the alias is being expanded in a source editor:

  • %l

    Line on which the cursor is when pressing Ctrl-o.

  • %c

    Like %l, except the current column.

  • %f

    Name of current file (its base name only, not including directory).

  • %d

    Directory containing current file.

  • %p

    Base name of the project file referencing the current file.

  • %P

    Like %p, but the full name of the project file (directory and base name).

GPS preserves the indentation of the alias when it is expanded. All lines are indented the same as the alias name. You can override this default behavior by selecting the checkbox Indent source editor after expansion. In that case, GPS replaces the name of the alias by its expansion and then recomputes the position of each line with its internal indentation engine as if the text had been inserted manually.

The third part of the alias editor, the top right corner, lists the parameters for the currently selected alias. Whenever you insert a %name string in the expansion text, GPS detects new, changed, or deleted parameter references and updates the list of parameters to show the current list.

Each parameter has three attributes:

  • name

    The name you use in the expansion text of the alias in the %name macro.

  • Environment

    Whether the default value of the parameter comes from the list of environment variables set before GPS was started.

  • default value

    Instead of getting the default value from the environment variable, you can also specify a fixed value. Clicking on the initial value of the currently selected variable opens a text entry which you can use to edit this default value.

When an alias that contains parameters is expanded, GPS first displays a dialog to ask for the value of the parameters. You can interactively enter this value, which replaces all corresponding %name entities in the expanded text.

14.5.14. Alias files

Customization files can also contain alias definitions that can be used to create project or system- wide aliases. All customization files are parsed to look for aliases definitions. All customization files are treated as read-only by GPS and therefore cannot be edited through its graphical interface. You can override some of the aliases in your own custom files. The system files are loaded first and aliases defined there can be overridden by the user-defined file. There is one specific files which must contain only aliases definitions: $HOME/.gps/aliases. Whenever you edit aliases graphically or create new ones, they are stored in this file, which is the only one GPS ever modifies automatically.

These files are standard XML customization files. The XML tag to use is <alias>, one per new alias. The following example contains a standalone customization file, though you may wish to merge the <alias> tag into any other customization file.

The following child tags are supported:

  • <alias>

    Indicates the start of a new alias. It has one mandatory attribute, name, the text to type before pressing Ctrl-o, and one optional attribute, indent, which, if set to true tells GPS to recompute the indentation of the newly inserted paragraph after the expansion.

  • <param>

    One per alias parameter. It has one mandatory attribute, name, the name in %{name) in the alias expansion text, and one optional attribute, environment, indicating whether or not the default value must be read from the environment variables.

  • <text>

    Replacement text, possibly multiple lines.

Here is an example of an alias definition in a configuration file:

<?xml version="1.0"?>
<Aliases>
  <alias name="proc" >
    <param name="p" >Proc1</param>
    <param environment="true" name="env" />
    <text>procedure %(p) is
%(env)%_
end %(p);</text>
  </alias>
</Aliases>

14.5.15. Defining project attributes

Project files are required by GPS and store various pieces of information related to the current set of source files, including how to find the source files and how the files should be compile or manipulated through various tools.

The default set of attributes used by GPS in a project file is limited to those attributes used by tools packaged with GPS or GNAT. If you are delivering your own tools, you may want to store similar information in the project files, since they are a very convenient location to associate specific settings with a given set of source files.

GPS lets you manipulate the contents of projects through XML customization files and script commands. You can add your own typed attributes into the projects and have them saved automatically when the user saves the project and reloaded automatically when GPS reloads the project.

14.5.15.1. Declaring the new attributes

You can declare new project attributes in two ways: either using the advanced XML tags below or the <tool> tag (see Defining tool switches).

The customization files support the file:<project_attribute> tag, used to declare attributes GPS should support in a project file. Attributes that are not supported by GPS are not accessible through the GPS scripting languagues and generate warnings in the Messages window.

Each project attributes has a type typed and can either have a single value or have a set of values (a list). Each value can be a free-form string, a file name, a directory name, or a value extracted from a list of preset values.

Attributes declared in these customization files are also graphically editable through the project properties dialog or the project wizard. When you define an attribute, you need to specify how it is presented to the GPS user.

The <project_attribute> tag accepts the following attributes:

  • package (string)

    Package in the project file containing the attribute. Good practice suggests that one such package should be used for each tool. These packages provide namespaces so that attributes with the same name but for different tools do not conflict with each other.

  • name (string, required)

    Name of the attribute. A string with no space that represents a valid Ada identifier (typically starting with a letter and be followed by a set of letters, digits or underscores). This is an internal name used when saving the attribute in a project file.

  • editor_page (string, default General)

    Name of the page in the Project Properties editor dialog in which the attribute is presented. If no such page exists, GPS creates one. If the page already exists, the attribute is appended to the bottom of those already on the page.

  • editor_section (string)

    Name of the section, if any, inside the editor page where the attribute is displayed. These sections are surrounded by frames, the title of which is given by the this attribute. If not present, the attribute is put in an untitled section.

  • label (string, default: name of the attribute)

    Textual label displayed to the left of the attribute in the graphical editor used to identify the attribute. However, it can be set to the empty string if the attribute is in a named section of its own, since the title of the section may be good enough.

  • description (string)

    Help message describing the role of the attribute, displayed as a tooltip if the user hovers over the attribute.

  • list (boolean, default false)

    If true, the project attribute contains a list of values, as opposed to a single value. An example is the list of source directories in standard projects.

  • ordered (boolean, default false)

    Only relevant if the project attribute contains a list of values, when it indicates whether the order of the values is relevant. In most cases, it is not. However, the order of source directories, for example, matters since it also indicates where GPS searches for the source files, and it stops at the first match.

  • omit_if_default (boolean, default true)

    Whether the project attribute should be set explicitly in the project if the user left it with its default value. Enable this to keep the project files as simple as possible if all the tools using this attribute know about the default value. Otherwise, set it false to always emit the definition of the project attribute.

  • base_name_only (boolean, default false)

    If the case of attributes that are a file or directory name, whether the base name (true) or the full path (false) is stored. In most cases, the full path is best. However, since GPS looks for source files in the list of directories the list of source files, for example, should only contain base names. This also increases the portability of project files.

  • case_sensitive_index (true, false (default), or file)

    Only relevant for project attributes that are indexed on another attribute (see below for more information on indexed attributes). It indicates whether two indexes that differ only by their casing are considered the same. For example, if the index is the name of one of the languages supported by GPS, the index is case insensitive since “Ada” is the same as “C”.

    The value file indicates that the case sensitivity is the same as the filesystem of the local host. Use that value when the index is a filename.

  • hide_in (string)

    Context in which GPS will not allow graphical editing of this attribute. GPS provides three such contexts (wizard, library_wizard, and properties corresponding to the project creation wizards and the project properties editor). If any of those contexs are specified, GPS will not display the widget to edit this attribute. Use this to keep the graphical interface simple.

  • disable_if_not_set (boolean, default false)

    If true, the field to edit this attribute is greyed out if the attribute is not explicitly set in the project. In most cases, you will not specify this, since the default value of the attribute can populate that field. However, when the value of the attribute is automatically computed depending on other attributes, you cannot specify the default value in the XML file, and it might be simpler to grey out the field. A checkbox is displayed next to the attribute so the user can choose to enable the field and add the attribute to the project.

  • file:disable (space-separated list of attribute names)

    List of attribute whose fields should be greyed out if this attribute is specified. This only works if both the current attribute and the referenced attributes all have their disable_if_not_set attribute set true. Use this to create mutually exclusive attributes.

14.5.15.2. Declaring the type of the new attributes

The type of the project attribute is specified by child tags of <project_attribute>. The following tags are recognized:

  • <string>

    Attribute is composed of a single string or a list of strings. This tag accepts the following XML attributes:

    • default (string)

      Default value of the attribute. If the attribute’s type is a file or directory, the default value is normalized: an absolute path is generated based on the project’s location, with ”.” representing the project’s directory. As a special case, if default is surrounded by parenthesis, no normalization is done so you can on test whether the user is still using the default value.

      Another special case is when you specify project source files, which is replaced by the known list of source files for the project. However, this does not work from the project wizard, since the list of source files has not been computed yet.

    • type (empty string (default), file, directory, or unit)

      What the string represents. In the default case, any value is valid. For file, it should be a file name, although no check is done to ensure the file actually exists. Similarly, directory tells GPS to expect a directory. For units, GPS should expect the name of one of the project’s units.

    • filter (none, project, extending_project)

      Ignored for all types except file, where it further specifies what type of files should be specified by this attribute. If none, any file is valid. If project, only files from the selected project are valid. If extended_project, only the files from the project extended by the current project can be specified. This attribute is not shown if the current project is not an extension project.

    • allow_empty (boolean, default True)

      Whether the value for this attribute can be an empty string. If not and the user does not specify a value, GPS will display an error message in the project properties editor and project wizard.

  • <choice>

    One of the valid values for the attribute. Use multiple occurrences of this tag to provide a static list of such values. If combined with a <string> tag, indicates that the attribute can be any string, although a set of possible values is provided to the user. This tag accepts one optional XML attribute, default, a boolean which indicates whether this value is the default. If several details attributes are present the default value of the attribute is a list, as opposed to a single value.

  • <shell>

    GPS scripting command to execute to get a list of valid values for the attribute. Like the <choice> tag, this can be combined with a <string> tag to indicate that the list of values returned by the scripting command is only a set of possible values, but that any valid is valid.

    The <shell> tag accepts two attributes:

    • lang (string, default shell)

      Scripting language in which the command is written. The only other possible value is python.

    • default (string)

      Default value of the attribute if the user has not specied one.

Sometimes either the type of the project attribute or its default value depends on what the attribute applies to. The project file supports this in the form of indexed project attributes. This, for example, is used to specify the name of the executable generated when compiling each of the main files in the project (e.g., the executable for gps.adb is gps.exe and the one for main.c is myapp.exe).

You can also declare such attributes in XML files. In such cases, the <project_attribute> tag should have one <index> child, and zero or more <specialized_index> children. Each of these two tags in turn accepts one of the already mentioned <string>, <choice>, or <shell> tags as children.

The <index> tag specifies what other project attribute is used to index the current one. In the example given above for the executable names, the index is the attribute containing the list of main files for the project.

It accepts the following XML attributes:

  • attribute (string, required)

    Name of the other attribute, which must be declared elsewhere in the customization files and whose type must be a list of values.

  • package (string)

    Package in which the index project attribute is defined. This is used to uniquely identify attributes with the same name.

Use the <specialized_index> tag to override the default type of the attribute for specific values of the index. For example, project files contain an attribute specifying the name of the compiler for each language, which is indexed on the project attribute specifying the language used for each source file. Its default value depends on the language (gnatmake for Ada, gcc for C, etc.). This attribute requires one XML attribute, value, which is the value of the attribute for which the type is overriden.

Almost all the standard project attributes are defined through an XML file, projects.xml, which is part of the GPS installation. Examine this file for advanced examples on declaring project attributes.

14.5.15.3. Examples

The following declares three attributes, each with a single string as their value. This string represents a file in the first case and a directory in the last two:

<?xml version="1.0"?>
<custom>
  <project_attribute

      name="Single1"
      package="Test"
      editor_page="Tests single"
      editor_section="Single"
      description="Any string">

     <string default="Default value" />
  </project_attribute>

  <project_attribute
      name="File1"
      package="Test"
      editor_page="Tests single"
      editor_section="Single"
      description="Any file" >

      <string type="file" default="/my/file" />
  </project_attribute>

  <project_attribute
      name="Directory1"
      package="Test"
      editor_page="Tests single"
      editor_section="Single"
      description="Any directory" >

      <string type="directory" default="/my/directory/" />
  </project_attribute>
</custom>

The following declares an attribute whose value is a string. However, it provides list of predefined possible values as an help for the user. If the <string> tag was not specified, the attribute’s value could only be one of the three possible choices:

<?xml version="1.0" ?>
<custom>
  <project_attribute
      name="Static2"
      package="Test"
      editor_page="Tests single"
      editor_section="Single"
      description="Choice from static list (or any string)" >

      <choice>Choice1</choice>
      <choice default="true" >Choice2</choice>
      <choice>Choice3</choice>
      <string />
  </project_attribute>
</custom>

The following declares an attribute whose value is one of the languages currently supported by GPS. Since this list of languages is only known when GPS is executed, the example uses a script command to query this list:

<?xml version="1.0" ?>
<custom>
 <project_attribute
      name="Dynamic1"
      package="Test"
      editor_page="Tests single"
      editor_section="Single"
      description="Choice from dynamic list" >

      <shell default="C" >supported_languages</shell>
  </project_attribute>
</custom>

The following declares an attribute whose value is a set of file names. The order of files in this list matters to the tools using this attribute:

<?xml version="1.0" ?>
<custom>
 <project_attribute
      name="File_List1"
      package="Test"
      editor_page="Tests list"
      editor_section="Lists"
      list="true"
      ordered="true"
      description="List of any file" >

      <string type="file" default="Default file" />
  </project_attribute>
</custom>

The following declares an attribute whose value is a set of predefined values. By default, two such values are selected, unless the user overrides the default:

<?xml version="1.0" ?>
<custom>
  <project_attribute
      name="Static_List1"
      package="Test"
      editor_page="Tests list"
      editor_section="Lists"
      list="true"
      description="Any set of values from a static list" >

      <choice>Choice1</choice>
      <choice default="true">Choice2</choice>
      <choice default="true">Choice3</choice>
  </project_attribute>
</custom>

The following declares an attribute whose value is a string. However, the value is specific to each language (it could, for example, be the name of a compiler to use for that language). This is an indexed attribute, with two default values, one for Ada and one for C. All other languages have no default value:

<?xml version="1.0" ?>
<custom>
  <project_attribute
      name="Compiler_Name"
      package="Test"
      editor_page="Tests indexed"
      editor_section="Single">

      <index attribute="languages" package="">
         <string default="" />
      </index>
      <specialized_index value="Ada" >
         <string default="gnatmake" />
      </specialized_index>
      <specialized_index value="C" >
         <string default="gcc" />
      </specialized_index>
  </project_attribute>
</custom>

14.5.15.4. Accessing project attributes

Attributes you define are accessible from the GPS scripting languages like all the standard attributes, see Querying project switches.

For example, you can access the Compiler_Name attribute we created above with a python command similar to:

GPS.Project.root().get_attribute_as_string ("Compiler_Name", "Test", "Ada")

You can also access the list of main files for the project, for example, by calling:

GPS.Project.root().get_attribute_as_list ("main")

14.5.16. Adding casing exceptions

You can use the customization files to declare a set of case exceptions by using the <case_exceptions> tag. Put each exception in child tag of <word> or <substring>. GPS uses these exceptions to determine the case of identifiers and keywords when editing case insensitive languages (except if corresponding case is set to Unchanged). See The Preferences Dialog. Here is an example:

<?xml version="1.0" ?>
<exceptions>
  <case_exceptions>
     <word>GNAT</word>
     <word>OS_Lib</word>
     <substring>IO</substring>
  </case_exceptions>
</exceptions>

14.5.17. Adding documentation

You can add new documentation to GPS in various ways. You can create a new menu, through a <menu> tag in a configuration file, associated with an action that either spawns an external web browser or calls the function GPS.Help.browse(). However, this will not show the documentation in the Help ‣ Contents menu, which is where people expect to find it. To do both, use the <documentation_file> tag. These tags are usually found in a gps_index.xml file, but are permitted in any customization file.

Your documentation files can contain the usual HTML links. In addition, GPS treats links starting with ‘%’ specially and considers them as script commands to execute instead of files to display. The following examples show how to insert a link that, which clicked by the user, opens a file in GPS:

<a href="%shell:Editor.editor g-os_lib.ads">Open runtime file</a>

The first token after ‘%’ is the name of the language; the command to execute is after the ‘:’ character.

The <documentation_file> tag accepts the following child tags:

  • <name>

    Name of the file, either an absolute filename or a filename relative to one of the directories in GPS_DOC_PATH. If this child is omitted, you must specify a <shell> child. The name can contain a reference to a specific anchor in the HTML file, using the standard HTML syntax:

    <name>file#anchor</name>
    
  • <shell>

    Name of a shell command to execute to get the name of the HTML file. This command could create the HTML file dynamically or download it locally using some special mechanism. This child accepts one attribute, lang, the name of the language in which the command is written

  • <descr>

    Description for this help file, which appears as a tool tip for the menu item.

  • >category>

    Used in the Help ‣ Contents menu to organize all documentation files.

  • <menu>

    Full path to the menu. See Adding new menus. If not set, GPS does not display a menu item for this file, although it still appears in the Help->Contents menu

    This tag accepts two attributes, before and after, that control the position of the menu item. If the new menu is inserted in a submenu, the attribute controls the deeper nesting. Parent menus are created as needed, but if you wish to control their display order, create them first with a <submenu> tag.

The following example creates a new entry item in the Help menu, that displays file.html (searched for in the GPS_DOC_PATH path):

<?xml version="1.0"?>
<index>
   <documentation_file>
      <name>file.html</name>
      <descr>Tooltip text</descr>
      <category>name</category>
      <menu>/Help/item</menu>
   </documentation_file>
</index>

The directories given by the GPS_DOC_PATH environment variable are searched for the HTML documentation files. However, you can also use the <doc_path> XML node to define additional directories to search. Such a directory is relative to the installation directory of GPS. For example:

<?xml version="1.0"?>
<GPS>
   <doc_path>doc/application/</doc_path>
</GPS>

adds the directory <prefix>/doc/application to the search path for documentation.

Youc an also add such a directory via Python, as in:

GPS.HTML.add_doc_directory ('doc/application')

14.5.18. Adding stock icons

You can also define ‘stock icons’ in an XML configuration file. Stock icons are pictures that are identified by their label and are used throughout GPS in places such as buttons, menus and toolbars.

You must declare stock icons using the tag <icon> within the global tag <stock>. The attribute id is the label used to identify the stock icon and the attribute file is the filename (either absolute or relative to the GPS icons directory) containing the actual picture. If you need to read the icons from a directory relative to the location of the plug-in, you should use a Python script like:

XML = r"""<GPS><stock>
    <icon id="gtk-new" file="${icons}/file.svg"/>
  </stock></GPS>"""

icons = os.path.normpath(
   os.path.join(os.path.dirname(__file__), "../dir"))
XML = XML.replace("${icons}", icons)
GPS.parse_xml(XML)

If you intend to use the stock icon in a toolbar, use the attribute label to specify the text to display in the toolbar, under the button, when the toolbar is configured to show text.

For icons intended to be displayed at multiple sizes, specify multiple files corresponding to these multiple sizes by adding children to the main <icon> tag, with the tag <alternate> containing a file attribute and a size attribute giving the size for which this alternate source should be used.

Possible values for the size attribute are:

  • Icon_Size_Menu

    Menu item, typically 16x16 pixels.

  • Icon_Size_Small_Toolbar

    Button in a small toolbar, typically 18x18 pixels.

  • Icon_Size_Large_Toolbar

    Button in a large toolbar, typically 24x24 pixels.

  • Icon_Size_Button

    Standard button, typically 20x20 pixels.

  • Icon_Size_Dnd

    Image used during drag-and-drop operation, typically 32x32 pixels.

  • Icon_Size_Dialog

    Main image in a dialog, typically 48x48 pixels

Here is an example:

<?xml version="1.0"?>
<my_visual_preferences>
  <stock>
    <icon id="myproject-my-picture" file="icons/my-picture.png" />
    <icon id="myproject-multipurpose-image"
           label="do something"
           file="icons/icon_default.png">
       <alternate file="icons/icon_16.png" size="Icon_Size_Menu" />
       <alternate file="icons/icon_24.png" size="Icon_Size_Large_Toolbar" />
       <alternate file="icons/icon_20.png" size="Icon_Size_Button" />
    </icon>

  </stock>
</my_visual_preferences>

As shown in the example above, you should prefix the label with a unique name, here myproject-, to make sure predefined stock icons do not get overridden by your icons.

14.5.19. Customizing Remote Programming

There are two parts to specifying the configuration of remote programming functionality: the configuration of the tools (remote connection tools, shells, and rsync parameters) and the servers.

The first part (see Defining a remote connection tool, Defining a shell, and Configuring rsync usage) is performed by a pre-installed file in the plug-ins directory called protocols.xml.

The second part (see Defining a remote server and Defining a remote path translation) creates a remote.xml file in the user’s gps directory when the user has configured them (see Setup the remote servers). System-wide servers can be also installed.

14.5.19.1. Defining a remote connection tool

A remote connection tool is responsible for making a connection to a remote machine. GPS already defines several remote access tools: ssh, rsh, telnet, and plink. You can add support other tools using the tag <remote_connection_config>, which requires a name attribute giving the name of the tool. This name need not necessarilly correspond to the command used to launch the tool.

The following child tags are defined:

  • <start_command> (required)

    The command used to launch the tool. This tag supports the use_pipes attribute, which selects on Windows the manner in which GPS launchs the remote tools and accepts the following values:

    • true

      Use pipes to launch the tool.

    • false (default)

      Use a tty emulation, a bit slower but allows password prompt retrieval with some tools.

  • <start_command_common_arg>

    Arguments provided to the tool. This string can contain the following macros, which are replaced by the following strings:

    • %C: Command executed on the remote host (normally the shell command).
    • %h: Remote host name.
    • %U: Value of <fstart_command_user_args>, if specified.
    • %u: User name.

    If you have not included either %u or %U in the string and the user specifies a username in the remote connection configuration, GPS places the value of <start_command_user_args> at the beginning of the arguments.

  • <start_command_user_args>

    Arguments used to define a specific user during connection. %u is replaced by the user name.

  • <send_interrupt>

    Character sequence to send to the connection tool to interrupt the remote application. If not specified, an Interrupt signal is sent directly to the tool.

  • <user_prompt_ptrn>, <password_prompt_ptrn>, <passphrase_prompt_ptrn>

    Regular expressions to detect username, password, and passphrase prompts, respectively, sent by the connection tool. If not specified, appropriate defaults are used.

  • <extra_ptrn>

    Used to handle prompts from the connection tool other than for username, password or passphrase. The auto_answer attribute selects whether GPS provides an answer to this prompt or asks the user. If true, a <answer> child is required. Its value is the answer to be supplied by GPS. If false, a <question> child is required. Its value is used by GPS to ask the user a question. Provide this child once for every prompt that must be handled.

14.5.19.2. Defining a shell

GPS already defines several shells: sh, bash, csh, tcsh, and, on Windows, cmd.exe). You can add other shells by using the <remote_shell_config> tag which has one required attribute, name, denoting the name of the shell. This name need not be same as the command used to launch the shell.

The following child tags are defined:

  • <start_command> (require)

    Command used to launch the shell. Put any required arguments here, separated by spaces.

  • <generic_prompt> (optional)

    Regular expression used to identify a prompt after the initial connection. If not set, a default value is used.

  • <gps_prompt> (required)

    Regular expression used to identify a prompt after the initial setup is performed. If not set, a default value is used.

  • <filesystem> (required)

    Either unix or windows, representing the filesystem used by the shell.

  • <init_commands> (optional)

    Contains <cmd> children, each containing a command to initialize a new session.

  • <exit_commands> (optional)

    Like <init_commands>, but each <cmd> child contains a command to exit a session.

  • <no_echo_command> (optional)

    Command used to tell the remote shell to suppress echo.

  • <cd_command> (require)

    Command to change directories. %d is replaced by the directory’s full name.

  • <get_status_command> (required)

    Command used to retrieve the status of the last command launched.

  • <get_status_ptrn> (mandatory)

    Regular expression used to retrieve the status returned by <get_status_command>. You must include a single pair of parentheses; that subexpression identifies the status.

14.5.19.3. Configuring rsync usage

GPS includes native support for the rsync tool to synchronize paths during remote programming operations.

By default, GPS uses the –rsh=ssh option if ssh is the connection tool used for the server. It also uses the -L switch when transfering files to a Windows local host.

You can define additional arguments to rsync by using the <rsync_configuration> tag, which accepts <arguments> tags as children, each containing additional arguments to pass to rsync.

14.5.19.4. Defining a remote server

Users can define remote servers, as described in Setup the remote servers. Doing this creates a remote.xml file in the user’s gps directory, which can be installed in any plug-ins directory to set the values system-wide. The tag used in this file is <remote_machine_descriptor> for each remote server. You can also write this tag manually. Its attributes are:

  • nickname (required)

    Uniquely identifies the server.

  • network_name (required)

    Server’s network name or IP address.

  • remote_access (required)

    Name of the remote access tool used to access the server. These tools are defined in Defining a remote connection tool.

  • remote_shell (required)

    Name of the shell used to access the server. See Defining a shell.

  • remote_sync (required)

    Remote file synchronisation tool used to synchronize files between the local host and the server. Must be rsync.

  • debug_console (optional)

    Boolean that indicates whether GPS displays a debug console during the connection with a remote host. Default is false.

The optionally child tags for this tag are:

  • <extra_init_commands>

    Contains <cmd> children whose values are used to set server-specific initialization commands.

  • max_nb_connections

    Positive number representing the maximum number of simultaneous connections GPS is permitted to launch.

  • timeout

    Positive number representing a timeout value (in ms) for every action performed on the remote host.

14.5.19.5. Defining a remote path translation

The user can also define a remote path translation, as described in Setup the remote servers. Each remote paths translations corresponds to one <remote_path_config> tag, which has one required attribute, server_name, the server name that uses this path translation, and contains child <remote_path_config> tags, that have the following required attributes:

  • local_path

    Absolute local path, written using local filesystem syntax.

  • remote_path

    Absolute remote path, written using remote filesystem syntax.

  • sync

    Synchronization mechanism used for the paths (see Path settings). Must be one of NEVER, ONCE_TO_LOCAL, ONCE_TO_REMOTE, or ALWAYS.

14.5.20. Customizing Build Targets and Models

You can customize the information displayed in The Target Configuration Dialog and in the Mode selection via the XML configuration files.

14.5.20.1. Defining new Target Models

Define a model with a target-model tag, which has one attribute, name, containing the name of the model, and which supports the following child tags:

  • <icon> (required)

    Name of the stock icon associated by default with targets of this model. See Adding stock icons.

  • <description> (required)

    One-line description of what the model supports.

  • <server> (default Build Server)

    Server used for launching targets of this model. See Remote operations.

  • <is-run> (default False)

    Whether targets of this model correspond to the launching of an executable instead of performing a build. GPS launches such targets using an interactive console and does not parse their output for errors.

  • <uses-shell> (default False)

    Whether GPS should launch targets of this model with the shell pointed to by the SHELL environment variable.

  • <command-line> (required)

    Contains <arg> child tags, each containing an argument of the default command line for this model, beginning with the executable name.

  • <switches>

    Description of the switches. (See Defining tool switches):

    <?xml version="1.0" ?>
       <my_model>
       <target-model name="gprclean" category="">
          <description>Clean compilation artefacts with gprclean</description>
          <command-line>
             <arg>gprclean</arg>
             <arg>-P%PP</arg>
             <arg>%X</arg>
          </command-line>
          <icon>gps-clean</icon>
          <switches command="%(tool_name)s" columns="1">
             <check label="Clean recursively" switch="-r"
                    tip="Clean all projects recursively" />
          </switches>
       </target-model>
    </my_model>
    

14.5.20.2. Defining new Targets

Define targets with a <target> tag, which has three attributes:

  • name

    Name of the target. It must be a unique name. Underscores are interpreted as menu mnemonics. If you want an actual underscore, use a double underscore.

  • category

    Category containing the target for purposes of ordering the tree in the Target Configuration Dialog and Build menus. Underscores are interpreted as menu mnemonics. If you want an actual underscore, use a double underscore. If the string begins and ends with an underscore, GPS places the menu for the target in the toplevel Build menu.

  • messages_category

    Name of category to organize messages in the Locations view.

  • model

    Name of the initial model that this target inherits.

This tag accepts the following child tags:

  • <icon>

    Name of the stock icon associated by default with targets of this model. See Adding stock icons.

  • <in-toolbar> (default False)

    Whether the target has an associated icon in the toolbar.

  • file:<in-menu> (default True)

    Whether the target has an associated entry in the Build menu.

  • <in-contextual-menus-for-projects> (default False)

    Whether the target has an associated entry in the contextual menu for projects.

  • <in-contextual-menus-for-files>

    Likewise, but for files.

  • <visible> (default True)

    Whether the target is initially visible in GPS.

  • <read-only> (default False)

    Whether the user can remove the target.

  • <target-type>

    If present, a string indicating whether the target represents a simple target (empty) or a family of targets. The name is a parameter passed to the compute_build_targets hook. If set to main, a new subtarget is created for each main source defined in the project.

  • <launch-mode> (default MANUALLY)

    How GPS should launch the target. Possible values are MANUALLY, MANUALLY_WITH_DIALOG, MANUALLY_WITH_NO_DIALOG, and ON_FILE_SAVE.

  • <server> (default Build_Server)

    Server used for launching Target. See Remote operations.

  • <command-line>

    Contains a number of <arg> nodes, each with an argument of the default command line for this target, beginnng with the name of the executable:

    <?xml version="1.0" ?>
    <my_target>
       <target model="gprclean" category="C_lean" name="Clean _All">
           <in-toolbar>TRUE</in-toolbar>
           <icon>gps-clean</icon>
           <launch-mode>MANUALLY_WITH_DIALOG</launch-mode>
           <read-only>TRUE</read-only>
           <command-line>
              <arg>%gprclean</arg>
              <arg>-r</arg>
              <arg>%eL</arg>
              <arg>-P%PP</arg>
              <arg>%X</arg>
           </command-line>
      </target>
    </my_target>
    
  • <output-parsers>

    Optional list of output filters. See Processing Target’s Output for details.

14.5.20.3. Processing Target’s Output

You can filter output produced by a target’s run by using custom code. The list of filters already provided by GPS is shown below. By default, each is executed during each run of a target.

  • output_chopper

    Breaks output stream to pieces. Each of the piece contains one or more line of output and an end of line.

  • utf_converter

    Converts the stream to UTF-8 encoding if output is not in UTF-8.

  • progress_parser

    Drives GPS’s progress bar by looking for progress messages in the output stream. It excludes such messages from the stream.

  • console_writer

    Populates the GPS console with output from the stream.

  • location_parser

    Looks for special patterns in output to extract messages associated with processed files and locations and sends such messages to Location view (see The Locations View).

  • text_splitter

    Splits output into separate lines to simplify further processing.

  • output_collector

    Aggregates output and associates it with the build target. As result, the output is available for scripting (see GPS.get_build_output()) after the build completes:

    text = GPS.get_build_output(<name of your target>)
    
  • elaboration_cycles

    Detects the gnatbind report about circles in elaboration dependencies and draws them in the Elaboration Circularities browser (see The Elaboration Circularities browser).

  • end_of_build

    Cleans up internal data after a build run.

See GPS.OutputParserWrapper for examples of writing custom filter.

14.5.20.4. Defining new Modes

Define modes with a <builder-mode> tag which has one attribute, name, containing the name of the model. It supports the following child tags:

  • <description>

    One-line description of what the mode does

  • <subdir>

    Optional base name of the subdirectory to create for this mode. GPS will subsitute the macro arguments %subdir in the <extra-args> tags with this value.

  • <supported-model>

    Name of a model supported by this mode. You can provide multiple tags, each corresponding to a supported model and optionally specify a filter attribute corresponding to the switches used for this mode. By default, all switches are considered. GPS passes the <extra-args> of the mode matching filter to commands of the supported models.

  • <extra-args>

    List of <arg> tags, each containing one extra argument to append to the command line when launching targets while this mode is active. Macros are supported in the <arg> nodes:

    <?xml version="1.0" ?>
    <my_mode>
     <builder-mode name="optimization">
      <description>Build with code optimization activated</description>
      <subdir>optimized_objects</subdir>
      <supported-model>builder</supported-model>
      <supported-model>gnatmake</supported-model>
      <supported-model filter="--subdirs=">gprclean</supported-model>
      <extra-args>
         <arg>--subdirs=%subdir</arg>
         <arg>-cargs</arg>
         <arg>-O2</arg>
      </extra-args>
     </builder-mode>
    </my_mode>
    

14.5.21. Customizing Toolchains

You can customize the list of toolchains and their values presented in the project editor (see The Project Wizard) with the XML configuration files. GPS’s default list is contained in toolchains.xml. You can add your own toolchain by providing an XML description with the following tags:

  • <toolchain_default>

    Default names for the different tools used by all toolchains. The final name used is toolchain_name-default_name.

  • <toolchain>

    Defines a toolchain, with an attribute, name, giving the name of the toolchain, which overrides the default values defined in <toolchain_default>.

Each of the above tags can have the following child tags:

  • <gnat_driver>

    GNAT driver to use.

  • <gnat_list>

    GNAT list tool to use.

  • <debugger>

    Debugger to use.

  • <cpp_filt>

    Reserved.

  • <compiler>

    Requires a lang attribute naming an language and defines the compiler to use to compile that language.

You can override (including by setting the value to null) any value in the <toolchain_default> tag by providing the same tag withing a toolchain tag.

14.6. Adding support for new tools

GPS has built-in support for many external tools. This list of tools is frequently enhanced, so if you are planning to use the external tool support in GPS, check the latest GPS version available.

You can use this feature to support additional tools (in particular, different compilers). You need to do following to successfully use a tool:

  • Specify its command line switches.
  • Pass it the appropriate arguments depending on the current context and on user input.
  • Spawn the tool.
  • Optionally parse its result and act accordingly.

Each of these is discussed below. In all cases most of the work can be done statically through XML customization files. These files have the same format as other XML customization files (Customizing through XML and Python files). Tool descriptions are found in <tool> tags, which accept the following attributes:

  • name (required)

    Name of the tool. This is purely descriptive and appears throughout the GPS interface whenever this tool is referenced, for example the tabs of the switch editor.

  • package (default ide)

    Which package is used in the project to store information about this tool, including its switches. You should use the default value unless you are using one of the predefined packages.

    See also Defining project attributes for more information on defining your own project attributes. Using the XML package, attribute, or index attributes of <tool> implicitly creates new project attributes as needed.

    If ide is specified, switches cannot be set for a specific file, but only at the project level. Support for file-specific switches currently requires modification of the GPS sources themselves.

  • attribute (default default_switches)

    Name of the attribute in the project used to store the switches for the tool.

  • index (default is the tool name)

    What index is used in the project. This is mostly for internal use by GPS and indicates which index of the project attribute GPS uses to store the switches for the tool.

  • override (default False)*

    Whether the tool definition can be redefined. If the tool is defined several times GPS will display a warning.

This tag supports the following child tags, each described in a separate section:

14.6.1. Defining supported languages

A tool supports one or more languages. If you do not specify any language, the tool applies to all languages and the switches editor page is displayed for all languages. If at least one language is specified, the switches editor page will only be displayed if that language is supported by the project.

Specify the languages that the tool supports using the <tool> tag:

<?xml version="1.0" ?>
<my_tool>
  <tool name="My Tool" >
    <language>Ada</language>
    <language>C</language>
  </tool>
</my_tool>

14.6.2. Defining the default command line

You can define the command line to be used for a tool when the user is using the default project and has not overridden the command line in the project. Do this with the <initial-cmd-line> tag, as a child of the <tool> tag. Its value is the command line to be passed to the tool. This command line is parsed in the usual manner and quotes are used to avoid splitting switches each time a space is encountered:

<?xml version="1.0" ?>
<my_tool>
  <tool name="My tool" >
     <initial-cmd-line>-a -b -c</initial-cmd-line>
  </tool>
</my_tool>

14.6.3. Defining tool switches

The user must be able to specify which switches are passed to the tool. If the tool is only called through custom menus, you can hardcode some or all of the switches. However, it is usually better to use the project properties editor so the user can specify project-specific switches.

This is what GPS does by default for Ada, C, and C++. Look at the GPS installation directory to see how the switches for these languages are defined in an XML file. These provide extended examples of the use of customization files.

The switches editor in the project properties editor provides a powerful interface to the command line, allowing the user to edit the command line both as text and through GUI widgets.

In customization files, the switches are declared with the <switches> tag, which must be a child of a <tool> tag as described above. Use this tag to produce the needed GUI widgets to allow a user to specify the desired switch value.

This tag accepts the following attributes:

  • lines (default 1), columns (default 1)

    Switches in the project properties editor are organized into boxes, each surrounded by a frame, optionally with a title. These attribute specify the number of rows or columns (respectively) of such frames.

  • separator

    Default character placed between a switch and its value, for example, = produces -a=1. Can can override this separately for each switch. If you want the separator to be a space, you must use the value &#32; instead of a blank since XML parser will normalize the latter to the empty string when reading the XML file.

  • use_scrolled_window (default False)

    Whether boxes of the project editor are placed into scrolled window. This is particularily useful if the number of displayed switches is large.

  • show_command_line (default True)

    If False, the command line is not displayed in the project properties editor. Use this, for example, if you only want users to edit the command line through the buttons and other widgets but not directly as text.

  • switch_char (Default -)

    Leading character of command line arguments that are considered to be switches. Arguments not starting with this character remain unmodified and do not have graphical widgets associated with them.

  • sections

    Spaceseparated list of switches delimiting a section (such as -bargs -cargs -largs). A section of switches is a set of switches that are grouped together and preceded by a particular switch. Sections are always placed at the end of the command line, after regular switches.

The <switches> tag can have any number of child tags, listed below. Repeat them multiple times if you need several check boxes. For consistency, most of these child tags accept the following attributes:

  • line (default 1), column (default 1)

    This indicates the row or column (respectively) of the frame to contain the switch. See the attributes of the same name above.

  • label (required)

    Label displayed in the graphical interface.

  • switch (required)

    Text put in the command line if the switch is selected. This text might be modified, see the description of <combo> and <spin> below. The value must not contain any spaces.

  • switch-off

    Defined in <check> tags, where it specified the switch used for deactivating the relevant feature. Use this for features that are enabled by default but can be disabled.

  • section

    Switch section delimiter (such as -cargs). See the sections attribute of the <switches> tag for more information.

  • tip

    Tooltip describing the switch more extensively. Tags accepting this attribute also accept a single child <tip> whose value contains the text to be displayed. The advantage of the latter is that text formatting is retained.

  • before (default false

    Whether the switch must always be inserted at the begining of the command line.

  • min (default 1), max (default 1)

    Only supported for <spin> tags. Specifies the minimum or maximum (respectively) value allowed for the switch.

  • default (default 1)

    Used for <check> and <spin> tags. See the description below.

  • noswitch, nodigit

    Only valid for <combo> tags and documented there.

  • value (required)

    Only valid for <combo-entry> tags and documented there.

  • separator

    Overrides the separator to use between the switch and its value. See the description of this attribute for <switches>.

Here are the valid children for <switches>:

  • <title>

    Accepts the line and column attributes and used to give a name to a specific frame. The value of the tag is the title. You need not specify a name.

    Use the line-span or column-span attribute to specify how many rows or columns (respectively) the frame should span. The default for both is 1. If is set to 0, the frame is hidden from the user. See, for example, the usage in the Ada or C switches editor.

  • <check>

    Creates a toggle button. When active, the text defined in the switch attribute is added to the command line. The switch can also be activated by default (the default attribute is on or true), in which case, deactivating the switch adds the value of switch-off to the command line.

    Accepts the line, column, label, switch, switch-off, section, default, before, and tip attributes, and you can specify an optional <tip> child.

  • <spin>

    Adds the contents of the switch attribute followed by the current numeric value of the widget to the command line. One usage is to indicate indentation length. If the current value of the widget is equal to the default attribute, nothing is added to the command line.

    This tag accepts the line, column, label, switch, section, tip, min, max, separator, and default attributes and you can specify an optional <tip> child.

  • <radio>

    Groups together any number of children, each of which is associated with its own switch, allowing only one of the children can be selected at any given time.

    This tag accepts the line, column , label, switch, section, before, and tip attributes. Specify an empty value for the switch attribute to indicate the default switch to use in this group of radio buttons. Each child must have the tag radio-entry or <tip>.

  • <field>

    Creates a text field, which can contain any text the user types and be editable by the user. This text is prefixed by the value of the switch attribute and the separator character. If the user does not enter any text in the field, nothing is added to the command line.

    You can specify an optional <tip> child tag. This tag accepts the line, column, label, switch, section, separator, before, and tip attributes, and the following additional attributes:

    • as-directory

      If true, an extra Browse button is displayed, allowing the user to easily select a directory.

    • as-file

      Like as-directory, but opens a dialog to select a file instead of a directory. If both attributes are true, GPS displays a file selector.

  • <combo>

    GPS inserts the text from the switch attribute, concatenated with the text of the value attribute for the currently selected entry, into the command line. If the value of the current entry is the same as that of the nodigit attribute, only the text of the switch attribute is inserted into the command line. (This is used, for example, to interpret the gcc switch -O as -O1.) If the value of the current entry is the same as that of the noswitch attribute, nothing is added to the command line.

    This tag accepts the line, column, label, switch, section, before, tip, noswitch, separator, and nodigit attributes and any number of combo-entry child tags, each of which accepts the label and value attribute. You can also include an optional <tip> child.

  • <popup>

    Displays a button that, when clicked, displays a dialog with some additional switches. This dialog, like the switches editor itself, is organized into lines and columns of frames, the number of which is provided by the lines and columns attributes.

    This tag accepts those attributes as well as the label attribute and any number of child <switch> tags.

  • <dependency>

    Describes a relationship between two switches. For example, when the Debug Information switch is selected for Make, we need to force it for the compiler as well.

    This tag supports the following additional attributes:

    • master-page, master-switch, master-section

      Define the switch that can force a specific setting for a slave switch. In our example, they have the values Make and -g. The switch referenced by these attributes must be of type <check> or <field>. If it is part of a section, you must also specify the master-section attribute. If the user selects the check button of the this switch, GPS forces the selection of the check button for the slave switch. Likewise, if user sets the field to any value, GPS sets the slave switch to that same value.

    • slave-page, slave-switch, :file:` slave-section`

      Likewise, but designates the slave switch. In our example, they have the values Ada and -g. The switch referenced by these attributes must be of type <check> or <field>.

    • master-status, slave-status

      Which state of the master switch forces which state of the slave switch. In our example, they both have the value on: when the user enables debug information for make, GPS also enables compiler debug information. However, if the user does not enable debug information for make, nothing is changed for the compiler debug information. If you specify off for master-status and the master switch is a field, GPS changes the status of the slave when the user does not specify any value in the master switch’s field.

  • <default-value-dependency>

    Describes a relationship between two switches, which is slightly different from the <dependency> tag. This relationsip only affects the default values. For example, when the -gnatwa switch is selected for the Ada compiler, other switches, such as -gnatwc and -gnatwd, are enabled by default. But the user can disable them by specifying, e,g., -gnatwC and -gnatwD.

    It supports the following additional attributes:

    • master-switch

      Switch that triggers the dependency. If that switch is present in the command line, GPS changes the default status of slave-switch.

    • slave-switch

      Switch whose default value depends on master-switch. This must be a switch already defined in a <switch> tag. The switch can match the switch or switch-off attributes. In the latter case, the slave-switch default value is disabled if the user specifies the master-switch.

  • <expansion>

    Describe how switches are grouped together on the command line to keep it shorter. It also defines aliases between switches.

    It is easier to explain the functioning of this tag with an example. Specifying the GNAT switch -gnatyy is equivalent to specifying -gnaty3abcefhiklmnprst. This is a style check switch with a number of default values. But it can also be decomposed it into several switches, such as -gnatya and -gnatyb. Knowing this, GPS can keep the command line length as short as possible, making it more readable.

    Specify the above details in the <expansion> tag, which supports two attributes: switch is mandatory and alias is optional. In our example, alias contains the text -gnatyabcefhiklmnprst.

    This tag works in two ways:

    • If you do not specify the alias attribute, the switch attribute requests GPS to group all switches starting with that prefix. For example, if you specify -gnatw as the value of the switch attribute, if the user selects both the -gnatwa and -gnatw.b switches, GPS merges them on the command line as -gnatwa.b.
    • If you specify the alias, GPS views the switch attribute as a shorter way of writting the switch. For example, if switch is -gnatyy and alias is “-gnaty3abcefhiklmnprst, then if the user types -gnatyy, it means the whole set of options.

    You can specify the same switch attribute can be used in multiple <expansion> tags nodes if you want to combine their behavior.

    For historical reasons, this tag supports <entry> child tags, but these are no longer used.

14.6.4. Executing external tools

Once the user specified the switches to use for the external tool, it can be spawned from a menu item or by pressing a key. Both cases are described in an XML customization file, as described previously, and both execute what GPS calls an action, a set of commands defined by an <action> tag.

14.6.4.1. Chaining commands

The <action> tag (see Defining Actions) executes one or more commands, either internal GPS commands (written in any of the scripting language supported by GPS) or external commands provided by executables found on the PATH.

You can hard-code the command line for each of these commands in the customization file or it can be the result of previous commands executed as part of the same action. As GPS executes each command from the action, it saves its output on a stack. If a command line contains the construct %1, %2, etc., these constructs are replaced respectively by the result the last command executed, the previous command, and so on. The replacement is done with the value returned by the command, not by any output it might have made to some of the consoles in GPS. Each time GPS executes a new command, it pushes the previous result on the stack, so that, for example, the value of %1 becomes the value of %2.

The result of the previous commands is substituted exactly as is. However, if the output is surrounded by quotes, GPS ignores them when a substitution is done, so you must put them back if needed. This is done because many scripting languages systematically protect their output with quotes (simple or double) and these quotes are often undesired when calling further external commands:

<?xml version="1.0" ?>
<quotes>
  <action name="test quotes">
    <shell lang="python">'-a -b -c'</shell>
    <external> echo with quotes: "%1"</external>
    <external> echo without quotes: %2</external>
  </action>
</quotes>

14.6.4.2. Saving open windows

Before launching the external tool, you may want to force GPS to save all open files. Do this using the same command GPS uses before starting a compilation, MDI.save_all, which takes one optional boolean argument specifiying whether GPS displays an interactive dialog for the user.

This command fails when the user presses cancel, so you can put it in its own <shell> command, as in:

<?xml version="1.0" ?>
<save_children>
  <action name="test save children">
    <shell>MDI.save_all 0</shell>
    <external>echo Run unless Cancel was pressed</external>
  </action>
</save_children>

14.6.4.3. Querying project switches

You can use GPS shell commands to query the default switches set by the user in the project file. These are get_tool_switches_as_string(), get_tool_switches_as_list(), or, more generally, get_attribute_as_string() and get_attribute_as_list(). The first two require a unique parameter, the name of the tool as specified in the <tool> tag. This name is case-sensitive. The last two commands are more general and can be used to query the status of any attribute in the project. See their description by typing the following in the GPS shell console window:

help Project.get_attribute_as_string
help Project.get_attribute_as_list

The following is a short example on how to query the switches for the tool Find from the project shown as Tool example. It first creates an object representing the current project, then passes this object as the first argument of the get_tool_switches_as_string() command. The last external command outputs these switches:

<?xml version="1.0" ?>
<find_switches>
  <action name="Get switches for Find">
    <shell>Project %p</shell>
    <shell>Project.get_tool_switches_as_string %1 Find </shell>
    <external>echo %1</external>
  </action>
</find_switches>

The following example shows how something similar can be done from Python, in a simpler manner. This function queries the Ada compiler switches for the current project and prints them in the Messages view:

<?xml version="1.0" ?>
<query_switches>
  <action name="Query compiler switches">
    <shell lang="python">GPS.Project("%p").get_attribute_as_list
      (package="compiler",
       attribute="default_switches",
       index="ada")</shell>
    <external>echo compiler switches= %1</external>
  </action>
</query_switches>

14.6.4.4. Querying switches interactively

You can also query the arguments for the tool by asking the user interactively. The scripting languages provides a number of solutions for these, which generally have their own native way to read input, possibly by creating a dialog. The simplest solution is to often use the predefined GPS commands:

  • yes_no_dialog

    This takes a single argument, a question to display, and presents two buttons to the user, Yes and No. The result of this function is the button the user selected, as a boolean value.

  • input_dialog

    This function is more general. It takes a minimum of two arguments. The first argument is a message describing what input is expected from the user. The second, third, and following arguments each correspond to an entry line in the dialog, each querying one specific value (as a string). The result of this function is a list of strings, each corresponding to these arguments.

    From the GPS shell, it is only convenient to query one value at a time, since it does not have support for lists and would return a concatenation of the values. However, this function is especially useful in other scripting languages.

The following is a short example that queries the name of a directory and a file name and displays each in the Messages view:

<?xml version="1.0" ?>
<query_file>
  <action name="query file and dir">
    <shell lang="python">list=GPS.MDI.input_dialog \\
      ("Please enter directory and file name", "Directory", "File")</shell>
    <shell lang="python">print ("Dir=" + list[0], "File=" + list[1])</shell>
    </shell>
  </action>
</query_file>

14.6.4.5. Redirecting the command output

By default, GPS sends the output of external commands to the Messages view. However, you can exercise finer control using the output attribute of the <external> and <shell> tags. You can also specify this attribute in the <action> tag, where it defines the default value for all <shell> and <external> tags.

This attribute is a string. Specifying an empty string (to override a specification in the <action> tag)` produces the default behavior. A value of none tells GPS to hide the output of the command as well as the text of the command itself and not show it to the user. If you specify any other value, GPS creates a new window with the title given by the attribute. If such a window already exists, it is cleared before any command in the chain is executed. The output of the command, as well as the text of the command itself, are sent to this new window:

<?xml version="1.0" ?>
<ls>
  <action name="ls current directory" output="default output" >
     <shell output="Current directory" >pwd</shell>
     <external output="Current directory contents" >/bin/ls</external>
  </action>
</ls>

14.6.4.6. Processing the tool output

Once the output of the tool has either been hidden or made visible to the user in one or more windows, you can do several additional things with this output, for further integration of the tool in GPS.

  • Parsing error messages

    External tools usually display error messages for the user that are associated with specific locations in specific files. For example, the GPS builder itself analyzes the output of make using this information.

    You can do this done for your own tools using the shell command Locations.parse, which takes several arguments so that you can specify your own regular expression to find the file name, line number and so on in the error message. By default, it is configured to work with error message of the forms:

    file:line: message
    file:line:column: message
    

    Please refer to the online help for this command to get more information (by typing help Locations.parse in the GPS Shell).

    Here is a short example showing how to run a make command and send the errors to the Locations view.

    For languages that support it, it is recommended that you quote the argument with triple quotes (see The GPS Shell), so that any special character such as newlines and quotes in the output of the tool are not specially interpreted by GPS. You should also leave a space at the end, in case the output itself ends with a quote:

    <?xml version="1.0" ?>
    <make>
      <action name="make example" >
         <external>make</external>
         <on-failure>
            <shell>Locations.parse """%1 """ make_example</shell>
         </on-failure>
      </action>
    </make>
    
  • Auto-correcting errors

    GPS supports automatically correcting errors for some of languages. You can get access to this auto-fixing feature through the Codefix.parse() shell command, which takes the same arguments as Locations.parse(). This automatically adds pixmaps to the relevant entries in the Locations view, so you should call Locations.parse() before calling this command.

    Errors can also be fixed automatically by calling the methods of the Codefix class. Several codefix sessions can be active at the same time, each of which is associated with a specific category. The list of currently active sessions can be retrieved through the Codefix.sessions() command.

    If support for Python is enabled, you can also manipulate those errors that can be fixed for a given session. To do so, first get a handle for that section, as shown in the example below. Then get the list of fixable errors through the errors() command.

    Each error is of the class CodefixError, which has one important method, fix(), allowing you to perform an automatic correction of that error. The list of possible fixes is retrieved through possible_fixes():

    print GPS.Codefix.sessions ()
    session = GPS.Codefix ("category")
    errors  = session.errors ()
    print errors [0].possible_fixes ()
    errors [0].fix ()
    

14.7. Customization examples

14.7.2. Tool example

This section provides an example of how you can define a new tool. This is only a short example, since Ada, C, and C++ support themselves are provided through such a file, available in the GPS installation.

This example adds support for the find Unix utility, with a few switches. All the switches are editable through the project properties editor. It also adds a new action and menu. The action associated with this menu gets the default switches from the currently selected project, and asks the user interactively for the name of the file to search:

<?xml version="1.0" ?>
<toolexample>
  <tool name="Find" >
    <switches columns="2" >
      <title column="1" >Filters</title>
      <title column="2" >Actions</title>

      <spin label="Modified less than n days ago" switch="-mtime-"
            min="0" max="365" default="0" />
      <check label="Follow symbolic links" switch="-follow" />

      <check label="Print matching files" switch="-print" column="2" />
    </switches>
  </tool>

  <action name="action find">
    <shell>Project %p</shell>
    <shell>Project.get_tool_switches_as_string %1 Find </shell>
    <shell>MDI.input_dialog "Name of file to search" Filename</shell>
    <external>find . -name %1 %2</external>
  </action>

  <Submenu>
    <Title>External</Title>
     <menu action="action find">
       <Title>Launch find</Title>
    </menu>
  </Submenu>
</toolexample>

14.8. Scripting GPS

14.8.1. Scripts

Scripts are small programs that interact with GPS and allow you to perform complex tasks repetitively and easily. GPS currently includes support for two scripting languages, although additional languages may be added in the future. These two languages are described in the following section.

Support for scripting is currently a “work in progress” in GPS. As a result, not many commands are currently exported by GPS, although their number is increasing daily. These commands are similar to what is available to those who extend GPS directly in Ada, but with major advantages: they do not require recompilation of the GPS core and can be tested and executed interactively. The goal of such scripts is to help automate processes such as builds and generation of graphs.

These languages all have a separate console associated with them, which you can open from the Tools menu. In each of these console, GPS displays a prompt, at which you can type interactive commands. These consoles provide completion of the command names through the tab key.

For example, in the GPS shell console you can start typing:

GPS> File

then press the tab key, which lists all functions whose name starts with File.

A similar feature is available in the Python console, also providing completion for all the standard Python commands and modules.

All the scripting languages share the same set of commands exported by GPS, because of an abstract interface defined in the GPS core. As a result, GPS modules do not have to be modified when new scripting languages are added.

You can execute scripts immediately upon startup of GPS by using the command line switch –load. Specifying the following command line:

gps --load=shell:mytest.gps

forces the GPS script mytest.gps to be executed immediately, before GPS starts responding to user’s requests. Do this if you want to preform some initializations of the environment. It can also be used as a command line interface to GPS, if your script’s last command is to exit GPS.

You can also specify in-line commands directly on the command line through –eval command line switch.

For example, if you want to analyze an entity in the entity browser from the command line, you would pass the following command switches:

gps --eval=shell:'Entity entity_name file_name; Entity.show %1'

See the section Customizing through XML and Python files on how to bind key shortcuts to shell commands.

14.8.2. Scripts and GPS actions

There is a strong relationship between GPS actions, as defined in the customization files (Defining Actions), and scripting languages. You can bind actions to menus and keys through the customization files or the Edit ‣ Key shortcuts dialog. These actions can execute any script command (see Defining Actions) using the <shell> XML tag.

But the opposite is also true. From a script, you can execute any action registered in GPS. For example, you can split windows or highlight lines in the editor when no equivalent shell function exists. You can use this to execute external commands if the scripting language does not support this easily. Such calls are made through a call to execute_action, as in the following example:

execute_action "Split horizontally"

GPS.execute_action (action="Split horizontally")

The list of actions known to GPS can be found through the Edit ‣ Key shortcuts dialog. Action names are case sensitive.

Some shell commands take subprograms as parameters. If you are using the GPS shell, you to pass the name of a GPS action. If you are using Python, you pass a subprogram. See Subprogram parameters.

14.8.3. The GPS Shell

The GPS shell is a very simple-minded, line-oriented language. It is accessible through the Shell window at the bottom of the GPS window and similar to a Unix shell or a command window on Windows systems.

Type help at the prompt to get the list of available commands, or help followed by the name of a command to get more information on that command.

The following example shows how to get some information on a source entity, and find all references to the entity in the application. It searches for the entity entity_name, which has at least one reference somewhere in the file file_name.adb. After the first command, GPS returns an identifier for this entity, which can be used for all commands that need an entity as a parameter, as is the case for the second command. When run, the second command automatically displays all matching references in the Locations view:

GPS> Entity my_entity file_name.adb
<Entity_0x09055790>
GPS> Entity.find_all_refs <Entity_0x09055790>

Since the GPS shell is very simple, it does not provide any reference counting for the result types. As a result, all the values returned by a command, such as <Entity_0x09055790> in the example above, are kept in memory.

The GPS shell provides the command clear_cache() which removes all such values from the memory. After you run this command, you can no longer use references obtained from previous commands: you must run these commands again to get a new reference.

You can reference the return value of the 9 previous commands by using %1 through %9 on the command line. The previous example could have been written as:

GPS> Entity my_entity file_name.adb
<Entity_0x09055790>
GPS> Entity.find_all_refs %1

These return values are also modified for internal commands sent by GPS, so you should only use this when you emit multiple commands at the same time and do not perform any other action in GPS. This is mostly useful when used for command-line scripts (see the descriptions of –eval and –load above) and for custom files (see Customizing through XML and Python files).

Arguments to commands can, but need not, be quoted. If they do not contain any space, double-quote or newline characters you need not quote them. Otherwise, you should surround them with double-quotes and protect any double-quotes in the argument by preceding it with a backslash.

Another way to quote a command is to use three double-quotes characters in a row. Any character loses its special meaning until the next set of three double-quote characters. This is useful if you do not know in advance the contents of the string you are quoting:

Locations.parse """%1 """ category_name

14.8.4. The Python Interpreter

Python is an interpreted object-oriented language, created by Guido Van Rossum. It is similar in its capabilities to languages such as Perl, Tcl or Lisp. This section is not a tutorial on python programming. See http://docs.python.org/ for documentation on the current version of python.

If Python support has been enabled, the Python shell is accessible through the Python window at the bottom of the GPS window. You can also display it by using the Tools ‣ Consoles ‣ Python menu. The full documentation on what GPS makes visible through Python is available from the Help ‣ Python extensions menu.

The same example as shown for the GPS shell follows, now using Python. As you notice, the name of the commands is similar, although they are not run exactly in the same way. Specifically, GPS uses the object-oriented aspects of Python to create classes and instances of these classes.

In the first line, a new instance of the class Entity is created through the create_entity() function. Various methods can then be applied to that instance, including find_all_refs(), which lists all references to that entity in the Locations view:

>>> e=GPS.Entity ("entity_name", GPS.File ("file_name.adb"))
>>> e.find_all_refs()

The screen representation of the classes exported by GPS to Python has been modified, so most GPS functions return an instance of a class but still display their output in a user-readable manner.

Python has extensive introspection capabilities. Continuing the previous example, you can find what class e is an instance of with the following command:

>>> help(e)
Help on instance of Entity:

<GPS.Entity instance>

You can also to find all attributes and methods that can be applied to e, as in the following example:

>>> dir (e)
['__doc__', '__gps_data__', '__module__', 'called_by', 'calls',
'find_all_refs']

The list of methods may vary depending on what modules were loaded in GPS, since each module can add its own methods to any class. In addition, the list of all existing modules and objects currently known in the interpreter can be found with the following command:

>>> dir ()
['GPS', 'GPSStdout', '__builtins__', '__doc__', '__name__', 'e', 'sys']

You can also load and execute python scripts with the execfile() command, as in the following example:

>>> execfile ("test.py")

Python supports named parameters. Most functions exported by GPS define names for their parameters, so you can use this Python feature to make your scripts more readable. (A notable exception are functions that allow a variable number of parameters.) Using named parameters, you can specify the parameters in any order you wish, e.g:

>>> e=GPS.Entity (name="foo", file=GPS.File("file.adb"))

14.8.5. Python modules

GPS automatically imports (with Python’s import command) all files with the extension .py found in the directory $HOME/.gps/plug-ins, the directory $prefix/share/gps/plug-ins or in the directories pointed to by GPS_CUSTOM_PATH on startup. These files are loaded only after all standard GPS modules have been loaded, as well as the custom files, and before the script file or batch commands specified on the command lines with the –eval or –load switches.

As a result, you can use the usual GPS functions exported to Python in these startup scripts. Likewise, the script run from the command line can use functions defined in the startup files.

Because GPS uses the import() command, functions defined in this modules are only accessible by prefixing their name by the name of the file in which they are defined. For example, if a file mystartup.py is copied to the startup directory and defines the function func(), the latter is accessible in GPS as mystartup.func().

Python’s own mechanism for loading files at startup (using environment variable PYTHONSTARTUP) is not suitable for use within the context of GPS. When Python is loaded by GPS, the GPS module itself is not yet available and thus any script that depends on that module will fail to load correctly. Instead, copy your script to one of the plug-in directories, as documented above.

If you are writing a set of Python scripts for other people to use, you need to provide the Python files themselves. This is a set of .py files, which the user should install in the plug-ins directory.

To make the Python functions accessible through GPS, you can:

  • Export the APIs directly through Python, under the form of Actions (the Action class), Menus (the Contextual and Menu classes) or toolbar buttons (the ToolButton and Toolbar classes).
  • Write an XML that creates a set of actions using the <action> tag (see Defining Actions and which is exported to the user. This allows him to either create menus to execute these commands or to bind them to special key shortcuts. The menus can be created directly in Python, with the GPS.Menu class. The same XML can be directly embedded in the Python file itself and executed through GPS.parse_xml.

The following example defines a Python command that inserts a line full of dashes (‘-‘) at the current cursor location. This command is associated with the key binding Ctrl-c n and can be distributed as a single Python file:

# This code can be stored in a file test.py in $HOME/.gps/plug-ins
from GPS import *

def add_dashes_line():
   Editor.replace_text (current_context().file().name(),
                        current_context().location().line(),
                        current_context().location().column(),
                        "--------------------------------", 0, 0)
GPS.parse_xml ("""
   <action name="dashes line">
      <shell lang="python">test.add_dashes_line()</shell>
      <context>Source editor</context>
   </action>
   <key action="dashes line">control-c n</key>
""")

Several complex examples are provided in the GPS distribution, in the directory examples/python. These are modules you might want to use, but more importantly that show how GPS can be extended from Python.

If your script does not do what you expect it to do, there are several ways to debug it. The easiest is probably to add some print statements. Since some output of the scripts is sometimes hidden by GPS (for example, for interactive commands), you might not see this output. In that case, you can reuse the tracing facility embedded in GPS itself. Modify the file $HOME/.gps/traces.cfg, and add the following line:

PYTHON.OUT=yes

This include the Python traces as part of the general traces available in the file $HOME/.gps/log. Note that this may slow down GPS if there is a lot of output to process.

14.8.6. Subprogram parameters

Some functions exported by GPS in the GPS shell or in Python expect a subprogram as a parameter.

This is handled in different ways depending on what language you are using:

  • GPS shell

    You cannot define new functions in the GPS shell. However, this concept is similar to the GPS actions (see Defining Actions), which allow you to execute a set of commands and launch external processes. A subprogram parameter in the GPS shell is a string, the name of the action to execute.

    For examle, the following code defines the action on_editing, which is called each time a new file is edited. The action is defined in the shell itself, although this could be more conveniently done in a separate customization file:

    parse_xml """<action name="on_editing">
                 <shell>echo "File edited"</shell></action>"""
    Hook "file_edited"
    Hook.add %1 "on_editing"
    
  • Python

    Python, of course, has its own notion of subprogram, and GPS is fully compatible with it. As a result, the syntax is much more natural than in the GPS shell. The following example has the same result as above:

    import GPS
    def on_editing(self, *arg):
        print "File edited"
    GPS.Hook("file_edited").add(on_editing)
    

    The situation is slightly more complex if you want to pass methods as arguments. Python has three notions of callable subprograms, detailed below. The following examples all create a combo box in the toolbar that calls a subprogram whenever its value is changed. The documentation for the combo box indicates that the callback in this case takes two parameters:

    • The instance of the combo
    • The current selection in the combo box

    The first parameter is the instance of the combo box associated with the toolbar widget and, as always in Python, you can store your own data in the instance, as shown in the examples below.

    here is the description of the various subprograms:

    • Global subprograms

      These are standard subprograms, found outside class definitions. there is no implicit parameter in this case. However, if you need to pass data to such a subprogram, you need to use global variables:

      import GPS
      
      my_var = "global data"
      
      def on_changed(combo, choice):
         global my_var
         print ("on_changed called: " +
             my_var + " " + combo.data + " " + choice)
      
      combo = GPS.Combo(
         "name", label="name", on_changed=on_changed)
      GPS.Toolbar().append (combo)
      combo.data = "My own data"
      
    • Unbound methods

      These are methods of a class. You do not specify, when you pass the method in parameter to the combo box, what instance should be passed as its first parameter. Therefore, there is also no extra parameter.

      However, whatever class the method is defined in, the first parameter is always an instance of the class documented in the GPS documentation (in this case a GPS.Combo instance), not an instance of the current class.

      In this first example, since we do not have access to the instance of MyClass, we also need to store the global data as a class component. This is a problem if multiple instances of the class can be created:

      import GPS
      class MyClass:
         my_var = "global data"
         def __init__(self):
            self.combo = GPS.Combo(
               "name", label="name", on_changed=MyClass.on_changed)
            GPS.Toolbar().append (self.combo)
            self.combo.data = "My own data"
      
         def on_changed(combo, choice):
            ## No direct access to the instance of MyClass.
            print ("on_changed called: " +
               MyClass.my_var + " " + combo.data + " " + choice)
      
      MyClass()
      

      As the example above illustrates, there is no direct access to MyClass when executing on_changed(). An easy workaround is the following, in which the global data is stored in the instance of MyClass and therefore be different for each instance of MyClass:

      import GPS
      class MyClass:
         def __init__(self):
            self.combo = GPS.Combo(
                "name", label="name", on_changed=MyClass.on_changed)
            GPS.Toolbar().append (self.combo)
            self.combo.data = "My own data"
            self.combo.myclass = self   ## Save the instance
            self.my_var = "global data"
      
         def on_changed(combo, choice):
            print ("on_changed called: " +
               combo.myclass.my_var + " " + combo.data + " " + choice)
      
      MyClass()
      
    • Bound methods

      The last example works as expected, but is not convenient to use. You can make it more convenient by using a bound method, which is a method for a specific instance of a class. Such a method always has an extra first parameter, set implicitly by Python or GPS, which is the instance of the class the method is defined in.

      Note the way we pass the method in parameter to append(), and the extra third argument to on_changed() in the example below:

      import GPS
      class MyClass:
         def __init__(self):
            self.combo = GPS.Combo(
               "name", label="name", on_changed=self.on_changed)
            GPS.Toolbar().append (self.combo)
            self.combo.data = "My own data"
            self.my_var = "global data"
      
         def on_changed(self, combo, choice):
            # self is the instance of MyClass specified in call to append()
            print ("on_changed called: " +
               self.my_var + " " + combo.data + " " + choice)
      
      MyClass()
      

      You may find it convenient to use the object-oriented approach when writing Python scripts. If, for example, you want to spawn an external process, GPS provides the GPS.Process class. When you create an instance, you specify a callback to be called when some input is made available by the process. Matching the above example, the code looks something like:

      class MyClass:
        def __init__(self):
           self.process = GPS.Process(
              "command_line", on_match=self.on_match)
      
        def on_match (self, process, matched, unmatched):
           print ("Process output: " + unmatched + matched + "\n")
      

      A more natural approach, rather than having a class with a process() field, is to directly extend the GPS.Process class, as in:

      class MyClass(GPS.Process):
        def __init__(self):
           GPS.Process.__init__(
              self, "command_line", on_match=self.on_match)
      
        def on_match (self, matched, unmatched):
           print ("Process output: " + unmatched + matched + "\n")
      

      Any command that can be used on a process (such as send()) can then directly be used on instances of MyClass.

      There is one non-obvious improvement possible in the code above: the on_match() callback has one less parameter. What happens is the following: as per the documentation of GPS.Process.__init__(), GPS gives three arguments to its on_match() callback: the instance of the process (process() in the first example above), the string that matched the regular expression, and the string before that match.

      In the first example above, we are passing self.on_match(), a bound method, as a callback. That tells Python it should automatically and transparently add an extra first parameter, self(), when calling MyClass.on_match(). This is why the first example has four parameters for on_match().

      However, the second example only has three parameters, because GPS detected that self() (the instance of MyClass) and the instance of GPS.Process() are the same in this case. So it need not ada an extra parameter (self() and process() would have been the same).

14.8.7. Python FAQ

This section lists some problems that have been encountered while using Python inside GPS. This is not a general Python discussion.

14.8.7.1. Hello World! in python

Writing a Python script to interact with GPS is very simple. Here we show how to create a new menu in GPS that when clicked, diplays a dialog saying the famous ‘Hello World!’.

Here is the code that you need to put in hello_world.py:

import GPS

def hello_world (self):
   GPS.MDI.dialog ("Hello World!")

GPS.Menu.create ("/Help/Hello World!", on_activate=hello_world)

To use this plug-in, launch GPS with the following command line:

$ gps --load=python:hello_world.py

If want the plug-in to be loaded every time you launch GPS without having to specify it on the command line, copy hello_world.py to your $HOME/.gps/plug-ins/ directory (%USERPROFILE%\.gps\ on Windows). Alternatively, you can add the directory containing your plug-in to your GPS_CUSTOM_PATH environment variable. For a description of the various environment variables used by GPS, see Environment Variables.

14.8.7.2. Spawning external processes

There are various mechanisms to spawn external processes from a script:

  • Use the functionalities provided by the GPS.Process class.

  • Execute a GPS action through GPS.execute_action().

    The action should have an <external> XML node indicating how to launch the process.

  • Create a pipe and execute the process with os.popen() calls.

    This solution does not provide a full interaction with the process.

  • Use a standard expect library in Python

    The use of an expect library may be a good solution. There are various Python expect libraries that already exist.

    These libraries generally try to copy the parameters of the standard file class. They may fail doing so, since GPS’s consoles do not fully emulate all the primitive functions of that class (there is no file descriptor, for example).

    When possible, we recommend using one of the methods above instead.

14.8.7.3. Redirecting the output of spawned processes

In general, you can redirect the output of any Python script to any GPS window (either an already existing one or one GPS creates automatically) using the output attribute of XML configuration files.

However, there is a limitation in Python that the output of processes spawned through os.exec() or os.spawn() is redirected to the standard output instead of the usual Python output that GPS has overriden.

There are two solutions for this:

  • Execute the external process in through a pipe

    The output of the pipe is then redirected to Python’s output, as in:

    import os, sys
    def my_external():
       f = os.popen ('ls')
       console = GPS.Console ("ls")
       for l in f.readlines():
          console.write ('   ' + l)
    

    This solution allows you, at the same time, to modify the output, for example to indent it as in the example above.

  • Execute the process through GPS

    You can go through the process of defining an XML customization string for GPS and execute your process that way, like:

    GPS.parse_xml ("""
       <action name="ls">
         <external output="output of ls">ls</external>
       </action>""")
    
    def my_external():
       GPS.execute_action ("ls")
    

    This solution also allows you to send the output to a different window than the rest of your script. But you cannot filter or modify the output as you can using the first solution.

14.8.7.4. Contextual menus on object directories only

The following filter can be used for actions that can only execute in the Project view and only when the user clicks on an object directory. The contextual menu entry is not visible in other contexts:

<?xml version="1.0" ?>
<root>
   <filter name="object directory"
           shell_cmd="import os.path; os.path.samefile (GPS.current_context().project().object_dirs()[0],GPS.current_context().directory())"
           shell_lang="python"
           module="Explorer" />

   <action name="Test on object directory">
      <filter id="object directory" />
      <shell>echo "Success"</shell>
   </action>

   <contextual action="Test on object directory" >
      <Title>Test on object directory</Title>
   </contextual>
</root>

Another example is a filter so that the contextual menu only appears when on a project node in the Project view. Using %P in your command is not enough since the current context when you click on a file or directory also contains information about the project the file or directory belongs to. Thus this implicit filter is not sufficient to hide your contextual menu.

As a result, you need to do a slightly more complex test, where you check that the current context does not contains information on directories (which will disable the contextual menu for directories, files and entities). Since the command uses %P, GPS guarantees that a project is available.

We will implement this contextual menu in a Python file, called filters.py:

import GPS
def on_project():
   try:
      GPS.current_context().directory()
      return False
   except:
      return True

GPS.parse_xml ("""
<action name="test_filter">
<filter module="Explorer"
     shell_lang="python"
     shell_cmd="filters.on_project()" />
<shell>echo current project is %P</shell>
</action>
<contextual action="test_filter">
<title>Print current project</title>
</contextual>""")

The example above shows the flexibility of filters since you can pretty much do anything you wish through the shell commands. However, it is complex to write the above for such a simple filter. GPS provides a predefined filter for just that purpose, so you can write instead, in an XML file:

<action name="test_filter" >
<filter id="Explorer_Project_Node" />
<shell>echo current project is %P</shell>
</action>

14.8.7.5. Redirecting the output to specific windows

By default, GPS displays the output of all Python commands in the Python console. However, you might, in some cases, want to create other windows in GPS for this output. This can be done in one of two ways:

  • Define a new action

    If the entire output of your script should be redirected to the same window or if the script is used interactively through a menu or a key binding, the easiest way is to create a new XML action and redirect its output, as in:

    <?xml version="1.0" ?>
    <root>
      <action name="redirect output" output="New Window">
         <shell lang="python">print "a"</shell>
      </action>
    </root>
    

    All the shell commands in your action can be output in a different window and this also applies for the output of external commands.

  • Explicit redirection

    If, however, you want to control within your script where the output should be sent (for example if you cannot know that statically when you write your commands), you can use the following code:

    sys.stdin = sys.stdout = GPS.Console ("New window")
    print "foo"
    print (sys.stdin.read ())
    sys.stdin = sys.stdout = GPS.Console ("Python")
    

    The first line redirects all input and output to a new window, which is created if it does not yet exist. Note however that the output of stderr() is not redirected: you need to explicitely do it for sys.stderr().

    The last line restore the default Python console. You must do this at the end of your script or all scripts will continue to use the new console.

    You can alternatively create separate objects for the output and use them explictly:

    my_out  = GPS.Console ("New Window")
    my_out2 = GPS.Console ("New Window2")
    
    sys.stdout=my_out
    print "a"
    sys.stdout=my_out2
    print "b"
    sys.stdout=GPS.Console ("Python")
    

    The parameter to the constructor GPS.Console() indicates whether any output sent to that console should be saved by GPS and reused for the %N parameters if the command is executed in a GPS action. It should normally be 1, except for stderr() when it should be 0.

14.8.7.6. Reloading a Python file in GPS

After you have made modification to a Python file, you may want to reload it. This requires careful use of Python commands. Let’s assume you have a Python file ("mymod.py") containing the following:

GPS.parse_xml ("""
   <action name="my_action">
      <shell lang="python">mymod.myfunc()</shell>
   </action>""")

def myfunc():
   print "In myfunc\\n"

This file defines an action my_action, that you can, for example, associate with a keybinding through the Edit ‣ Key shortcuts menu.

If you copy this file into one of the plug-ins directories, GPS automatically loads it at startup. The function myfunc() is in a separate namespace, with the name mymod, like the file. If you decide, during your GPS session, to edit this file, for exampl to have the function print “In myfunc2” instead, you then to reload the file by typing the following command in the Python console:

> execfile ("HOME/.gps/plug-ins/mymod.py", mymod.__dict__)

The first parameter is the full path to the file that you want to reload. The second argument is less obvious, but indicates the file should be reloaded in the namespace mymod.

If you omit the optional second parameter, Python loads the file, but the function myfunc() is defined in the global namespace, so the new definition is accessible through:

> myfunc()

Therefore, the key shortcut you previously set, which still execute mymod.myfunc(), will keep executing the old definition.

GPS provides a contextual menu, Python ‣ Reload module when you are editing a Python file to deal with all the above details.

14.8.7.7. Printing the GPS Python documentation

The Python extension provided by GPS is fully documented in this manual and in a separate manual accessible through the Help menu in GPS. However, this documentation is provided in HTML, and might not be the best format suitable for printing. To generate your own documentation for any Python module, including GPS, and print the result:

import pydoc
pydoc.writedoc (GPS)

In the last comamnd, “GPS” is the name of the module whose documentation you want to print.

These commands generate a .html file in the current directory.

Alternatively, you can generate a simple text file with:

e=file("./python_doc", "w")
e.write (pydoc.text.document (GPS))
e.flush()

This text file includes bold characters by default. Such bold characters are correctly interpreted by tools such as a2ps which you can can use to convert the text file into a Postscript document.

14.8.7.8. Automatically loading python files at startup

At startup, GPS automatically loads all Python files found in the share/gps/plug-ins and $HOME/.gps/plug-ins directories. In addition, Python files located under <prefix>/share/gps/python can be imported (using the import command) by any Python script. You can also set the PYTHONPATH environment variable to add other directories to the Python search path.

14.8.7.9. Hiding contextual menus

GPS provides access to most of its functionality through contextual menus, accessed by right clicking in various parts of GPS. Due to the number of tools provided by GPS, these contextual menus can be large and you might want to control what is displayed in them. There are several ways to do that:

  • Define appropriate filters for your actions.

    If you are creating your own contextual menus through customization files and XML, they are are usually associated with actions (<action>) you have created. In that case, you need to define filters appropriately, through the <filter> tag to decide when the action is relevant and hence when the contextual menu is displayed.

  • Use shell commands to hide the menus

    If you want to control the visibility of predefined contextual menus or for menus where you cannot easily modify the associated filter, you can use shell and Python commands to hide the menu entry. To do this, you need to find the name of the menu, which can be done by consulting the list returned by GPS.Contextual.list(). This name is also the value of the <title> tag for contextual menus you have created. Using this name, you can disable the contextual menu by executing:

    GPS.Contextual ("name").hide()
    

    in the Python console.

14.8.7.10. Creating custom graphical interfaces

GPS is based on the Gtk+ graphical toolkit, which is available under many platforms and for many programming languages.

In particular, GPS comes with pygobject, a Python binding to Gtk+. Using pygobject, you can create your own dialogs and graphical windows using the Python capabilities provided by GPS.

See the Help ‣ Python Extensions menu, specifically the documentation for GPS.MDI, for a sample of code on how to create your own graphical interfaces and integrate them with GPS.

14.8.8. Hooks

A hook is a named set of commands to be executed on particular occasions as a result of user actions in GPS.

GPS and its various modules define a number of standard hooks, called, for example, when a new project is loaded, or when a file is edited. You can define your own commands to be executed in such cases.

You can find the list of hooks that GPS currently supports by calling the Hook.list() function, which takes no argument and returns a list of the names of all hooks. You can get more advanced description for each hook using the Help ‣ Python Extensions menu:

GPS> Hook.list
project_changed
open_file_action_hook
preferences_changed
[...]

Python> GPS.Hook.list()

The description of each hook includes a pointer to the type of the hook, which is what parameters the subprograms in this hook receive.

You can find the list of all known hook types can be found using the Hook.list_types() function, which takes no argument and returns a list of all known types of hooks. You can find more information for each of these type by calling Hook.describe_type().

14.8.8.1. Adding commands to hooks

Add your own command to existing hooks by calling the Hook.add() function. Whenever the hook is executed by GPS or another script, your command is also executed and is passed the parameters that were specified when the hook is run. The first parameter is always the name of the hook being executed.

This function applies to an instance of the hook class and takes one parameter, the command to be executed. This is a subprogram parameter (see Subprogram parameters).

  • GPS shell

    The command can be any GPS action (see Defining Actions). The arguments for the hook will be passed to the action, and are available as %N. In the following example, the message “Just executed the hook: project_changed” is printed in the Shell console. We are defining the action to be executed inline, but it could be defined in a separate XML customization file:

    GPS> parse_xml """<action name="my_action"><shell>echo "Just executed the hook"</shell></action_name>"""
    GPS> Hook project_changed
    GPS> Hook.add %1 "my_action"
    
  • Python

    The command must be a subprogram to execute. The arguments for the hook are passed to this subprogram. In the following example, the message “The hook project_changed was executed by GPS” is displayed in the Python console whenever the project changes:

    def my_callback (name):
        print "The hook " + name + " was executed by GPS"
    GPS.Hook ("project_changed").add (my_callback)
    

The example above illustrates the simplest type of hook, which does not have any arguments. However, most hooks receive several parameters. For example, the file_edited() hook receives the file name as a parameter.

  • GPS shell

    The following code prints the name of the hook (“file_edited”) and the name of the file in the shell console each time a file is openen in GPS:

    GPS> parse_xml """<action name="my_action"><shell>echo name=$1 file=$2</shell></action>"""
    GPS> Hook "file_edited"
    GPS> Hook.add %1 "my_action"
    
  • Python

    The following code prints the name of the file being edited by GPS in the Python console whenever a new file is opened. The second argument is of type GPS.File:

    def my_file_callback (name, file):
        print "Editing " + file.name()
    GPS.Hook ("file_edited").add (my_file_callback)
    

14.8.8.2. Action hooks

Hooks whose name ends with _action_hook are handled specially by GPS. As opposed to the standard hooks described in the previous section, the execution of the action hooks stops if one of the subprograms returns a True value (1 or true). The subprograms associated with that hook are executed sequentially. If any such subprogram knows how to do the the action for that hook, it should do so and return “1”.

Other action hooks expect a string as a return value instead of a boolean. Execution stops when a subprogram returns a non-empty string.

This mechanism is used extensively by GPS internally. For example, whenever a file needs to be opened in an editor, GPS executes the open_file_action_hook(). Several modules are connected to that hook.

One of the first modules to be executed is the external editor module. If the user has chosen to use an external editor, this module spawn the editor and returns 1. This immediately stops the execution of the open_file_action_hook().

However, if user is not using an external editor, this module returns 0, which keep executing the hook, and in particular executes the source editor module, which always takes an actions and open an editor internally in GPS.

This is a very flexible mechanism. In your own script, you could choose to have some special handling for files with a .foo extension, for example. If the user wants to open such a file, you could, for example, spawn an external command (say, my_editor) to edit this file, instead of opening it in GPS.

You can do this with code similar to the following:

from os.path import *
import os
def my_foo_handler(name, file, line, column,
                   column_end, enable_nav, new_file, reload):
    if splitext(file.name())[1] == ".foo":
        os.spawnv(
           os.P_NOWAIT, "/usr/bin/emacs", ("emacs", file.name()))
        return 1   ## Prevent further execution of the hook
    return 0  ## Let other subprograms in the hook do their job

GPS.Hook("open_file_action_hook").add(my_foo_handler)

14.8.8.3. Running hooks

Each module in GPS is responsible for running hooks when appropriate. Most of the time the subprograms exported by GPS to the scripting languages properly run the hook. But you might also need to run them in your own scripts.

As usual, this results in the execution of all the functions bound to that hook, whether they are defined in Ada or in any of the scripting languages.

This is done by the Hook.run() function. It applies to an instance of the Hook class and has a variable number of arguments, which must be in the right order and of the right type for that specific type of hook. If you are running an action hook, the execution stops as usual as soon as one of the subprograms return a True value.

The following example shows how to run a simple hook with no parameter and a more complex hook with several parameters. The latter requests the opening of an editor for the file in GPS and has an immediately visible effect on the interface. The file is opened at line 100. See the description of the hook for more information on the other parameters:

GPS.Hook ("project_changed").run()
GPS.Hook ("open_file_action_hook").run(
   GPS.File ("test.adb"), 100, 1, 0, 1, 1, 1)

14.8.8.4. Creating new hooks

The list of hooks known to GPS is fully dynamic. GPS itself declares a number of hooks, mostly for its internal use, though you can also connect to them. But you can also create your own hooks to report events happening in your own modules and programs. In this way, any other script or GPS module can react to these events.

Such hooks can either be of a type exported by GPS, which constraints the list of parameters for the callbacks, but make such hooks more portable and secure, or they can be of a general type, which allows almost any kind of parameters. In the latter case, GPS checks at runtime to ensure that the subprogram called as a result of running the hook has the right number of parameters. If this is not the case, GPS complains and displays error messages. Such general hooks do not pass their parameters to other scripting languages.

You create a new hook by calling Hook.register(). This function takes two arguments: the name of the hook you are creating and the type of the hook. The name of the hook is left to you. Any character is allowed in that name, although using only alphanumerical characters is recommended.

The type of the hook must be one of the following:

  • the empty string

    Indicates that the hook does not take any argument. None should be passed to Hook.run() and none should be expected by the various commands connected to that hook, other than the hook name itself.

  • general

    Indicates that the hook is of the general type that allows any number of parameter, of any type. Other scripts are able to connect to it but will not be executed when the hook is run if they do not expect the same number of parameters passed to Hook.run(). Other scripts in other languages only receive the hook name as a parameter, not the full list of parameters.

  • one of the values returned by Hook.list_types()

    Indicates that the hook is of one of the types exported by GPS itself. The advantage of using such explicit types instead of general is that GPS is able to do more testing of the validity of the parameters. Such hooks can also be connected to from other scripting languages.

A small trick worth noting: if the command bound to a hook does not have the correct number of parameters that this hook provides, the command will not be executed and GPS reports an error. You can make sure that your command is always executed by either giving default values for its parameter or by using Python’s syntax to indicate a variable number of arguments.

This is especially useful if you are connecting to a general hook, since you do not know in advance how many parameters the call of Hook.run() provides:

## This callback can be connected to any type of hook
def trace (name, *args):
   print "hook=" + name

## This callback can be connected to hooks with one or two parameters
def trace2 (name, arg1, arg2=100):
   print "hook=" + str (arg1) + str (arg2)

Hook.register ("my_custom_hook", "general")
Hook ("my_custom_hook").add (trace2)
Hook ("my_custom_hook").run (1, 2) ## Prints 1 2
Hook ("my_custom_hook").run (1)    ## Prints 1 100

14.9. Adding support for a new Version Control System

14.9.1. Custom VCS interface

You can customize the Version Control interface in GPS, either to refine the behavior of the existing system and adapt it to your specific needs or to add support for other Version Control systems.

Custom VCS interfaces are defined through XML files and Python plugins. Those files are read in the same location as all the other XML and Python customizations that GPS offers. See Customizing through XML and Python files for a complete description.

To create a custom VCS interface you must first describe the VCS itself, then implement actions corresponding to all the operations the VCS can perform, and finally define the layout of the menus. The following three sections (Describing a VCS, Implementing VCS actions, and Implementing VCS menus) describe those steps.

GPS is distributed with XML and Python files describing the interfaces to ClearCase, CVS, Subversion, and Git and experimental support for Mercurial. These files are located in the directory share/gps/plug-ins in the GPS installation. You can use them as a reference for implementing custom VCS interfaces.

14.9.2. Describing a VCS

14.9.2.1. The VCS node

The <vcs> tag is the toplevel tag containing the description of the general behavior expected from the VCS. It has the following attributes:

  • name

    Identifier of the VCS. The casing of this name is significant: the same casing must be used in project files.

  • absolute_names

    If True, all commands in the VCS work on absolute filenames. If FALSE, all actions work on base filenames and GPS must switch to the appropriate directory before executing an action.

  • group_queries_by_directory

    Whether, when querying status for all the source files in a directory, GPS should launch a query for the directory instead of launching a query for multiple files. The default is FALSE.

  • ignore_file

    Name of the file used by the VCS Explorer to obtain the list of files to ignore. For CVS, the default is .cvsignore.

  • atomic_commands

    Whether the VCS supports atomicity. If TRUE, the VCS supports atomic commands. The default is FALSE by default. This attribute triggers the activities group commit feature. See VCS Activities.

  • path_style

    Which kind of directory separator is supported by the VCS, one of UNIX, DOS, Cygwin or System_Default. The later value is the default value. Use this attribute to control the directory separator used when specifying files to the VCS. If Cygwin, the drive is specified as /cygdrive/<drive>.

  • dir_sep

    Alias for path_style, obsolescent.

  • commit_directory

    Whether the VCS supports commits on directories. If TRUE, the VCS supports commit on directories (like Subversion).

  • administrative_directory

    Name of the directory where the external VCS stores the local repository information. For example, this is .svn for Subversion. This information is used when the project is set up so that GPS can automatically select the external VCS. See Version Control System.

  • prev_revision, head_revision

    String used when querying revisions to indicate the previous or head (respectively) revision of a file. For example, PREV and HEAD for Subversion.

  • require_log

    Whether the VCS require a log for commit, add, and delete actions. If TRUE, GPS ensures that a log is created for each file. If FALSE, GPS does not ask for log, but expects the external VCS to do so.

To support group commit with shared log, both absolute_name and atomic_commands must be true. This is the case for the Subversion VCS, for example.

Here is an example, adapted to the use of CVS:

<vcs name="Custom CVS" absolute_names="FALSE">

   (... description of action associations ...)
   (... description of supported status ...)
   (... description of output parsers ...)

</vcs>

14.9.2.2. Associating actions with operations

GPS knows about a set of predefined ‘operations’ that a VCS can perform. When adding support for a VCS, you can decide to implement some, but not necessarily all of them. This section describes how.

Each predefined action described in Implementing VCS actions has a tag of the same name, with the following attributes:

  • action

    Name of the action to launched when GPS ask the VCS to perform the operation.

  • label

    Name that appears in the GPS menus when working on a file under the control of the defined VCS.

14.9.2.3. Defining revision information

Some VCS’s have revisions number that can be used to find the related branch. This is the case in CVS, for example, where a revision number for a branch uses as prefix the branch point revision number. For such VCS, you can specify two regular expressions as the regexp attribute of one of the <parent_revision> and <branch_root_revision> tags, which, when passed the revision number, have subexpressins that match the parent revision and the branch root, respectively. For example, in CVS, with a revision number of 1.2.4.5, the regular expressionin <parent_revision> should match 1.2 and that in <branch_root_revision> should match 1.2.4.

14.9.2.4. Defining status

All VCS have the notion of ‘status’ or ‘state’ to describe the relationship between the local file and the repository. Use the XML tag <status> to describe the statuses supported by a custom VCS and the icon associated with each. This tag supports two attributes:

  • label

    Name of the status, for example Up to date or Needs update for CVS.

  • stock

    Stock identifier of the icon associated to this status used to denote the status in the VCS Explorer. See Adding stock icons for details on defining stock icons.

The order in which status are defined in the XML file is significant: the first status listed displayed must correspond to the equivalent of the Up-to-date status.

14.9.2.5. Output parsers

GPS needs to parse the output of VCS commands when querying the status or annotating a file. You specify how to parse the results by specifying a set of regular expressions as child tags within the <vcs> tag. node.

  • <status_parser>, <local_status_parser>, and <update_parser>

    Used by the function VCS.status_parse to parse a string for the status of files controlled by a VCS.

    They each accept the following child tags:

    • <regexp> (required)

      Regular expression to match against.

    • <file_index>

      Index of a parenthesized subexpression that matches the filename. name of a file.

    • <status_index>

      Index of a parenthesized expression that matches the status, which status is passed to the regular expressions defined in the <status_matcher> tags described below.

    • <local_revision_index>

      Index of a parenthesized expression that matches the name of the local revision (the version of the file that was checked out).

    • <repository_revision_index>

      Index of a parenthesized expression that matches the name of the repository revision (the latest version of the file in the VCS).

    • <status_matcher>

      Regular expression which, when matching an expressions indicates that the status is that given in the label attribute of this tag.

  • <annotations_parser>

    Used by the function VCS.annotations_parse to parse a line of for annotations in a file controlled by a VCS.

    It accepts the following child tags:

    • <regexp> (required)

      Regular expression to match against.

    • <repository_revision_index> (required)

      Index of a parenthesized expression that matches the repository revision of the line.

    • <author_index>

      Index of a parenthesized expression that matches the author of the line.

    • <date_index>

      Index of a parenthesized expression that matches the date of the line.

    • <file_index>

      Index of a parenthesized expression that matches the part of the line that belongs to the file (e.g., the actual line text).

    • <tooltip_pattern>

      Template pattern used to format the tooltip information. It can contain text and reference parenthesized expressions using \n (where n represents the nth expression in the value of <regexp>)).

  • <log_parser>

    Used by the function VCS.log_parse to parse the log for revision histories in a file controlled by a VCS.

    It accepts the following child tags:

    • <regexp> (required)

      Regular expression to match against.

    • <repository_revision_index> (required)

      Index of a parenthesized expression that matches the repository revision.

    • <author_index>

      Index of a parenthesized expression that matches the author.

    • <date_index>

      Index of a parenthesized expression that matches the date.

    • <log_index>

      Index of a parenthesized expression that matches the revision text.

  • <revision_parser>

    Used by the function VCS.revision_parse to parse a string for revision tags and branches in a file controlled by a VCS.

    It accepts the following child tags, all of which are required:

    • <regexp>

      Regular expression to match against.

    • <sym_index>

      Index of a parenthesized expression that matches the tags or branches symbolic name of the revision.

    • <repository_revision_index>

      Index of a parenthesized expression that matches the repository revision number of the revision.

14.9.3. Implementing VCS actions

GPS defines standard VCS operations, each of which can be implemented using Actions (see Defining Actions). Here is a list of all the defined VCS operations and their parameters:

  • status_files

    Query the status of a list of files. This performs a complete VCS query and returns as complete results as possible.

    • $1 = whether the log files should be cleared when obtaining up-to-date status
    • $2- = the list of files to query status for.
  • status_dir

    Likewise, but queries all files in one directory.

    • $1 = the directory.
  • status_dir_recursive

    Likewise, but queries all the files in one directory and all subdirectories, recursively.

    • $1 = the directory.
  • local_status_files

    Query the local status for specified files. This query should be as fast as possible and avoid connecting to any remote VCS. The results need not be complete, but you should not implement this command if the output does not at least contain the working revision.

    • $* = list of files
  • open

    Open files or directories for editing. Implement this command for any VCS that require an explicit check-out, open, or edit action before being able to edit a file.

    • $* = list of files
  • update

    Bring the specified files up to date with the latest repository revision.

    • $* = list of files
  • resolved

    Mark files’ merge conflics as resolved. Some version control systems (such as Subversion) block any commit until this action is called.

    • $* = list of files
  • commit

    Commit, submit, or check-in files or directories with the provided log. The log is passed in a file.

    • $1 = log file
    • $2- = list of files
  • commit_dir

    Likewise, but for all the files in a directory.

    • $1 = log
    • $2 = directory
  • history_text

    Query the complete log history for the specified file. The result is expected to be placed into an editor as plain text.

    • $1 = file
  • history

    Likewise, but the result is expected to be placed into a Revision view.

    • $1 = file
  • history_revision

    Query the history for the corresponding revision of the specified file.

    • $1 = revision
    • $2 = file
  • annotate

    Query the annotations for a file.

    • $1 = file
  • add

    Add files and/or direcories to the repository, with the provided revision log. The added files and directories are commited.

    • $1 = log
    • $2- = list of files and/or directories
  • add_no_commit

    Likewise, but do not comment any added files or directories.

    • $1 = log
    • $2- = list of files or dirs
  • remove

    Remove the file or directory from the repository, with the provided revision log.

    • $1 = log
    • $2 = file or directory
  • remove_no_commit

    Likewise, but do not commit the removal.

    • $1 = log
    • $2 = file or directory
  • revert

    Revert the local file to the repository revision, cancelling all local changes, and close the file for editing if it was open.

    • $* = files
  • diff_patch

    Create a textual diff for the given file. This command is used to build the activity patch file.

    • $1 = file
  • diff_head

    Display a visual comparison between the local file and the latest repository revision. The diff command must provide a normal diff as opposed to context or unified ones.

    • $1 = file
  • diff_base_head

    Likewise, but compare the revision from which the file has been checked-out with the latest repository revision.

  • diff_working

    Likewise, but compare the local file and the revision from which it was obtained.

  • diff

    Likewise, but compare the local file with a specific revision.

  • diff2

    Display a visual comparison between the two specified revisions of the file. The diff command must provide a normal diff as opposed to context or unified ones.

    • $1 = revision 1
    • $2 = revision 2
    • $3 = file

14.9.4. Implementing VCS menus

All of the actions defined in the previous section can, for example, be viewed in the VCS page of the Key Shortcuts dialog (see The Key Manager Dialog).

GPS provides a Python facility in the plugin vcs.py that associates menu items to VCS actions. This facility defines, in one place, the VCS menus to be displayed in the global VCS menu, in the contextual menus on contexts that contain files, and on the menus in the VCS explorer.

To use this facility, you must first define a list of associations in Python, and then register this list through a call to the function vcs.register_vcs_actions(), which has the following parameters:

  • the name of the version control system as defined in the name attribute of the <vcs> tag in the XML definition.
  • a list of dictionaries of the form ACTION : <name of the vcs action>, LABEL: <menu label>. You can use the predefined SEPARATOR dictionary to indicate a separator to be displayed in the contextual menus on files and in the VCS Explorer.

If you defined a custom VCS in a previous version of GPS, you need to define your menus through this facility. The easiest way is to copy one of the existing plugins (for example, subversion.py or clearcase.py) and change the first parameter in the call to register_vcs_actions().

14.10. The Server Mode

To give access to the GPS capabilities from external processes (e.g. emacs), you can launch GPS in server mode.

The relevant command line switches are –server and –hide. –server opens a socket on the specified port, allowing multiple clients to connect to a running GPS and send GPS shell or Python commands. –hide tells GPS not to display its main window when starting. On Unix systems, you still need to have access to the current screen (as determined by the DISPLAY environment variable) in this mode. Using both switches provides a way to launch GPS as a background process with no initial user interface.

Clients connecting through a standard socket have access to a simple shell using GPS>> as the prompt between each command. This is needed in order to determine when the output (result) of a command is completed. All GPS shell commands (as defined in The GPS Shell) are available from this shell. In addition, the Python interpreter, if enabled, is also available through the use of the python prefix before a Python command.

For example, sending pwd through the socket sends the pwd command through the GPS shell and sends the result to the socket; similarly, sending python GPS.pwd() will send the GPS.help() command through the python interpreter (see The Python Interpreter for more details).

The socket shell provides also additional commands:

  • logout

    Inform the GPS server that the connection should be closed.

  • id <string>

    Register the current session with a given string. This string can then be used within GPS itself (for example via a .xml or Python plug-in) to display extra information to the client via the socket, using the function GPS.Socket().send().

For example, suppose we start GPS with the –server=1234 command: this brings up GPS as usual. Now, on a separate terminal, create a simple client by typing the following:

telnet localhost 1234
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
GPS>> id test-1
id set to 'test-1'
GPS>> pwd
c:\\working-dir\\
GPS>>

Then in the GPS Python Console:

>>> GPS.Socket ("test-1").send ("hello, it is time to logout\\n");

At this point, the following is received on the client (telnet) side:

GPS>> hello, it is time to logout

We can then close the client:

logout
Connection closed by foreign host.

14.11. Adding project templates

The Project template wizard lists a selection of templates. GPS locates the default set in the share/gps/templates directory of your GPS installation.

You can register new directories in which GPS looks for templates by using the Shell/Python function GPS.ProjectTemplate.add_templates_{dir}().

To create a new project template, first create a subdirectory in the share/gps/templates/ directory or in one of the directories you have registered with GPS.ProjectTemplate.add(). Then, in this directory, create one template description file, which is a text file with the .gpt extension and the following syntax:

Name: <name>
Category: <category>
Project: <project file>
<optional_hook_line>

<variable_1>: <variable_1_default_value>: <variable_1_description>
<variable_2>: <variable_2_default_value>: <variable_3_description>
<etc>

[Description]
<the description>

Where the following are specified:

  • <name>

    Name of the template as it appears in the template tree in the Project template wizard.

  • <category>

    Category in which the template is inserted in the template tree. There can be multiple levels of categories, separated with /.

  • <variable_1>

    Name substituted in the template files when deploying the template; see below.

  • <variable_1_default_value>

    Default value for variable 1, which appears in the project template wizard.

  • <variable_1_description>

    Description of variable 1.

  • <optional_hook_line>

    Optional line of the form post_hook: <python_file> where <python_file> is the name of a Python file present in the same directory as the template description file. This Python file is run by GPS once, immediately after it deploys the project template.

  • <description>

    Short paragraph describing the project template. This paragraph is displayed in the Project template wizard when the user selects the template in the tree.

When deploying templates, GPS copies all files and directories present in the directory containing the template description file (except the Python file indicated as post_hook() and the template description file itself) into the destination directory chosen by the user.

As it deploys templates, GPS replaces strings of the form <variable_name> with the value of the variable. If <variable_name> is all lower case, the substitution is converted to lower-case. If <variable_name> is in mixed case, the substitution is converted into mixed case as well. If it is in upper case, the substitution contains the original value specified by the user.