17. Useful plug-ins — GPS 6.0.1 documentation

### Navigation

- index
- modules |
- next |
- previous |
- GPS 6.0.1 documentation »

# 17. Useful plug-ins

## 17.1. User plug-ins

GPS comes with a number of plug-ins. Some of these plugins are activated by default, others are not. In both cases, you can control which plug-ins should be activated by using the menu /Tools/Plug-ins.

This section highlights a few of these plug-ins, but GPS comes with many more plug-ins. The dialog Tools/Plug-ins will show their description, so that you can decide whether you want them or not.

### 17.1.1. The `auto_highlight_occurrences.py` module

This plug-in highlights all occurrences of the entity under the cursor.

Whenever your cursor rests in a new location, GPS will search for all other places where this entity is referenced using either the cross-reference engine in GPS, if this information is up-to-date, or a simple textual search. Each of these occurrences will then be highlighted in a color depending on the kind of the entity.

This plug-in does its work in the background, whenever GPS is not busy responding to your actions, so it should have limited impact on the performances and responsiveness of GPS.

If you are interested in doing something similar in your own plugins, we recommend you look at the `gps_utils.highlighter.Background_Highlighter` class instead, which provides the underlying framework.

A similar plug-in which you might find useful is in the `gps_utils.highlighter.Regexp_Highlighter` class. By creating a simple python file in your gps directory, you are able to highlight any regular expression in the editor, which is useful for highlighting text like “TODO”, or special comments for instance.

### 17.1.2. The `dispatching.py` module

Highlighting all dispatching calls in the current editor

This package will highlight with a special background color all dispatching calls found in the current editor. In particular, at such locations, the cross-references might not lead accurate result (for instance “go to body”), since the exact subprogram that is called is not known until run time.

## 17.2. Helper plug-ins

A number of plug-ins are in fact useful when you want to create your own plug-ins.

### 17.2.1. The `gps_utils` module

`gps_utils.` `execute_for_all_cursors`(editor, mark_fn, extend_selection=False)

  Execute the function mark_fn for every cursor in the editor, meaning, the main cursor + every existing multi cursor. mark_fn has the prototype def mark_fn(EditorBuffer, EditorMark)

`gps_utils.` `freeze_prefs`()

  A context manager that temporarily freezes GPS’ preferences_changed signal from being emitted, and then reactivated it. This is useful when modifying a large number of preferences as a single batch.

  This can be used as:

      with gps_utils.freeze_prefs():
          GPS.Preference(...).set(...)
          GPS.Preference(...).set(...)
          GPS.Preference(...).set(...)

`gps_utils.` `in_ada_file`(context)

  Returns True if the focus is currently inside an Ada editor

`gps_utils.` `in_xml_file`(context)

  Returns True if the focus is in an XML editor

class `gps_utils.` `interactive`(category='General', filter='', menu='', key='', contextual='', name='', before='', after='')

  A decorator with the same behavior as make_interactive(). This can be used to easily associate a function with an interactive action, menu or key, so that a user can conveniently call it:

      @interactive("Editor", menu="/Edit/Foo")
      def my_function():
          pass

`gps_utils.` `is_writable`(context)

  Returns True if the focus is currently inside a writable editor

`gps_utils.` `make_interactive`(callback, category='General', filter='', menu='', key='', contextual='', name='', before='', after='')

  Declare a new GPS action (an interactive function, in Emacs talk), associated with an optional menu and default key. The description of the action is automatically taken from the documentation of the python function. Likewise the name of the action is taken from the name of the python function, unless specified with name.

  Parameters: | callback – is a python function that requires no argument, although it can have optional arguments (none will be set when this is called from the menu or the key shortcut). Alternatively, callback can also be a class: when the user executes the action, a new instance of the class is created, so it is expected that the work is done in the __init__ of the class. This is in particular useful for classes that derive from CommandWindow. menu – The name of a menu to associate with the action. It will be placed within its parent just before the item referenced as before, or after the item referenced as after.

`gps_utils.` `remove_interactive`(menu='', name='', contextual='')

  Undo the effects of make_interactive.

