Java Code Examples for org.eclipse.xtext.util.ITextRegion#getOffset()

The following examples show how to use org.eclipse.xtext.util.ITextRegion#getOffset() . 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: StringBasedTextRegionAccessDiffBuilder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean isModified(ITextRegion region) {
	int offset = region.getOffset();
	int endOffset = offset + region.getLength();
	for (Rewrite action : rewrites) {
		int rwOffset = action.originalFirst.getOffset();
		int rwEndOffset = action.originalLast.getEndOffset();
		if (rwOffset <= offset && offset < rwEndOffset) {
			return true;
		}
		if (rwOffset < endOffset && endOffset <= rwEndOffset) {
			return true;
		}
	}
	return false;
}
 
Example 2
Source File: QuickTypeHierarchyHandler.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void openPresentation(final XtextEditor editor, final IJavaElement javaElement,
		final EObject selectedElement) {
	final ISourceViewer sourceViewer = editor.getInternalSourceViewer();
	ITextRegion significantTextRegion = locationInFileProvider.getSignificantTextRegion(selectedElement);
	InformationPresenter presenter = new HierarchyInformationPresenter(sourceViewer, javaElement, new Region(significantTextRegion.getOffset(),significantTextRegion.getLength()));
	presenter.setDocumentPartitioning(IDocumentExtension3.DEFAULT_PARTITIONING);
	presenter.setAnchor(AbstractInformationControlManager.ANCHOR_GLOBAL);
	IInformationProvider provider = new JavaElementProvider(editor, false);
	presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
	presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC);
	presenter.setInformationProvider(provider, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
	presenter.setInformationProvider(provider, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
	presenter.setInformationProvider(provider, IJavaPartitions.JAVA_STRING);
	presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER);
	presenter.setSizeConstraints(50, 20, true, false);
	presenter.install(sourceViewer);
	presenter.showInformation();
}
 
Example 3
Source File: AstSelectionProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected ITextRegion getTextRegion(EObject eObject) {
	if (eObject == null)
		return null;
	IParseResult parseResult = ((XtextResource)eObject.eResource()).getParseResult();
	if (parseResult == null)
		return null;
	ICompositeNode rootNode = parseResult.getRootNode();
	Map<ILeafNode, EObject> comments = commentAssociater.associateCommentsWithSemanticEObjects(eObject, singleton(rootNode));
	final ITextRegion result = locationProvider.getFullTextRegion(eObject);
	int start = result.getOffset();
	int end = result.getOffset() + result.getLength();
	for (Entry<ILeafNode, EObject> entry : comments.entrySet()) {
		if (entry.getValue() == eObject) {
			ILeafNode node = entry.getKey();
			if (node.getTotalOffset() < start) {
				start = node.getTotalOffset();
			}
			if (node.getTotalEndOffset() > end) {
				end = node.getTotalEndOffset();
			}
		}
	}
	return new TextRegion(start, end-start);
}
 
Example 4
Source File: AbstractFormatter2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean isInRequestedRange(EObject obj) {
	Collection<ITextRegion> regions = request.getRegions();
	if (regions.isEmpty())
		return true;
	ITextRegionAccess access = request.getTextRegionAccess();
	IEObjectRegion objRegion = access.regionForEObject(obj);
	if (objRegion == null)
		return false;
	IHiddenRegion previousHidden = objRegion.getPreviousHiddenRegion();
	IHiddenRegion nextHidden = objRegion.getNextHiddenRegion();
	int objOffset = previousHidden != null ? previousHidden.getOffset() : 0;
	int objEnd = nextHidden != null ? nextHidden.getEndOffset() : access.regionForRootEObject().getEndOffset();
	for (ITextRegion region : regions) {
		int regionOffset = region.getOffset();
		int regionEnd = regionOffset + region.getLength();
		if (regionOffset <= objEnd && regionEnd >= objOffset)
			return true;
	}
	return false;
}
 
