Book

A paper I wrote some time ago about combining textual and graphical editors in model driven architecture (MDA) has been published as book. It is only available in german and the title is Verbinden eines textuellen und eines graphischen Editors bei MDA. Available on Amazon, for example.

61AwqLLRTeL._SL1360_

Obtain the model object selected in a Xtext editor

When extending a Xtext editor it is sometime necessary to obtain the model node currently selected within the textual representation. But the problem is, if you add an ISelectionChangedListener to the Xtext editor part you will only get selected text as String.

Here’s a code snipped that tries to determine the nearest model object at the given selection offset:

 
private class MySelectionListener implements ISelectionChangedListener {
	
	public void selectionChanged(SelectionChangedEvent event) {
		final TextSelection selection = (TextSelection) event.getSelection();			
		if (selection.isEmpty()) {
			return;
		}	

		XtextSourceViewer viewer = (XtextSourceViewer) event.getSource();
		XtextDocument document = (XtextDocument) viewer.getDocument();
						
		EObject selectedObject = document.readOnly(new IUnitOfWork<EObject, XtextResource>() {						
			public EObject exec(XtextResource resource) throws Exception {
				IParseResult parseResult = resource.getParseResult();
	            if (parseResult == null) {
	            	return null;
	            }
	            ICompositeNode rootNode = parseResult.getRootNode();
	            int offset = selection.getOffset();
	            ILeafNode node = NodeModelUtils.findLeafNodeAtOffset(rootNode, offset);
	            return NodeModelUtils.findActualSemanticObjectFor(node);
			}
	    });
			
		if (selectedObject != null && selectedObject instanceof KindDecl) {
			//Do something with the selected model object
		}	
	}		
}

I’m using Xtext 2.3.0, but it might also work with earlier versions.