Search code examples
eclipseeclipse-plugineditormouseeventeclipse-cdt

Eclipse CDT plugin - get AST element based of X and Y position of mouse click in editor


I am currently developing a Eclipse CDT plugin, where based on the mouse click on the currently active editor I want to do some filtering - I want to display an action only if the clicked element is an Function Name (IFunction instance).

I have managed to achieve this, but only for the current caret position (via ISelection object) of the cursor in the active editor. However, I would like to do this for when the right click occurred, rather than the position, at which the caret is located.

So far, I have managed to get the mouse click event (object of type org.eclipse.swt.events.MouseEvent) and save it. However, I haven't found a way how to get the current selected AST element via any information in this object - widget, X, Y position of the click.

I have though of somehow changing the caret position to also change the current selection, but found no way how to do this or if this is the way to go.

Any ideas and help would be appreciated!

Thanks.


Solution

  • It looks like StyledText.getOffsetAtPoint() can be used to convert the coordinates of a click to a caret offset.

    The method's description specifically says:

    The return value reflects the character offset that the caret will be placed at if a mouse click occurred at the specified point.

    The StyledText object for an editor can be obtained based on the IEditorInput as follows:

    IEditorPart editor = CUIPlugin.getActivePage().findEditor(editorInput);
    StyledText textWidget = (StyledText) editor.getAdapter(Control.class);