Example 5
Source File: DotRenameStrategy.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void createDeclarationUpdates(String newName,
		ResourceSet resourceSet,
		IRefactoringUpdateAcceptor updateAcceptor) {
	super.createDeclarationUpdates(newName, resourceSet, updateAcceptor);

	// perform renaming of the dependent element
	if (targetElement instanceof NodeId) {
		URI resourceURI = getTargetElementOriginalURI().trimFragment();

		NodeId targetNodeId = (NodeId) targetElement;
		List<NodeId> dependentNodeIds = DotAstHelper
				.getAllNodeIds(targetNodeId);

		for (NodeId dependentNodeId : dependentNodeIds) {
			ITextRegion dependentNodeIdTextRegion = locationInFileProvider
					.getFullTextRegion(dependentNodeId);
			TextEdit referenceEdit = new ReplaceEdit(
					dependentNodeIdTextRegion.getOffset(),
					dependentNodeIdTextRegion.getLength(), newName);
			updateAcceptor.accept(resourceURI, referenceEdit);
		}
	}
}
 
Example 6
Source File: XtendProposalProvider.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public void completeInRichString(EObject model, RuleCall ruleCall, ContentAssistContext context,
		ICompletionProposalAcceptor acceptor) {
	INode node = context.getCurrentNode();
	ITextRegion textRegion = node.getTextRegion();
	int offset = textRegion.getOffset();
	int length = textRegion.getLength();
	String currentNodeText = node.getText();
	if (currentNodeText.startsWith("\u00BB") && offset + 1 <= context.getOffset()
			|| currentNodeText.startsWith("'''") && offset + 3 <= context.getOffset()) {
		if (context.getOffset() > offset && context.getOffset() < offset + length)
			addGuillemotsProposal(context, acceptor);
	} else if (currentNodeText.startsWith("\u00AB\u00AB")) {
		try {
			IDocument document = context.getViewer().getDocument();
			int nodeLine = document.getLineOfOffset(offset);
			int completionLine = document.getLineOfOffset(context.getOffset());
			if (completionLine > nodeLine) {
				addGuillemotsProposal(context, acceptor);
			}
		} catch (BadLocationException e) {
			// ignore
		}
	}
}
 
Example 7
Source File: FlexTokenRegionProvider.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public ITextRegion getTokenRegion(String text, ITextRegion region) {
	try {
		InternalFlexer flexer = flexerFactory.createFlexer(new StringReader(text));
		int token = flexer.advance();
		int prevStart = 0;
		int nextStart = flexer.getTokenLength();
		
		final int regionStartOffset = region.getOffset();
		final int regionEnd = regionStartOffset + region.getLength();
		while (token != Token.EOF && nextStart <= regionStartOffset) {
			prevStart = nextStart;
			token = flexer.advance();
			nextStart += flexer.getTokenLength();
		}
		while (token != Token.EOF && nextStart < regionEnd) {
			token = flexer.advance();
			nextStart += flexer.getTokenLength();
		}
		return new TextRegion(prevStart, nextStart - prevStart);
	} catch(IOException e) {
		throw new RuntimeException(e); // cannot happen since StringReader doesn't throw IOException
	}
}
 
Example 8
Source File: RegionNodeModelFormatter.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IFormattedRegion format(final ICompositeNode root, final int offset, final int length) {
  final TokenStringBuffer buf = new TokenStringBuffer();
  final ITokenStream out = offset == 0 ? buf : new FilterStream(buf);
  final ITokenStream formatStream = formatter.createFormatterStream(null, out, false);
  if (!(formatStream instanceof IDelegatingTokenStream)) {
    return super.format(root, offset, length);
  }
  try {
    ITextRegion range;
    if (offset > 0) {
      int noffset = root.getText().lastIndexOf('\n', offset) + 1; // Keep the new line
      int nlength = length + (offset - noffset); // Always start in the beginning of the line
      range = nodeModelStreamer.feedTokenStream(formatStream, root, noffset, nlength);
    } else {
      range = nodeModelStreamer.feedTokenStream(formatStream, root, offset, length);
    }
    return new FormattedRegion(range.getOffset(), range.getLength(), buf.toString());
  } catch (IOException e) {
    // this should never happen since TokenStringBuffer doesn't throw IOEs.
    throw new RuntimeException(e); // NOPMD
  }
}
 
