org.eclipse.xtext.util.ITextRegion Java Examples
The following examples show how to use
org.eclipse.xtext.util.ITextRegion.
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: RegionNodeModelFormatter.java From dsl-devkit with Eclipse Public License 1.0 | 6 votes |
@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 #2
Source File: N4JSRenameStrategy.java From n4js with Eclipse Public License 1.0 | 6 votes |
/** * Override this method to handle the case in which PropertyNameOwner has a LiteralOrComputedPropertyName child node * that contains 'literalName' to be renamed */ @Override protected ITextRegion getOriginalNameRegion(final EObject targetElement, EAttribute nameAttribute) { if (targetElement instanceof SyntaxRelatedTElement) { EObject nameElement = ((SyntaxRelatedTElement) targetElement).getAstElement(); // PropertyNameOwner has a LiteralOrComputedPropertyName child node that contains 'literalName' to be // renamed if (nameElement instanceof PropertyNameOwner) { nameElement = ((PropertyNameOwner) nameElement).getDeclaredName(); EAttribute nAttribute = SimpleAttributeResolver.newResolver(String.class, "literalName") .getAttribute(nameElement); return this.getOriginalNameRegion(nameElement, nAttribute); } } return super.getOriginalNameRegion(targetElement, nameAttribute); }
Example #3
Source File: OutlineWithEditorLinker.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
protected void selectInTreeView(ISelection selection) { if (selection instanceof ITextSelection && !treeViewer.getTree().isDisposed()) { ITextSelection textSelection = (ITextSelection) selection; ITextRegion selectedTextRegion = new TextRegion(textSelection.getOffset(), textSelection.getLength()); Object input = treeViewer.getInput(); if (input instanceof IOutlineNode) { try { IOutlineNode nodeToBeSelected = findBestNode((IOutlineNode) input, selectedTextRegion); if (nodeToBeSelected != null) treeViewer.setSelection(new StructuredSelection(nodeToBeSelected)); } catch(Exception exc) { // ignore, editor can have a different state than the tree } } } }
Example #4
Source File: AstSelectionProvider.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
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 #5
Source File: ExpressionUtil.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
/** * @return whether the given selection is zero length */ protected boolean isBeginOfExpression(INode node) { ITextRegion textRegion = node.getTextRegion(); if (textRegion.getLength() == 0) return false; char firstChar = node.getText().charAt(0); return Character.isLetterOrDigit(firstChar) || firstChar == '\'' || firstChar == '"' || firstChar == '[' || firstChar == '(' || firstChar == '{' || firstChar == '#' || firstChar == '@' ; }
Example #6
Source File: OutlineWithEditorLinker.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
protected IOutlineNode findBestNode(IOutlineNode input, ITextRegion selectedTextRegion) { ITextRegion textRegion = input.getFullTextRegion(); if (textRegion == null || textRegion.contains(selectedTextRegion)) { IOutlineNode currentBestNode = input; for (IOutlineNode child : input.getChildren()) { IOutlineNode candidate = findBestNode(child, selectedTextRegion); if (candidate != null && (currentBestNode.getFullTextRegion() == null || candidate.getFullTextRegion() != null && currentBestNode.getFullTextRegion().getLength() >= candidate.getFullTextRegion().getLength())) { currentBestNode = candidate; } } return currentBestNode; } return null; }
Example #7
Source File: DefaultReferenceUpdater.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
protected void createReferenceUpdate(EObject referringElement, URI referringResourceURI, EReference reference, int indexInList, EObject newTargetElement, IRefactoringUpdateAcceptor updateAcceptor) { if (!transientValueService.isValueInListTransient(referringElement, indexInList, reference)) { ITextRegion referenceTextRegion = locationInFileProvider.getFullTextRegion(referringElement, reference, indexInList); if (referenceTextRegion != null) { CrossReference crossReference = getCrossReference(referringElement, referenceTextRegion.getOffset()); if (crossReference != null) { RefTextEvaluator refTextComparator = getRefTextEvaluator(referringElement, referringResourceURI, reference, indexInList, newTargetElement); String newReferenceText = crossReferenceSerializer.getCrossRefText(referringElement, crossReference, newTargetElement, refTextComparator, referenceTextRegion, updateAcceptor.getRefactoringStatus()); if (newReferenceText == null) { newReferenceText = resolveNameConflict(referringElement, reference, newTargetElement, updateAcceptor); } if (newReferenceText == null) { updateAcceptor.getRefactoringStatus().add(RefactoringStatus.ERROR, "Refactoring introduces a name conflict.", referringElement, referenceTextRegion); } createTextChange(referenceTextRegion, newReferenceText, referringElement, newTargetElement, reference, referringResourceURI, updateAcceptor); } } } }
Example #8
Source File: DefaultSemanticHighlightingCalculator.java From xtext-core with Eclipse Public License 2.0 | 6 votes |
/** * Highlights the non-hidden parts of {@code node} with the styles given by the {@code styleIds} */ protected void highlightNode(IHighlightedPositionAcceptor acceptor, INode node, String... styleIds) { if (node == null) return; if (node instanceof ILeafNode) { ITextRegion textRegion = node.getTextRegion(); acceptor.addPosition(textRegion.getOffset(), textRegion.getLength(), styleIds); } else { for (ILeafNode leaf : node.getLeafNodes()) { if (!leaf.isHidden()) { ITextRegion leafRegion = leaf.getTextRegion(); acceptor.addPosition(leafRegion.getOffset(), leafRegion.getLength(), styleIds); } } } }
Example #9
Source File: DefaultNodeModelFormatter.java From xtext-core with Eclipse Public License 2.0 | 6 votes |
@Override public IFormattedRegion format(ICompositeNode root, int offset, int length) { String indent = getIndentation(root, offset); TokenStringBuffer buf = new TokenStringBuffer(); ITokenStream out = offset == 0 ? buf : new FilterFirstWhitespaceStream(buf); ITokenStream fmt; if (formatter instanceof IFormatterExtension) { EObject semanticElement = NodeModelUtils.findActualSemanticObjectFor(root); if (semanticElement != null) fmt = ((IFormatterExtension) formatter).createFormatterStream(semanticElement, indent, out, false); else { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=380406 ITextRegion rootRegion = root.getTextRegion(); return new FormattedRegion(rootRegion.getOffset(), rootRegion.getLength(), root.getText()); } } else fmt = formatter.createFormatterStream(indent, out, false); try { ITextRegion range = nodeModelStreamer.feedTokenStream(fmt, 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); } }
Example #10
Source File: XtendQuickfixProvider.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
protected void replaceKeyword(Keyword keyword, String replacement, EObject container, IXtextDocument document) throws BadLocationException { ICompositeNode node = NodeModelUtils.findActualNodeFor(container); if (node != null) { for (ILeafNode leafNode : node.getLeafNodes()) { if (leafNode.getGrammarElement() == keyword) { ITextRegion leafRegion = leafNode.getTextRegion(); String actualReplacement = replacement; if (!Character.isWhitespace(document.getChar(leafRegion.getOffset() - 1))) { actualReplacement = " " + replacement; } document.replace(leafRegion.getOffset(), leafRegion.getLength(), actualReplacement); } } } }
Example #11
Source File: XbaseLocationInFileProviderTest.java From xtext-extras with Eclipse Public License 2.0 | 5 votes |
@Test public void testStaticFeatureCall_10() throws Exception { String text = "java.util.Collections::emptyList"; XMemberFeatureCall featureCall = castedExpression(text); ITextRegion region = locationInFileProvider.getFullTextRegion(featureCall, XbasePackage.Literals.XMEMBER_FEATURE_CALL__MEMBER_CALL_TARGET, 0); String significant = text.substring(region.getOffset(), region.getOffset() + region.getLength()); assertEquals("java.util.Collections", significant); }
Example #12
Source File: TypeChooser.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
protected void revealInEditor(XtextEditor activeXtextEditor, Iterable<TypeUsage> usages, final XtextResource resource) { boolean isRevealUsages = activeXtextEditor.getDocument().priorityReadOnly(new IUnitOfWork<Boolean, XtextResource>() { @Override public Boolean exec(XtextResource state) throws Exception { return state.getURI().equals(resource.getURI()); } }); if(isRevealUsages) { originalSelection = activeXtextEditor.getSelectionProvider().getSelection(); ITextRegion firstOccurrence = usages.iterator().next().getTextRegion(); activeXtextEditor.selectAndReveal(firstOccurrence.getOffset(), firstOccurrence.getLength()); } }
Example #13
Source File: AstSelectionProvider.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
protected ITextRegion getRegion(Pair<EObject, EObject> selection) { final ITextRegion firstRegion = getTextRegion(selection.getFirst()); if (selection.getFirst() == selection.getSecond()) { return firstRegion; } ITextRegion secondRegion = getTextRegion(selection.getSecond()); return new TextRegion(firstRegion.getOffset(), getEndOffset(secondRegion) - firstRegion.getOffset()); }
Example #14
Source File: AstSelectionAction.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
protected IUnitOfWork<ITextRegion, XtextResource> createTextSelectionWork(final ITextRegion selection) { return new IUnitOfWork<ITextRegion, XtextResource>() { @Override public ITextRegion exec(XtextResource xtextResource) throws Exception { ITextRegion result = selection; if (xtextResource != null) { IParseResult parseResult = xtextResource.getParseResult(); if (parseResult != null) { result = internalSelect(xtextResource, selection); } } return result; } }; }
Example #15
Source File: AbstractTextSegment.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
@Override public ITextSegment merge(ITextRegion other) { if (contains(other)) return this; if (other instanceof ITextSegment && other.contains(this)) return (ITextSegment) other; int offset = getOffset(); int length = getLength(); int newOffset = Math.min(offset, other.getOffset()); int newLength = Math.max(offset + length, other.getOffset() + other.getLength()) - newOffset; return new TextSegment(getTextRegionAccess(), newOffset, newLength); }
Example #16
Source File: XbaseLocationInFileProviderTest.java From xtext-extras with Eclipse Public License 2.0 | 5 votes |
@Test public void testStaticFeatureCall_15() throws Exception { String text = "java::lang::Thread$State::NEW"; XMemberFeatureCall featureCall = castedExpression(text); ITextRegion region = locationInFileProvider.getSignificantTextRegion(featureCall, XbasePackage.Literals.XMEMBER_FEATURE_CALL__MEMBER_CALL_TARGET, 0); String significant = text.substring(region.getOffset(), region.getOffset() + region.getLength()); assertEquals("java::lang::Thread$State", significant); }
Example #17
Source File: ContentFormatter.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
protected void initRequest(IXtextDocument document, IRegion region, XtextResource resource, FormatterRequest request) { ITextRegion textRegion = new TextRegion(region.getOffset(), region.getLength()); request.setAllowIdentityEdits(false); request.setFormatUndefinedHiddenRegionsOnly(false); request.setRegions(singletonList(textRegion)); ITextRegionAccess tokenAccess = regionBuilder.forNodeModel(resource).create(); IPreferenceValues preferenceValues = preferencesProvider.getPreferenceValues(resource); request.setPreferences(TypedPreferenceValues.castOrWrap(preferenceValues)); request.setTextRegionAccess(tokenAccess); if (tokenAccess.hasSyntaxError()) request.setExceptionHandler(ExceptionAcceptor.IGNORING); else request.setExceptionHandler(ExceptionAcceptor.LOGGING); }
Example #18
Source File: OppositeFileOpenerContributor.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
protected ITextRegion getSelectedRegion(IEditorPart editor) { if (editor instanceof ITextEditor) { ISelection selection = ((ITextEditor) editor).getSelectionProvider().getSelection(); if (selection instanceof ITextSelection) { ITextSelection textSelection = (ITextSelection) selection; return new TextRegion(textSelection.getOffset(), textSelection.getLength()); } } return null; }
Example #19
Source File: DefaultFoldingRegionAcceptor.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
/** * @return a freshly created {@link FoldedPosition} * * @since 2.8 * @deprecated use / override {@link #newFoldedPosition(IRegion, ITextRegion)} instead */ @Deprecated protected FoldedPosition newFoldedPosition(IRegion region, ITextRegion significantRegion, boolean initiallyFolded) { if (region == null) return null; if (significantRegion != null) return new DefaultFoldedPosition(region.getOffset(), region.getLength(), significantRegion.getOffset() - region.getOffset(), significantRegion.getLength(), initiallyFolded); return new DefaultFoldedPosition(region.getOffset(), region.getLength(), DefaultFoldedPosition.UNSET, DefaultFoldedPosition.UNSET, initiallyFolded); }
Example #20
Source File: XtendExpressionUtilTest.java From xtext-xtend with Eclipse Public License 2.0 | 5 votes |
protected void assertExpressionSelected(final String modelWithSelectionMarkup, final String expectedSelection) { StringConcatenation _builder = new StringConcatenation(); _builder.append("class Foo {"); _builder.newLine(); _builder.append("\t"); _builder.append("def foo() "); _builder.append(modelWithSelectionMarkup, "\t"); _builder.newLineIfNotEmpty(); _builder.append("}"); _builder.newLine(); final String model = _builder.toString(); final String cleanedModel = model.replaceAll("\\$", ""); final XtendFile expression = this.parse(cleanedModel); final int selectionOffset = model.indexOf("$"); int _lastIndexOf = model.lastIndexOf("$"); int _minus = (_lastIndexOf - selectionOffset); final int selectionLength = (_minus - 1); Resource _eResource = expression.eResource(); TextSelection _textSelection = new TextSelection(selectionOffset, selectionLength); final XExpression selectedExpression = this.util.findSelectedExpression(((XtextResource) _eResource), _textSelection); final ITextRegion selectedRegion = this.locationInFileProvider.getFullTextRegion(selectedExpression); int _offset = selectedRegion.getOffset(); int _offset_1 = selectedRegion.getOffset(); int _length = selectedRegion.getLength(); int _plus = (_offset_1 + _length); Assert.assertEquals(expectedSelection, cleanedModel.substring(_offset, _plus)); }
Example #21
Source File: XbaseLocationInFileProviderTest.java From xtext-extras with Eclipse Public License 2.0 | 5 votes |
@Test public void testFeatureCall_05() throws Exception { String text = "((newArrayList('a')))"; XFeatureCall featureCall = castedExpression(text); ITextRegion region = locationInFileProvider.getFullTextRegion(featureCall); String textRegion = text.substring(region.getOffset(), region.getOffset() + region.getLength()); assertEquals("newArrayList('a')", textRegion); }
Example #22
Source File: AbstractEObjectHover.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
/** * 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 #23
Source File: XbaseLocationInFileProviderTest.java From xtext-extras with Eclipse Public License 2.0 | 5 votes |
@Test public void testFeatureCall_03() throws Exception { String text = "String::valueOf('a')"; XMemberFeatureCall featureCall = castedExpression(text); ITextRegion region = locationInFileProvider.getSignificantTextRegion(featureCall); String significant = text.substring(region.getOffset(), region.getOffset() + region.getLength()); assertEquals(text.substring(text.indexOf('v')), significant); }
Example #24
Source File: XbaseLocationInFileProviderTest.java From xtext-extras with Eclipse Public License 2.0 | 5 votes |
@Test public void testFeatureCall_01() throws Exception { String text = "newArrayList('a')"; XFeatureCall featureCall = castedExpression(text); ITextRegion region = locationInFileProvider.getSignificantTextRegion(featureCall); String significant = text.substring(region.getOffset(), region.getOffset() + region.getLength()); assertEquals(text, significant); }
Example #25
Source File: ExpressionUtilTest.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
protected void assertExpressionSelected(String modelWithSelectionMarkup, String expectedSelection) throws Exception { String cleanedModel = modelWithSelectionMarkup.replaceAll("\\$", ""); XExpression expression = parse(cleanedModel); int selectionOffset = modelWithSelectionMarkup.indexOf("$"); int selectionLength = modelWithSelectionMarkup.lastIndexOf("$") - selectionOffset - 1; XExpression selectedExpression = util.findSelectedExpression((XtextResource) expression.eResource(), new TextSelection(selectionOffset, selectionLength)); ITextRegion selectedRegion = locationInFileProvider.getFullTextRegion(selectedExpression); assertEquals(expectedSelection, cleanedModel.substring(selectedRegion.getOffset(), selectedRegion.getOffset() + selectedRegion.getLength())); }
Example #26
Source File: HoverService.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
protected HoverContext createContext(Document document, XtextResource resource, int offset) { EObject crossLinkedEObject = eObjectAtOffsetHelper.resolveCrossReferencedElementAt(resource, offset); if (crossLinkedEObject != null) { if (crossLinkedEObject.eIsProxy()) { return null; } IParseResult parseResult = resource.getParseResult(); if (parseResult == null) { return 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) { return null; } ITextRegion leafRegion = leafNode.getTextRegion(); return new HoverContext(document, resource, offset, leafRegion, crossLinkedEObject); } EObject element = eObjectAtOffsetHelper.resolveElementAt(resource, offset); if (element == null) { return null; } ITextRegion region = locationInFileProvider.getSignificantTextRegion(element); return new HoverContext(document, resource, offset, region, element); }
Example #27
Source File: AstSelectionProvider.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
public ITextRegion selectLast(XtextResource resource, ITextRegion currentEditorSelection) { if (selectionHistory.isEmpty()) { return ITextRegion.EMPTY_REGION; } if (!currentEditorSelection.equals(selectionHistory.pop())) { selectionHistory.clear(); return ITextRegion.EMPTY_REGION; } return selectionHistory.isEmpty() ? ITextRegion.EMPTY_REGION : selectionHistory.peek(); }
Example #28
Source File: XtendHighlightingCalculator.java From xtext-xtend with Eclipse Public License 2.0 | 5 votes |
@Override protected void highlightSpecialIdentifiers(ILeafNode leafNode, IHighlightedPositionAcceptor acceptor, TerminalRule idRule) { super.highlightSpecialIdentifiers(leafNode, acceptor, idRule); if (contextualKeywords != null && contextualKeywords.contains(leafNode.getGrammarElement())) { ITextRegion leafRegion = leafNode.getTextRegion(); acceptor.addPosition(leafRegion.getOffset(), leafRegion.getLength(), HighlightingStyles.DEFAULT_ID); } }
Example #29
Source File: DefaultFoldingRegionProvider.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
protected void computeObjectFolding(XtextResource xtextResource, IFoldingRegionAcceptor<ITextRegion> foldingRegionAcceptor) { IParseResult parseResult = xtextResource.getParseResult(); if(parseResult != null){ EObject rootASTElement = parseResult.getRootASTElement(); if(rootASTElement != null){ if (cancelIndicator.isCanceled()) throw new OperationCanceledException(); if (isHandled(rootASTElement)) { computeObjectFolding(rootASTElement, foldingRegionAcceptor); } if (shouldProcessContent(rootASTElement)) { TreeIterator<EObject> allContents = rootASTElement.eAllContents(); while (allContents.hasNext()) { if (cancelIndicator.isCanceled()) throw new OperationCanceledException(); EObject eObject = allContents.next(); if (isHandled(eObject)) { computeObjectFolding(eObject, foldingRegionAcceptor); } if (!shouldProcessContent(eObject)) { allContents.prune(); } } } } } }
Example #30
Source File: TypeUsages.java From xtext-extras with Eclipse Public License 2.0 | 5 votes |
public void addTypeUsage( JvmDeclaredType typeToImport, JvmDeclaredType usedType, ITextRegion textRegion, JvmMember context) { simpleName2types.put(typeToImport.getSimpleName(), typeToImport); types2usages.put(typeToImport, new TypeUsage(usedType, textRegion, context)); }