How do you contribute a command to an editor context menu in Eclipse

前端 未结 2 1857
自闭症患者
自闭症患者 2021-01-06 11:33

I want to contribute a command to the context menu of any text editor when text is selected. In \"the old days\", I would have done this using objectContribution and a neste

相关标签:
2条回答
  • 2021-01-06 11:56

    If I revisit my answer "Eclipse RCP: Actions VS Commands", you need a Command handler.

    This thread seems to sum up your options:

    • One is a common pattern, to instantiate the handler in the view itself and have the handler simply look at the view selection and control its own enabled state.
      The handler API allows it to fire an event on enabled change, see org.eclipse.core.commands.AbstractHandler.

    • The other is to create a property tester that can get your view selection.

    IWorkbenchPart p = page.findViewReference("your.id").getPart(false);
    if (p!=null) {
      p.getSite().getSelectionProvider().getSelection() ... whatever
    }
    

    Your view would monitor its own selection change events, and call org.eclipse.ui.services.IEvaluationService.requestEvaluation(String) (source here) for that property (which would cause all core expressions using that property tester to be re-evaluated).
    The important point is that simply changing views would not cause a re-evaluation (and not change enabled state).

    You can set up the property tester to be specific to each view that you need this for, or create one com.example.views.localSelection and use args to specify the view id.

    0 讨论(0)
  • 2021-01-06 12:02

    I read more about the variables available in command expressions, and I came close to figuring it out on my own, but failed. I then asked a similar question on the eclipse newsgroup and was led in the right direction. Here's an example of how to do mostly what I was looking for:

     <command
          commandId="org.marcesher.blogcodeformatter.commands.wikiFormatterCommand"
          tooltip="Format And Copy to Clipboard"
          id="org.marcesher.blogcodeformatter.popup.wikiFormatterCommand">
        <visibleWhen>
           <with variable="selection">
              <instanceof value="org.eclipse.jface.text.ITextSelection"/>
           </with>
        </visibleWhen>
    

    0 讨论(0)
提交回复
热议问题