`gps_utils.` `save_current_window`(f, args=[], kwargs={})

  Save the window that currently has the focus, executes f, and reset the focus to that window.

`gps_utils.` `save_dir`(fn)

  Saves the current directory before executing the instrumented function, and restore it on exit. This is a python decorator which should be used as:

      @save_dir
      def my_function():
          pass

`gps_utils.` `save_excursion`(f, args=[], kwargs={}, undo_group=True)

  Save current buffer, cursor position and selection and execute f. (args and kwargs) are passed as arguments to f. They indicate that any number of parameters (named or unamed) can be passed in the usual way to save_excursion, and they will be transparently passed on to f. If undo_group is True, then all actions performed by f will be grouped so that the user needs perform only one single undo to restore previous start.

  Then restore the context as it was before, even in the case of abnormal exit.

  Example of use:

      def my_subprogram():
         def do_work():
             pass   # do actual work here
         save_excursion(do_work)

  See also the with_save_excursion decorator below for cases when you need to apply save_excursion to a whole function.

`gps_utils.` `with_save_current_window`(fn)

  A decorator with the same behavior as save_current_window.

`gps_utils.` `with_save_excursion`(fn)

  A decorator with the same behavior as save_excursion. To use it, simply add @with_save_excursion before the definition of the function. This ensures that the current context will be restored when the function terminates:

      @with_save_excursion
      def my_function():
          pass

### 17.2.2. The `gps_utils.highlighter.py` module

This file provides various classes to help highlight patterns in files.

class `gps_utils.highlighter.` `Background_Highlighter`(style)

  An abstract class that provides facilities for highlighting parts of an editor. If possible, this highlighting is done in the background so that it doesn’t interfer with the user typing. Example of use:

      class Example(Background_Highlighter):
         def process(self, start, end):
             ... analyze the given range of lines, and perform highlighting
             ... where necessary.

      e = Example()
      e.start_highlight(buffer1)   # start highlighting a first buffer
      e.start_highlight(buffer2)   # start highlighting a second buffer

  Parameters: | style (OverlayStyle) – style to use for highlighting.

  `on_start_buffer`(buffer)

    Called before we start processing a new buffer.

  `process`(start, end)

    Called to highlight the given range of editor. When this is called, previous highlighting has already been removed in that range.

    Parameters: | start (GPS.EditorLocation) – start of region to process. end (GPS.EditorLocation) – end of region to process.

  `remove_highlight`(buffer=None)

    Remove all highlighting done by self in the buffer.

    Parameters: | buffer (GPS.EditorBuffer) – defaults to the current buffer

  `set_style`(style)

    Change the current highlight style.

    Parameters: | style (OverlayStyle) – style to use for highlighting.

  `start_highlight`(buffer=None, line=None, context=None)

    Start highlighting the buffer, possibly in the background.

    Parameters: | buffer (GPS.EditorBuffer) – The buffer to highlight (defaults to the current buffer). This buffer is added to the list of buffers, and will be processed when other buffers are finished. line (integer) – The line the highlighting should start from. By default, this is the current line in the editor, so that the user sees changes immediately. But you could chose to start from the top of the file instead. context (integer) – Number of lines before and after ‘line’ that should be highlighted. By default, the whole buffer is highlighted.

  `stop_highlight`(buffer=None)

    Stop the background highlighting of the buffer, but preserves any highlighting that has been done so far.

    Parameters: | buffer (GPS.EditorBuffer) – If specified, highlighting is only stopped for a specific buffer.

class `gps_utils.highlighter.` `Location_Highlighter`(style, context=2)

  An abstract class that can be used to implement highlighter related to the cross-reference engine. As usual, such an highlighter does its job in the background. To find the places to highlight in the editor, this class relies on having a list of entities and their references. This list will in general be computed once when we start processing a new buffer:

      class H(Location_Highlighter):
          def recompute_refs(self, buffer):
              return ...computation of references within file ...

  Parameters: | context (integer) – The number of lines both before and after a given reference where we should find for possible approximate matches. This is used when the reference returned by the xref engine was outdated.

  `recompute_refs`(buffer)

    Called before we start processing a new buffer.

    Returns: | a list of tuples, each of which contains an (name, GPS.FileLocation). The highlighting is only done if the text at the location is name. Name should be a byte-sequence that encodes a UTF-8 strings, not the unicode string itself (the result of GPS.EditorBuffer.get_chars or GPS.Entity.name can be used).

