Search code examples
javaeclipsepluginsplugin.xml

How to add a command in right click menu of a function or class in Eclipse?


This is kind of newbie question. All tutorials show a way to add a command to a iFile object class. Can you show me an example of a plugin.xml file that registers a command for a function or class?

What I want to achieve is to right-click on a class or a function name in Outline view or in the code itself and have my new command in the context menu.


Solution

  • The key is to use visibleWhen part properly. This is an example of a command showing in Project Explorer which is visible only when a Java method or class is selected:

      <menuContribution
            locationURI="popup:org.eclipse.ui.navigator.ProjectExplorer#PopupMenu">
         <command
               commandId="__your.command.id__"
               id="your.contribution.id"
               label="Some Label"
               style="push">
            <visibleWhen
                  checkEnabled="false">
               <iterate
                     ifEmpty="false"
                     operator="and">
                  <or>
                     <instanceof
                           value="org.eclipse.jdt.core.IType">
                     </instanceof>
                     <instanceof
                           value="org.eclipse.jdt.core.IMethod">
                     </instanceof>
                  </or>
               </iterate>
            </visibleWhen>
         </command>
      </menuContribution>
    

    Don't forget to set commandId to something real.

    You can find more info about property and selection testing here.