Example 9
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 10
Source File: N4JSRenameStrategy.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Custom logics for creating text edits for definitions of composed members
 */
@Override
public void createDeclarationUpdates(String newName, ResourceSet resourceSet,
		IRefactoringUpdateAcceptor updateAcceptor) {

	EObject targetElement = resourceSet.getEObject(getTargetElementOriginalURI(), true);
	if (TypeModelUtils.isComposedTElement(targetElement)) {
		// If target element is a composed element, create updates for its constituent members
		List<TMember> constituentMembers = ((TMember) targetElement).getConstituentMembers();
		for (TMember constituentMember : constituentMembers) {
			String text = newName;
			EAttribute att = getNameAttribute(constituentMember);
			ITextRegion nameRegion = getOriginalNameRegion(constituentMember, att);
			ReplaceEdit replaceEdit = new ReplaceEdit(nameRegion.getOffset(), nameRegion.getLength(), text);
			updateAcceptor.accept(EcoreUtil.getURI(constituentMember).trimFragment(),
					replaceEdit);
		}
	} else {
		updateAcceptor.accept(getTargetElementOriginalURI().trimFragment(), getDeclarationTextEdit(newName));
	}
}
 
Example 11
Source File: FormatterTester.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected ArrayList<TextReplacement> createMissingEditReplacements(XtextResource res, Collection<TextReplacement> edits, int offset,
		int length) {
	Set<Integer> offsets = IterableExtensions
			.toSet(Iterables.transform(edits, (TextReplacement it) -> Integer.valueOf(it.getOffset())));
	ArrayList<TextReplacement> result = new ArrayList<>();
	int lastOffset = 0;
	IParseResult parseResult = res.getParseResult();
	if (parseResult != null) {
		ICompositeNode rootNode = parseResult.getRootNode();
		if (rootNode != null) {
			for (ILeafNode leaf : rootNode.getLeafNodes()) {
				if (!leaf.isHidden() || !StringExtensions.isNullOrEmpty(leaf.getText().trim())) {
					ITextRegion leafRegion = leaf.getTextRegion();
					if (lastOffset >= offset && leafRegion.getOffset() <= offset + length && !offsets.contains(Integer.valueOf(lastOffset))) {
						result.add(new TextReplacement(lastOffset, leafRegion.getOffset() - lastOffset, "!!"));
					}
					lastOffset = leafRegion.getOffset() + leafRegion.getLength();
				}
			}
		}
	}
	return result;
}
 
Example 12
Source File: AbstractEObjectHover.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Call this method only from within an IUnitOfWork
 */
protected Pair<EObject, IRegion> getXtextElementAt(XtextResource resource, final int offset) {
	// check for cross reference
	EObject crossLinkedEObject = eObjectAtOffsetHelper.resolveCrossReferencedElementAt(resource, offset);
	if (crossLinkedEObject != null) {
		if (!crossLinkedEObject.eIsProxy()) {
			IParseResult parseResult = resource.getParseResult();
			if (parseResult != null) {
				ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset);
				if(leafNode != null && leafNode.isHidden() && leafNode.getOffset() == offset) {
					leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset - 1);
				}
				if (leafNode != null) {
					ITextRegion leafRegion = leafNode.getTextRegion();
					return Tuples.create(crossLinkedEObject, (IRegion) new Region(leafRegion.getOffset(), leafRegion.getLength()));
				}
			}
		}
	} else {
		EObject o = eObjectAtOffsetHelper.resolveElementAt(resource, offset);
		if (o != null) {
			ITextRegion region = locationInFileProvider.getSignificantTextRegion(o);
			final IRegion region2 = new Region(region.getOffset(), region.getLength());
			if (TextUtilities.overlaps(region2, new Region(offset, 0)))
				return Tuples.create(o, region2);
		}
	}
	return null;
}
 
