Next: Redirecting the output to specific windows, Previous: Redirecting the output of spawned processes, Up: Python FAQ

##### 16.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 will not be 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 would be to have 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 contain information about the project this file or directory belongs to. Thus this implicit filter will not be enough to hide your contextual menu.

As a result, you need to do a slightly more complex test, where you check that the current context doesn't contains information on directories (which will disable the contextual menu for directories, files and entities). Since the command uses `%P`, GPS garantees that a project is available.

We'll 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 for such a simple filter. Luckily, GPS provides a predefined filter just for that purpose, so that 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>