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()) {

		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.

2 thoughts on “Obtain the model object selected in a Xtext editor

  1. Please send me the ‘site’ of ‘prayers in different occasions’ just now I was going through the ‘prayers’ in one of the site when the ‘connection of the internet’ went off and have lost that page…….kindly do send me this page please. Thanks.Love in Jesus Name ……Amen.jean

  2. zroot, veo que tiene usted un profundo conocimiento del sistema de revisión por pares, así que me gustaría que me dijera a dónde me tengo que dirigir para cobrar mis honorarios, ya que tras revisar varios artículos científicos y proyectos de investigación, todavía no he visto ni un céntimo.

Leave a Reply

Your email address will not be published. Required fields are marked *