Java Code Examples for org.eclipse.xtext.nodemodel.INode#getEndOffset()

The following examples show how to use org.eclipse.xtext.nodemodel.INode#getEndOffset() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: N4JSQuickfixProvider.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private int getOffsetOfNameEnd(EObject object) {
	INode node;
	if (object instanceof N4FieldDeclaration) {
		N4FieldDeclaration fieldDecl = (N4FieldDeclaration) object;
		if (fieldDecl.isDeclaredOptional()) {
			return -1;
		}
		node = NodeModelUtils.findActualNodeFor(((PropertyNameOwner) object).getDeclaredName());
	} else if (object instanceof TField) {
		TField field = (TField) object;
		if (field.isOptional()) {
			return -1;
		}
		node = NodeModelUtils.findNodesForFeature(object, TypesPackage.Literals.IDENTIFIABLE_ELEMENT__NAME).get(0);
	} else {
		return -1;
	}
	return node.getEndOffset();
}
 
Example 2
Source File: EObjectAtOffsetHelper.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.1
 */
public INode getCrossReferenceNode(XtextResource resource, ITextRegion region) {
	IParseResult parseResult = resource.getParseResult();
	if (parseResult != null) {
		ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), region.getOffset());
		INode crossRefNode = findCrossReferenceNode(leaf);
		// if not a cross reference position and the cursor is at the beginning of a node try the previous one.
		if (crossRefNode == null && leaf != null && region.getLength()==0 && leaf.getOffset() == region.getOffset()) {
			leaf = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), region.getOffset() - 1);
			return findCrossReferenceNode(leaf);
		} else if (crossRefNode != null && crossRefNode.getEndOffset() >= region.getOffset() + region.getLength()) {
			return crossRefNode;
		}
	}
	return null;
}
 
Example 3
Source File: N4JSOffsetAdapter.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/***/
@Creates
public IEObjectCoveringRegion IEObjectCoveringRegion() {
	final boolean haveRegion = region != null;

	int offset = haveRegion ? region.getOffset() : this.matchedOffset;
	int length = haveRegion ? region.getLength() : 0;
	int endOffset = offset + length;
	EObject semanticObject = null;

	INode node = NodeModelUtils.findLeafNodeAtOffset(resource.getParseResult().getRootNode(), offset);
	while (node != null) {
		EObject actualObject = NodeModelUtils.findActualSemanticObjectFor(node);
		if (actualObject != null) {
			if (haveRegion) {
				int nodeEndOffset = node.getEndOffset();
				if (nodeEndOffset <= endOffset || semanticObject == null) {
					semanticObject = actualObject;
				}
				if (nodeEndOffset >= endOffset) {
					break;
				}
			} else { // no region given, just a matched offset
				if (semanticObject == null) {
					semanticObject = actualObject;
					break;
				}
			}
		}
		node = node.getParent();
	}
	return new EObjectCoveringRegion(semanticObject, offset);
}
 
Example 4
Source File: ImportsRemovalChangesComputer2.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private static IChange removeNodeButKeepComments(IXtextDocument doc, INode importNode) throws BadLocationException {
	if (importNode == null)
		return IChange.IDENTITY;

	int end = importNode.getEndOffset();
	int offset = importNode.getOffset();
	return ChangeProvider.removeText(doc, offset, end - offset, true);
}
 
Example 5
Source File: PackageJsonChangeProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns change instance to set the ProjectType to the given value.
 *
 * @param pckJsonResource
 *            The package.json resource
 * @param projectType
 *            The project type to set
 * @param projectDescription
 *            The project description object of the package.json
 */
public static IAtomicChange setProjectType(Resource pckJsonResource, ProjectType projectType,
		ProjectDescription projectDescription) {

	URI uri = pckJsonResource.getURI();
	String newProjectTypeInQuotations = "\"" + projectType.getName().toLowerCase() + "\"";

	List<JSONStringLiteral> pairs = PackageJsonUtils.findNameValuePairs(pckJsonResource,
			PackageJsonProperties.PROJECT_TYPE, JSONStringLiteral.class);

	INode prjTypeNode = null;
	if (!pairs.isEmpty()) {
		JSONStringLiteral jsonStringLiteral = pairs.get(0);
		prjTypeNode = NodeModelUtils.findActualNodeFor(jsonStringLiteral);
	}

	if (prjTypeNode == null) {
		// Append a new entry
		List<JSONObject> n4jss = PackageJsonUtils.findNameValuePairs(pckJsonResource, PackageJsonProperties.N4JS,
				JSONObject.class);

		if (!n4jss.isEmpty()) {
			prjTypeNode = NodeModelUtils.findActualNodeFor(n4jss.get(0));
			int location = (prjTypeNode == null) ? 0 : prjTypeNode.getEndOffset();

			String name = PackageJsonProperties.PROJECT_TYPE.name;
			String nameValuePair = "\n" + name + ": " + newProjectTypeInQuotations + ((location == 0) ? "\n" : "");
			return new Replacement(uri, location, 0, nameValuePair);
		}
	} else {
		// Replace existing entry
		return new Replacement(uri, prjTypeNode.getOffset(), prjTypeNode.getLength(), newProjectTypeInQuotations);
	}

	return new Replacement(uri, 0, 0, "");
}
 
Example 6
Source File: XbaseIdeContentProposalProvider.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void completeBinaryOperation(final EObject model, final Assignment assignment, final ContentAssistContext context, final IIdeContentProposalAcceptor acceptor) {
  if ((model instanceof XBinaryOperation)) {
    int _length = context.getPrefix().length();
    boolean _tripleEquals = (_length == 0);
    if (_tripleEquals) {
      final INode currentNode = context.getCurrentNode();
      final int offset = currentNode.getOffset();
      final int endOffset = currentNode.getEndOffset();
      if ((((offset < context.getOffset()) && (endOffset >= context.getOffset())) && (currentNode.getGrammarElement() instanceof CrossReference))) {
        return;
      }
    }
    int _endOffset = NodeModelUtils.findActualNodeFor(model).getEndOffset();
    int _offset = context.getOffset();
    boolean _lessEqualsThan = (_endOffset <= _offset);
    if (_lessEqualsThan) {
      AbstractElement _terminal = assignment.getTerminal();
      this.createReceiverProposals(((XExpression) model), ((CrossReference) _terminal), context, acceptor);
    } else {
      AbstractElement _terminal_1 = assignment.getTerminal();
      this.createReceiverProposals(((XBinaryOperation)model).getLeftOperand(), 
        ((CrossReference) _terminal_1), context, acceptor);
    }
  } else {
    final EObject previousModel = context.getPreviousModel();
    if ((previousModel instanceof XExpression)) {
      if (((context.getPrefix().length() == 0) && (NodeModelUtils.getNode(previousModel).getEndOffset() > context.getOffset()))) {
        return;
      }
      AbstractElement _terminal_2 = assignment.getTerminal();
      this.createReceiverProposals(((XExpression)previousModel), 
        ((CrossReference) _terminal_2), context, acceptor);
    }
  }
}
 
Example 7
Source File: StatemachineFoldingRegionProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Determine the text region between the start node and the end node.
 */
private ITextRegion textRegionBetween(XtextResource res, INode startNode, INode endNode) {
	int offset = startNode.getOffset();
	int endOffset = endNode.getEndOffset();
	int length = endOffset - offset;
	return new TextRegion(offset, length);
}
 
Example 8
Source File: ProposalConflictHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean existsConflict(String proposal, ContentAssistContext context) {
	// hidden node between lastCompleteNode and currentNode?
	INode lastCompleteNode = context.getLastCompleteNode();
	Region replaceRegion = context.getReplaceRegion();
	int nodeEnd = lastCompleteNode.getEndOffset();
	if (nodeEnd < replaceRegion.getOffset())
		return false;
	
	return existsConflict(lastCompleteNode, replaceRegion.getOffset(), proposal, context);
}
 