class `gps_utils.highlighter.` `On_The_Fly_Highlighter`(style, context_lines=0)

  This abstract class provides a way to easily highlight text in an editor. When possible, the highlighting is done in the background, in which case it is also done on the fly every time the file is modified. If pygobject is not available, the highlighting is only done when the file is opened or saved

  Parameters: | style (OverlayStyle) – the style to apply. context_lines (intger) – The number of lines (plus or minus) around the current location that get refreshed when a local highlighting is requested.

  `do_highlight`(buffer, start, end)

    Do the highlighting in the range of text. This needs to be overridden to do anything useful

  `must_highlight`(buffer)

    Parameters: | buffer (GPS.EditorBuffer) – The buffer to test.
    Returns: | whether to highlight this buffer. The default is to higlight all buffers, but some highlightings might apply only to specific languages for instance
    Return type: | boolean

  `start`()

    Start highlighting. This is automatically called from __init__, and only needs to be called when you have called stop() first. Do not call this function multiple times.

  `stop`()

    Stop highlighting through self

class `gps_utils.highlighter.` `OverlayStyle`(name, foreground='', background='', weight=None, slant=None, editable=True, whole_line=False, speedbar=False, **kwargs)

  Description for a style to apply to a section of an editor. In practice, this could be implemented as an editor overlay, or a message, depending on whether highlighting should be done on the whole line or not.

  Parameters: | name (string) – name of the overlay so that we can remove it later. foreground (string) – foreground color background (string) – background color weight (string) – one of “bold”, “normal”, “light” slant (string) – one of “normal”, “oblique”, “italic” whole_line (boolean) – whether to highlight the whole line, up to the right margin speedbar (boolean) – whether to show a mark in the speedbar to the left of editors. This forces whole_line to True. kwargs – other properties supported by EditorOverlay

  `apply`(start, end)

    Apply the highlighting to part of the buffer.

    Parameters: | start (GPS.EditorLocation) – start of highlighted region. end (GPS.EditorLocation) – end of highlighted region.

  `remove`(start, end=None)

    Remove the highlighting in whole or part of the buffer. :param GPS.EditorLocation start: start of region. :param GPS.EditorLocation end: end of region. If unspecified, the highlighting for the whole buffer is removed.

  `use_messages`()

    Returns: | Whether this style will use a GPS.Message or a GPS.EditorOverlay to highlight.
    Return type: | boolean

class `gps_utils.highlighter.` `Regexp_Highlighter`(regexp, style, context_lines=0)

  The Regexp_Highlighter is a concrete implementation to highlight editors based on regular expressions. One example is for instance to highlight tabs or trailing spaces on lines, when this is considered improper style:

      Regexp_Highlighter(
          regexp="    +|\s+$",
          style=OverlayStyle(
             name="tabs style",
             strikethrough=True,
             background="#FF7979"))

  Another example is to highlight TODO lines. Various conventions exist to mark these in the sources, but the following should catch some of these:

      Regexp_Highlighter(
          regexp="TODO.*|\?\?\?.*",
          style=OverlayStyle(
             name="todo",
             background="#FF7979"))

  Another example is a class to highlight Spark comments. This should only be applied when the language is spark:

      class Spark_Highlighter(Regexp_Highlighter):
          def must_highlight(self, buffer):
              return buffer.file().language().lower() == "spark"

      Spark_Highlighter(
          regexp="--#.*$",
          style=OverlayStyle(
              name="spark", foreground="red"))

  Parameters: | regexp (string) – the regular expression to search for. It should preferrably apply to a single line, since highlighting is done on small sections of the editor at a time, and it might not detect cases where the regular expression would match across sections. style (OverlayStyle) – the style to apply.