Example 13
Source File: AbstractSourceView.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void setSelection(ITextRegion textSelection, boolean reveal) {
	StyledText text = getSourceViewer().getTextWidget();
	if (text.getText().length() >= textSelection.getOffset() + textSelection.getLength()) {
		getSourceViewer().setSelection(new TextSelection(textSelection.getOffset(), textSelection.getLength()),
				reveal);
	}
}
 
Example 14
Source File: DefaultFoldingRegionProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.8
 */
protected void computeObjectFolding(EObject eObject, IFoldingRegionAcceptor<ITextRegion> foldingRegionAcceptor, boolean initiallyFolded) {
	ITextRegion region = locationInFileProvider.getFullTextRegion(eObject);
	if (region != null) {
		ITextRegion significant = locationInFileProvider.getSignificantTextRegion(eObject);
		if (significant == null)
			throw new NullPointerException("significant region may not be null");
		int offset = region.getOffset();
		((IFoldingRegionAcceptorExtension<ITextRegion>)foldingRegionAcceptor).accept(offset, region.getLength(), initiallyFolded, significant);
	}
}
 
Example 15
Source File: ValidatingRichStringAcceptor.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected void resetCurrentOffset(/* @Nullable */ RichStringLiteral origin) {
	if (root == null)
		root = origin;
	if (origin != null && origin != recent) {
		if (wasCurrentOffset == -1)
			wasCurrentOffset = currentOffset;
		int diff = lastOffsetOfLiteral - currentOffset;
		// no actions are involved, we are interested in the real node
		recent = origin;
		List<INode> featureNodes = NodeModelUtils.findNodesForFeature(origin,
				XbasePackage.Literals.XSTRING_LITERAL__VALUE);
		if (featureNodes.size() == 1) {
			INode node = featureNodes.get(0);
			ITextRegion textRegion = node.getTextRegion();
			currentOffset = textRegion.getOffset();
			String nodeText = node.getText();
			if (nodeText.endsWith("'''")) {
				lastOffsetOfLiteral = currentOffset + textRegion.getLength() - 3;
			} else if (nodeText.endsWith("''")) {
				lastOffsetOfLiteral = currentOffset + textRegion.getLength() - 2;
			} else if (nodeText.endsWith("'") || nodeText.endsWith("\u00AB")) {
				lastOffsetOfLiteral = currentOffset + textRegion.getLength() - 1;
			}
			if (nodeText.charAt(0) == '\'') {
				currentOffset += 3;
			} else {
				currentOffset += 1;
			}
		}
		currentOffset -= diff;
	}
}
 
Example 16
Source File: ImportSectionRegionUtil.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public ITextRegion addLeadingWhitespace(ITextRegion textRegion, XtextResource resource) {
	String text = resource.getParseResult().getRootNode().getText();
	int offset = textRegion.getOffset();
	int length = textRegion.getLength();
	while(offset > 0 && Character.isWhitespace(text.charAt(offset-1)) ){
		--offset;
		++length;
	}
	return new TextRegion(offset, length);
}
 
Example 17
Source File: TypeUsageCollector.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void acceptPreferredType(EObject owner, EReference referenceToTypeOrMember) {
	ITextRegion refRegion = locationInFileProvider.getFullTextRegion(owner, referenceToTypeOrMember, 0);
	if (refRegion.getLength() > 0) {
		IParseResult parseResult = resource.getParseResult();
		if(parseResult != null) {
			String completeText = parseResult.getRootNode().getText();
			String refText = completeText.substring(refRegion.getOffset(), refRegion.getOffset() + refRegion.getLength());
			PreferredType preferredType = findPreferredType(owner, referenceToTypeOrMember, refText);
			if (preferredType != null) {
				if (preferredType.referencedType != null) {
					acceptType(preferredType.referencedType, preferredType.usedType, refRegion);
				} else {
					String suffix = refText.substring(preferredType.unresolvedTypeName.length());
					if (owner instanceof XFeatureCall) {
						XFeatureCall featureCall = (XFeatureCall) owner; 
						if (typeLiteralHelper.isPotentialTypeLiteral(featureCall, null)) {
							XAbstractFeatureCall root = typeLiteralHelper.getRootTypeLiteral(featureCall);
							if (root != null) {
								ITextRegion region = locationInFileProvider.getSignificantTextRegion(root);
								if (region.getOffset() == refRegion.getOffset()) {
									suffix = completeText.substring(region.getOffset(), region.getOffset() + region.getLength());
									suffix = suffix.substring(preferredType.unresolvedTypeName.length());
									refRegion = region;
								}
							}
						}
					}
					acceptUnresolvedType(preferredType.unresolvedTypeName, suffix, refRegion);
				}
			}
		}
	}
}
 
