adagnatgnat-gps

GNAT GPS: Add a custom command


I would like to know if it is possible to add a custom command to the GNAT Programming Studio (GPS)?

If the custom command is invoked (by a button in the menu bar or a keyboard shortcut) an external Python script should be called with the full/absolute path to the file that is opened and selected in the editor.


Solution

  • This is a quick-and-dirty script that might give some direction. I tested it on Linux, but it should also work on Windows. Change the action near the end to invoke the script you like. To actually use it, you must put it in the (hidden) .gps/plug-ins directory which can be found in your home directory. The actual action can be invoked from the context menu in the source code window.

    run_my_script.py

    """Run Python Script
    
    This plug-in executes a python script.
    """
    
    ###########################################################################
    # No user customization below this line
    ###########################################################################
    
    import os, sys
    import GPS
    from gps_utils import interactive
    
    def __contextualMenuFilter(context):
    
        # Check if the context is generated by the source editor
        if not (context.module_name == "Source_Editor"):
            return False
    
        # If all OK, show the menu item in the context menu.
        return True
    
    def __contextualMenuLabel(context):
    
        # Get current buffer
        name = context.file().name()
        basename = os.path.basename(name)
    
        # Name of the menu item.
        return "Run Python script for <b>{}</b>".format(basename)
    
    @interactive(
        name       ="Run Python script",
        contextual = __contextualMenuLabel,
        filter     = __contextualMenuFilter)
    def on_activate():
    
        # If modified, then save before proceeding.
        eb = GPS.EditorBuffer.get()
        if eb.is_modified:
            eb.save()
    
        # Run the action (defined below).
        GPS.execute_action("my_script")
    
    GPS.parse_xml ("""
       <action name="my_script">
         <external output="Output of my_script">python3 /home/deedee/my_script.py %F</external>
       </action>""")
    

    my_script.py (some test script)

    import sys
    
    print ("Running script {0} for {1}".format(sys.argv[0], sys.argv[1]));
    

    output (shown in GPS on a new tab named "Output of my_script")

    python3 /home/deedee/my_script.py /home/deedee/example/src/main.adb
    Running script /home/deedee/my_script.py for /home/deedee/example/src/main.adb
    

    Some relevant info from the GNAT Studio (formerly GPS) documentation: