views:

313

answers:

2

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 nested action with "enablesFor='+'".

How does one do this using commands instead of actions?

+1  A: 

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.

VonC
Thanks VonC. So looking at this, I can see no benefit to doing this with commands vs. objectContributions and Actions. Thoughts?
marc esher
If the `Command`/`handler` is not reused in many editors/views, it can be a little overkill and a single `Action` is enough.
VonC
A: 

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>

marc esher