Example 18
Source File: ExtractMethodRefactoring.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected ITextRegion getExpressionsRegion() {
	ITextRegion firstRegion = expressionUtil.getTextRegion(firstExpression);
	ITextRegion lastRegion = expressionUtil.getTextRegion(lastExpression);
	ITextRegion expressionRegion = new TextRegion(firstRegion.getOffset(), lastRegion.getOffset()
			+ lastRegion.getLength() - firstRegion.getOffset());
	return expressionRegion;
}
 
Example 19
Source File: ParameterContextInformationProvider.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void getContextInformation(ContentAssistContext context, IContextInformationAcceptor acceptor) {
	XExpression containerCall = getContainerCall(eObjectAtOffsetHelper.resolveContainedElementAt(context.getResource(), context.getOffset()));
	LightweightTypeReferenceFactory factory = proposalProvider.getTypeConverter(context.getResource());
	if (containerCall != null) {
		ICompositeNode containerCallNode = NodeModelUtils.findActualNodeFor(containerCall);
		ITextRegion containerCallRegion = containerCallNode.getTextRegion();
		if(containerCallRegion.getOffset() > context.getOffset()
				|| containerCallRegion.getOffset() + containerCallRegion.getLength() < context.getOffset()) 
			return;
		JvmIdentifiableElement calledFeature = getCalledFeature(containerCall);
		if (calledFeature instanceof JvmExecutable) {
			if(getParameterListOffset(containerCall) > context.getOffset()) 
				return;
			ParameterData parameterData = new ParameterData();
			IScope scope = getScope(containerCall);
			QualifiedName qualifiedName = QualifiedName.create(getCalledFeatureName(containerCall));
			boolean candidatesFound = false;
			for (IEObjectDescription element : scope.getElements(qualifiedName)) {
				if (element instanceof IIdentifiableElementDescription) {
					IIdentifiableElementDescription featureDescription = (IIdentifiableElementDescription) element;
					JvmIdentifiableElement featureCandidate = featureDescription.getElementOrProxy();
					if (featureCandidate instanceof JvmExecutable) {
						JvmExecutable executable = (JvmExecutable) featureCandidate;
						if(!executable.getParameters().isEmpty()) {
							StyledString styledString = new StyledString();
							proposalProvider.appendParameters(styledString, executable,
									featureDescription.getNumberOfIrrelevantParameters(), factory);
							parameterData.addOverloaded(styledString.toString(), executable.isVarArgs());
							candidatesFound = true;
						}
					}
				}
			}
			if (candidatesFound) {
				StyledString displayString = proposalProvider.getStyledDisplayString((JvmExecutable) calledFeature, true, 0, 
						qualifiedNameConverter.toString(qualifiedNameProvider.getFullyQualifiedName(calledFeature)), 
						calledFeature.getSimpleName(), factory);
				ParameterContextInformation parameterContextInformation = new ParameterContextInformation(
						parameterData, displayString.toString(), getParameterListOffset(containerCall), context.getOffset());
				acceptor.accept(parameterContextInformation);
			}
		}
	}
}
 
Example 20
Source File: AstSelectionProvider.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected int getEndOffset(ITextRegion region) {
	return region.getOffset() + region.getLength();
}