class `gps_utils.highlighter.` `Text_Highlighter`(text, style, whole_word=False, context_lines=0)

  Similar to Regexp_Highlighter, but highlights constant text instead of a regular expression. By default, highlighting is done in all buffer, override the function must_highlight to reduce the scope.

  Parameters: | text (string) – the text to search for. It should preferrably apply to a single line, since highlighting is done on small sections of the editor at a time, and it might not detect cases where the text would match across sections. style (OverlayStyle) – the style to apply.

### 17.2.3. The `gps_utils.console_process.py` module

class `gps_utils.console_process.` `ANSI_Console_Process`(process, args='')

  This class has a purpose similar to Console_Process. However, this class does not attempt to do any of the high-level processing of prompt and input that Console_Process does, and instead forward immediately any of the key strokes within the console directly to the external process. It also provides an ANSI terminal to the external process. The latter can thus send escape sequences to change colors, cursor position,...

class `gps_utils.console_process.` `Console_Process`(process, args='', close_on_exit=True, force=False, ansi=False, manage_prompt=True)

  This class provides a way to spawn an interactive process and do its input/output in a dedicated console in GPS. The process is created so that it does not appear in the task manager, and therefore the user can exit GPS without being asked whether or not to kill the process.

  You can of course derive from this class easily. Things are slightly more complicated if you want in fact to derive from a child of GPS.Console (for instance a class that would handle ANSI escape sequences). The code would then look like:

      class ANSI_Console (GPS.Console):
         def write (self, txt): ...

      class My_Process (ANSI_Console, Console_Process):
         def __init__ (self, process, args=""):
           Console_Process.__init__ (self, process, args)

  In the list of base classes for My_Process, you must put ANSI_Console before Console_Process. This is because python resolves overridden methods by looking depth-first search from left to right. This way, it will see ANSI_Console.write before Console_Process.write and therefore use the former.

  However, because of that the __init__ method that would be called when calling My_Process (...) is also that of ANSI_Console. Therefore you must define your own __init__ method locally.

  See also the class ANSI_Console_Process if you need your process to execute within a terminal that understands ANSI escape sequences.

  Parameters: | force (boolean) – If True, a new console is opened, otherwise an existing one will be reused (although you should take care in this case if you have multiple processes attached to the same console). manage_prompt (boolean) – If True, then GPS will do some higher level handling of prompts: when some output is done by the process, GPS will temporarily hide what the user was typing, insert the output, and append what the user was typing. This is in general suitable but might interfer with external programs that do their own screen management through ANSI commands (like a Unix shell for instance).

  `on_completion`(input)

    The user has pressed <tab> in the console. The default is just to insert the character, but if you are driving a process that knows about completion, such as an OS shell for instance, you could have a different implementation. input is the full input till, but not including, the tab character

  `on_destroy`()

    This method is called when the console is being closed. As a result, we terminate the process (this also results in a call to on_exit

  `on_exit`(status, remaining_output)

    This method is called when the process terminates. As a result, we close the console automatically, although we could decide to keep it open as well

  `on_input`(input)

    This method is called when the user has pressed <enter> in the console. The corresponding command is then sent to the process

  `on_interrupt`()

    This method is called when the user presses control-c in the console. This interrupts the command we are currently processing

  `on_key`(keycode, key, modifier)

    The user has pressed a key in the console (any key). This is called before any of the higher level on_completion or on_input callbacks. If this subprogram returns True, GPS will consider that the key has already been handled and will not do its standard processing with it. By default, we simply let the key through and let GPS handle it.

    Parameters: | key – the unicode character (numeric value) that was entered by the user. _modifier_ is a mask of the control and shift keys that were pressed at the same time. See the Mask constants above. keycode is the code of the key, which is useful for non-printable characters. It is set to 0 in some cases if the input is simulated after the user has copied some text into the console

    This function is also called for each character pasted by the user in the console. If it returns True, then the selection will not be inserted in the console.

  `on_output`(matched, unmatched)

    This method is called when the process has emitted some output. The output is then printed to the console

  `on_resize`(console, rows, columns=None)

    This method is called when the console is being resized. We then let the process know about the size of its terminal, so that it can adapt its output accordingly. This is especially useful with processes like gdb or unix shells

### Navigation

- index
- modules |
- next |
- previous |
- GPS 6.0.1 documentation »