No typing is good typing!

In the grammar we wrote some posts ago, the rule Room is formed by two separate keywords: 'OF' and 'TYPE'. For some reasons (you can think of them as some sort of weird requisite) we had to break the keywords in two distinct rules. That separation caused two immediate effects:

  1. Beetween 'OF' and 'TYPE' we allow an arbitrary number of hidden tokens (white space, end of line, ecc.).
  2. We have to call the content assist twice: one time for each keyword.

What if we want to call the content assist only once, without changing the grammar? In that way we also easly maintain the first effect. We have to customize how the content assist works, inserting 'TYPE' along with 'OF', when we trig the assistance at the position of 'OF'. Xtext gives us a class for this purpose, a ProposalProvider (MyDslProposalProvider), that extends AbstractMyDslProposalProvider. Of all the methods, there is one dedicated to the completion of keywords called completeKeyword where we will write our solution. The solution is break in two parts: first we have to check that we are calling the assist at the 'OF' position, then we have to build the new proposal that will appear in the content assist. Xtext API and Eclipse API will give us all the tools needed for the task. Here is the code:

public void completeKeyword(Keyword keyword,
                                              ContentAssistContext contentAssistContext, 
                                              ICompletionProposalAcceptor acceptor)
   //Call the super version: we still want all the old proposals.
   super.completeKeyword(keyword, contentAssistContext, acceptor);
   if(keyword.getValue().compareTo("OF") == 0)
      //Get the last Node.
      AbstractNode lastNode = contentAssistContext.getLastCompleteNode();
      //Get the EObject from the Node.
      EObject precModel = NodeUtil.findASTElement(lastNode);
      //Identify the EObject, here we can use various criteria.
      if(precModel instanceof Room && //What kind is it?
         precModel.eContainingFeature().getName().compareTo("rooms")==0 && //Where is contained?
         precModel.eContainer() instanceof Structure) //Which is its parent?
         //The new proposal.
         String proposal = "OF TYPE";
         //Create the proposal using the minimum version of the creation method.
         ICompletionProposal completion = createCompletionProposal(proposal, contentAssistContext);
         //Register the completion.

Now calling the content assist at the 'OF' position should show something like this:


About Luong

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s