Example 9
Source File: XbaseProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void completeBinaryOperationFeature(EObject model, Assignment assignment, ContentAssistContext context,
		ICompletionProposalAcceptor acceptor) {
	if (model instanceof XBinaryOperation) {
		if (context.getPrefix().length() == 0) { // check for a cursor inbetween an operator
			INode currentNode = context.getCurrentNode();
			int offset = currentNode.getOffset();
			int endOffset = currentNode.getEndOffset();
			if (offset < context.getOffset() && endOffset >= context.getOffset()) {
				if (currentNode.getGrammarElement() instanceof CrossReference) {
					// don't propose another binary operator
					return;
				}
			}
		}
		if (NodeModelUtils.findActualNodeFor(model).getEndOffset() <= context.getOffset()) {
			createReceiverProposals((XExpression) model,
					(CrossReference) assignment.getTerminal(), context, acceptor);
		} else {
			createReceiverProposals(((XBinaryOperation) model).getLeftOperand(),
					(CrossReference) assignment.getTerminal(), context, acceptor);
		}
	} else {
		EObject previousModel = context.getPreviousModel();
		if (previousModel instanceof XExpression) {
			if (context.getPrefix().length() == 0) {
				if (NodeModelUtils.getNode(previousModel).getEndOffset() > context.getOffset()) {
					return;
				}
			}
			createReceiverProposals((XExpression) previousModel,
					(CrossReference) assignment.getTerminal(), context, acceptor);
		}
	}
}
 
Example 10
Source File: XbaseQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private void addTypeCastToExplicitReceiver(XAbstractFeatureCall featureCall, IModificationContext context,
		JvmType declaringType, EReference structuralFeature) throws BadLocationException {
	List<INode> nodes = NodeModelUtils.findNodesForFeature(featureCall, structuralFeature);
	if (nodes.isEmpty())
		return;
	INode firstNode = IterableExtensions.head(nodes);
	INode lastNode = IterableExtensions.last(nodes);
	int offset = firstNode.getOffset();
	int length = lastNode.getEndOffset() - offset;
	ReplacingAppendable appendable = appendableFactory.create(context.getXtextDocument(),
			(XtextResource) featureCall.eResource(), offset, length);
	appendable.append("(");
	ListIterator<INode> nodeIter = nodes.listIterator();
	while (nodeIter.hasNext()) {
		String text = nodeIter.next().getText();
		if (nodeIter.previousIndex() == 0)
			appendable.append(Strings.removeLeadingWhitespace(text));
		else if (nodeIter.nextIndex() == nodes.size())
			appendable.append(Strings.trimTrailingLineBreak(text));
		else
			appendable.append(text);
	}
	appendable.append(" as ");
	appendable.append(declaringType);
	appendable.append(")");
	appendable.commitChanges();
}
 
Example 11
Source File: XbaseQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void remove(IXtextDocument document, ICompositeNode node) throws BadLocationException {
	int offset = node.getOffset();
	int length = node.getLength();
	if (node.hasPreviousSibling()) {
		INode previousSibling = node.getPreviousSibling();
		int endOffset = previousSibling.getEndOffset();
		length = length + (offset - endOffset);
		offset = endOffset;
	}
	document.replace(offset, length, "");
}
 
Example 12
Source File: ProposalConflictHelper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean existsConflict(String proposal, ContentAssistContext context) {
	// hidden node between lastCompleteNode and currentNode?
	INode lastCompleteNode = context.getLastCompleteNode();
	ITextRegion replaceRegion = context.getReplaceRegion();
	int nodeEnd = lastCompleteNode.getEndOffset();
	if (nodeEnd < replaceRegion.getOffset())
		return false;
	
	return existsConflict(lastCompleteNode, replaceRegion.getOffset(), proposal, context);
}
 
Example 13
Source File: ScriptError.java    From openhab-core with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Creates new ScriptError.
 *
 * This constructor uses the given EObject instance to calculate the exact position.
 *
 * @param message Error Message
 * @param atEObject the EObject instance to use for calculating the position
 *
 */
public ScriptError(final String message, final EObject atEObject) {
    this.message = message;
    INode node = NodeModelUtils.getNode(atEObject);
    LineAndColumn lac = NodeModelUtils.getLineAndColumn(node, node.getOffset());
    this.line = lac.getLine();
    this.column = lac.getColumn();
    this.length = node.getEndOffset() - node.getOffset();
}
 
Example 14
Source File: ScriptError.java    From smarthome with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Creates new ScriptError.
 *
 * This constructor uses the given EObject instance to calculate the exact position.
 *
 * @param message Error Message
 * @param atEObject the EObject instance to use for calculating the position
 *
 */
public ScriptError(final String message, final EObject atEObject) {
    this.message = message;
    INode node = NodeModelUtils.getNode(atEObject);
    LineAndColumn lac = NodeModelUtils.getLineAndColumn(node, node.getOffset());
    this.line = lac.getLine();
    this.column = lac.getColumn();
    this.length = node.getEndOffset() - node.getOffset();
}