Java Code Examples for org.eclipse.xtext.nodemodel.INode#getOffset()
The following examples show how to use
org.eclipse.xtext.nodemodel.INode#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: DotSemanticHighlightingCalculator.java From gef with Eclipse Public License 2.0 | 6 votes |
private void provideHighlightingForHtmlString(INode node, IHighlightedPositionAcceptor acceptor) { // highlight the leading '<' symbol int openingSymbolOffset = node.getOffset(); acceptor.addPosition(openingSymbolOffset, 1, DotHighlightingConfiguration.HTML_TAG); // highlight the trailing '>' symbol int closingSymbolOffset = node.getOffset() + node.getText().length() - 1; acceptor.addPosition(closingSymbolOffset, 1, DotHighlightingConfiguration.HTML_TAG); // trim the leading '<' and trailing '>' symbols String htmlString = node.getText().substring(1, node.getText().length() - 1); // delegate the highlighting of the the html-label substring to the // corresponding sub-grammar highlighter DotSubgrammarHighlighter htmlLabelHighlighter = new DotSubgrammarHighlighter( DotActivator.ORG_ECLIPSE_GEF_DOT_INTERNAL_LANGUAGE_DOTHTMLLABEL); htmlLabelHighlighter.provideHightlightingFor(htmlString, node.getOffset() + 1, acceptor); }
Example 2
Source File: PackageJsonHyperlinkHelperExtension.java From n4js with Eclipse Public License 1.0 | 6 votes |
private Pair<SafeURI<?>, Region> hyperlinkToMainModule(JSONStringLiteral mainModuleJsonLiteral) { String mainModule = mainModuleJsonLiteral.getValue(); if (!Strings.isNullOrEmpty(mainModule)) { URI packageJsonLoc = mainModuleJsonLiteral.eResource().getURI(); IN4JSProject project = model.findProject(packageJsonLoc).orNull(); INode node = NodeModelUtils.getNode(mainModuleJsonLiteral); if (project != null && node != null) { Region region = new Region(node.getOffset() + 1, node.getLength() - 2); for (IN4JSSourceContainer sc : project.getSourceContainers()) { QualifiedName qualifiedName = QualifiedName.create(mainModule); SafeURI<?> mainModuleURI = sc.findArtifact(qualifiedName, Optional.of(N4JSGlobals.N4JS_FILE_EXTENSION)); if (mainModuleURI == null) { mainModuleURI = sc.findArtifact(qualifiedName, Optional.of(N4JSGlobals.N4JSX_FILE_EXTENSION)); } if (mainModuleURI != null) { return Tuples.pair(mainModuleURI, region); } } } } return null; }
Example 3
Source File: DotFoldingRegionProvider.java From gef with Eclipse Public License 2.0 | 6 votes |
private int getAttributeValueStartOffset(Attribute attribute) { ID attributeValue = attribute.getValue(); List<INode> nodes = NodeModelUtils.findNodesForFeature(attribute, DotPackage.Literals.ATTRIBUTE__VALUE); if (nodes.size() != 1) { System.err.println( "Exact 1 node is expected for the attribute value: " //$NON-NLS-1$ + attributeValue + ", but got " + nodes.size()); //$NON-NLS-1$ return 0; } INode node = nodes.get(0); int attributeValueStartOffset = node.getOffset(); if (attributeValue.getType() == ID.Type.HTML_STRING || attributeValue.getType() == ID.Type.QUOTED_STRING) { // +1 is needed because of the < symbol (indicating the // beginning of a html-like label) or " symbol (indicating the // beginning of a quoted string) attributeValueStartOffset++; } return attributeValueStartOffset; }
Example 4
Source File: PackageJsonHyperlinkHelperExtension.java From n4js with Eclipse Public License 1.0 | 6 votes |
private Pair<SafeURI<?>, Region> hyperlinkToProjectProperty(NameValuePair nvpDependency) { String projectName = nvpDependency.getName(); SafeURI<?> pdu = getProjectDescriptionLocationForName(new N4JSProjectName(projectName)); if (pdu != null) { List<INode> node = NodeModelUtils.findNodesForFeature(nvpDependency, JSONPackage.Literals.NAME_VALUE_PAIR__NAME); if (!node.isEmpty()) { INode nameNode = node.get(0); Region region = new Region(nameNode.getOffset() + 1, nameNode.getLength() - 2); return Tuples.pair(pdu, region); } } return null; }
Example 5
Source File: SolidityHyperlinkHelper.java From solidity-ide with Eclipse Public License 1.0 | 6 votes |
protected void createImportedNamespacesHyperlinksByOffset(XtextResource resource, int offset, IHyperlinkAcceptor acceptor) { INode node = NodeModelUtils.findLeafNodeAtOffset(resource.getParseResult().getRootNode(), offset); if (node != null) { List<INode> importNodes = NodeModelUtils.findNodesForFeature(node.getSemanticElement(), SolidityPackage.Literals.IMPORT_DIRECTIVE__IMPORTED_NAMESPACE); if (importNodes != null && !importNodes.isEmpty()) { for (INode importNode : importNodes) { ImportDirective importElement = (ImportDirective) importNode.getSemanticElement(); URI targetURI = getFileURIOfImport(importElement); XtextHyperlink result = getHyperlinkProvider().get(); result.setURI(targetURI); Region region = new Region(importNode.getOffset(), importNode.getLength()); result.setHyperlinkRegion(region); result.setHyperlinkText(targetURI.toString()); acceptor.accept(result); } } } }
Example 6
Source File: DotSemanticHighlightingCalculator.java From gef with Eclipse Public License 2.0 | 6 votes |
private void provideHighlightingForArrowTypeString(INode node, IHighlightedPositionAcceptor acceptor) { String arrowTypeString = node.getText(); int offset = node.getOffset(); String suffix = null; // quoted attribute value if (arrowTypeString.length() > 0 && arrowTypeString.charAt(0) == '"') { // trim the leading '"' and trailing '"' symbols arrowTypeString = arrowTypeString.substring(1, arrowTypeString.length() - 1); // increase offset correspondingly offset++; // adapt highlighting to quoted style suffix = DotHighlightingConfiguration.QUOTED_SUFFIX; } // delegate the highlighting of the the arrowType substring to the // corresponding sub-grammar highlighter DotSubgrammarHighlighter arrowTypeHighlighter = new DotSubgrammarHighlighter( DotActivator.ORG_ECLIPSE_GEF_DOT_INTERNAL_LANGUAGE_DOTARROWTYPE); arrowTypeHighlighter.provideHightlightingFor(arrowTypeString, offset, acceptor, suffix); }
Example 7
Source File: XtendImportsConfiguration.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
@Override public int getImportSectionOffset(XtextResource resource) { XtendFile xtendFile = getXtendFile(resource); if(xtendFile != null) { if(!isEmpty(xtendFile.getPackage())) { List<INode> nodes = NodeModelUtils.findNodesForFeature(xtendFile, XtendPackage.Literals.XTEND_FILE__PACKAGE); if(!nodes.isEmpty()) { INode lastNode = nodes.get(nodes.size()-1); INode nextSibling = lastNode.getNextSibling(); while(nextSibling instanceof ILeafNode && ((ILeafNode)nextSibling).isHidden()) nextSibling = nextSibling.getNextSibling(); if(nextSibling != null && ";".equals(nextSibling.getText())) return nextSibling.getOffset() + 1; else return lastNode.getTotalEndOffset(); } } } return 0; }
Example 8
Source File: HiddenLeafAccess.java From xtext-extras with Eclipse Public License 2.0 | 5 votes |
public HiddenLeafs getHiddenLeafsBefore(final INode node) { HiddenLeafs _xblockexpression = null; { final Function1<ILeafNode, Boolean> _function = (ILeafNode it) -> { boolean _isHidden = it.isHidden(); return Boolean.valueOf((!_isHidden)); }; final ILeafNode start = this._nodeModelAccess.findNextLeaf(node, _function); final List<ILeafNode> nodes = this.findPreviousHiddenLeafs(start); HiddenLeafs _xifexpression = null; if ((start != null)) { int _xifexpression_1 = (int) 0; boolean _isEmpty = nodes.isEmpty(); if (_isEmpty) { _xifexpression_1 = start.getOffset(); } else { _xifexpression_1 = IterableExtensions.<ILeafNode>head(nodes).getOffset(); } _xifexpression = this.newHiddenLeafs(_xifexpression_1, nodes); } else { int _offset = 0; if (node!=null) { _offset=node.getOffset(); } _xifexpression = new HiddenLeafs(_offset); } _xblockexpression = _xifexpression; } return _xblockexpression; }
Example 9
Source File: ExpressionUtil.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
/** * @return the smallest single expression containing the selection. */ public XExpression findSelectedExpression(XtextResource resource, ITextSelection selection) { IParseResult parseResult = resource.getParseResult(); if (parseResult != null) { ICompositeNode rootNode = parseResult.getRootNode(); INode node = NodeModelUtils.findLeafNodeAtOffset(rootNode, selection.getOffset()); if (node == null) { return null; } if (isHidden(node)) { if (selection.getLength() > node.getLength()) { node = NodeModelUtils.findLeafNodeAtOffset(rootNode, node.getEndOffset()); } else { node = NodeModelUtils.findLeafNodeAtOffset(rootNode, selection.getOffset() - 1); } } else if (node.getOffset() == selection.getOffset() && !isBeginOfExpression(node)) { node = NodeModelUtils.findLeafNodeAtOffset(rootNode, selection.getOffset() - 1); } if(node != null) { EObject currentSemanticElement = NodeModelUtils.findActualSemanticObjectFor(node); while (!(contains(currentSemanticElement, node, selection) && currentSemanticElement instanceof XExpression)) { node = nextNodeForFindSelectedExpression(currentSemanticElement, node, selection); if(node == null) return null; currentSemanticElement = NodeModelUtils.findActualSemanticObjectFor(node); } return (XExpression) currentSemanticElement; } } return null; }
Example 10
Source File: XbaseProposalProvider.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
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 11
Source File: DefaultReferenceUpdater.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
protected CrossReference getCrossReference(EObject referringElement, int offset) { ICompositeNode node = NodeModelUtils.findActualNodeFor(referringElement); if (node != null) { Iterator<INode> iter = node.getAsTreeIterable().iterator(); while (iter.hasNext()) { INode childNode = iter.next(); if (childNode.getOffset() >= offset && childNode.getGrammarElement() instanceof CrossReference) return (CrossReference) childNode.getGrammarElement(); } } return null; }
Example 12
Source File: StatemachineFoldingRegionProvider.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
/** * 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 13
Source File: DomainmodelHyperlinkHelper.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
@Override public void createHyperlinksByOffset(XtextResource resource, int offset, IHyperlinkAcceptor acceptor) { super.createHyperlinksByOffset(resource, offset, acceptor); EObject eObject = getEObjectAtOffsetHelper().resolveElementAt(resource, offset); if (eObject instanceof Entity) { List<INode> nodes = NodeModelUtils.findNodesForFeature(eObject, DomainmodelPackage.Literals.ABSTRACT_ELEMENT__NAME); if (!nodes.isEmpty()) { INode node = nodes.get(0); if (node.getOffset() <= offset && node.getOffset() + node.getLength() > offset) { String qualifiedJavaName = qualifiedNameConverter.toString(qualifiedNameProvider.getFullyQualifiedName(eObject)); if (resource.getResourceSet() instanceof XtextResourceSet) { XtextResourceSet resourceSet = (XtextResourceSet) resource.getResourceSet(); Object uriContext = resourceSet.getClasspathURIContext(); if (uriContext instanceof IJavaProject) { IJavaProject javaProject = (IJavaProject) uriContext; try { IType type = javaProject.findType(qualifiedJavaName); if (type != null) { JdtHyperlink hyperlink = jdtHyperlinkProvider.get(); hyperlink.setJavaElement(type); hyperlink.setTypeLabel("Navigate to generated source code."); hyperlink.setHyperlinkText("Go to type " + qualifiedJavaName); hyperlink.setHyperlinkRegion((IRegion) new Region(node.getOffset(), node.getLength())); acceptor.accept(hyperlink); } } catch(JavaModelException e) { logger.error(e.getMessage(), e); } } } } } } }
Example 14
Source File: AbstractParseTreeConstructor.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
protected void assignNodesByMatching(Map<EObject, AbstractToken> eObject2Token, ICompositeNode rootNode, Map<ILeafNode, EObject> comments) throws IOException { NodeIterator contents = new NodeIterator(rootNode); while (contents.hasNext()) { INode containedNode = contents.next(); AbstractRule rule = containedNode.getGrammarElement() instanceof AbstractRule ? (AbstractRule) containedNode .getGrammarElement() : null; if (hiddenTokenHelper.isWhitespace(rule)) continue; else if (containedNode instanceof ILeafNode && hiddenTokenHelper.isComment(rule)) assignComment((ILeafNode) containedNode, eObject2Token, comments); else if (tokenUtil.isToken(containedNode)) { Pair<List<ILeafNode>, List<ILeafNode>> leadingAndTrailingHiddenTokens = tokenUtil .getLeadingAndTrailingHiddenTokens(containedNode); for (ILeafNode leadingHiddenNode : leadingAndTrailingHiddenTokens.getFirst()) { if (tokenUtil.isCommentNode(leadingHiddenNode)) { assignComment(leadingHiddenNode, eObject2Token, comments); } } assignTokenByMatcher(containedNode, eObject2Token); for (ILeafNode trailingHiddenNode : leadingAndTrailingHiddenTokens.getSecond()) { if (tokenUtil.isCommentNode(trailingHiddenNode)) { assignComment(trailingHiddenNode, eObject2Token, comments); } } contents.prune(); ICompositeNode parentNode = containedNode.getParent(); while (parentNode != null && assignTokenDirect(parentNode, eObject2Token)) parentNode = parentNode.getParent(); if (containedNode.getOffset() > rootNode.getEndOffset()) { break; } } } }
Example 15
Source File: N4JSQuickfixProvider.java From n4js with Eclipse Public License 1.0 | 5 votes |
/** * If a type declaration has Java-form such as 'int foo() {}', then the following quickfix proposed which transforms * it to colon style: 'foo(): int {}' It searches the bogus return type (which is 'int' in the example above) * beginning from the parent node (N4MethodDeclarationImpl) of the method declaration. The bogus return type removed * from the old position. A colon followed by the bogus return type added to the right side of the method name. */ @Fix(IssueCodes.TYS_INVALID_TYPE_SYNTAX) public void transformJavaTypeAnnotationToColonStyle(QuickfixContext context, ICodeActionAcceptor acceptor) { EObject element = getEObject(context); if (!(element instanceof ParameterizedTypeRef)) { return; } ParameterizedTypeRef typeRef = (ParameterizedTypeRef) element; if (!(typeRef.eContainer() instanceof N4MethodDeclaration)) { return; } ICompositeNode node = NodeModelUtils.getNode(element); ICompositeNode parentNode = findParentNodeWithSemanticElementOfType(node, N4MethodDeclaration.class); INode roundBracketNode = NodeModelUtilsN4.findKeywordNode(parentNode, ")"); List<INode> nodesForFeature = NodeModelUtils.findNodesForFeature(parentNode.getSemanticElement(), N4JSPackage.Literals.TYPED_ELEMENT__BOGUS_TYPE_REF); if (nodesForFeature.isEmpty()) { return; } INode bogusNode = nodesForFeature.get(0); Document doc = context.options.getDocument(); String stringOfBogusType = NodeModelUtilsN4.getTokenTextWithHiddenTokens(bogusNode); ILeafNode nodeAfterBogus = NodeModelUtils.findLeafNodeAtOffset(parentNode, bogusNode.getEndOffset()); int spaceAfterBogusLength = (nodeAfterBogus != null && nodeAfterBogus.getText().startsWith(" ")) ? 1 : 0; int offsetBogusType = bogusNode.getOffset(); int bogusTypeLength = stringOfBogusType.length(); int offsetRoundBracket = roundBracketNode.getTotalOffset(); List<TextEdit> textEdits = new ArrayList<>(); // inserts the bogus type at the new location (behind the closing round bracket) textEdits.add(replace(doc, offsetRoundBracket + 1, 0, ": " + stringOfBogusType)); // removes the bogus type and whitespace at the old location textEdits.add(replace(doc, offsetBogusType, bogusTypeLength + spaceAfterBogusLength, "")); acceptor.acceptQuickfixCodeAction(context, "Convert to colon style", textEdits); }
Example 16
Source File: DotHtmlLabelRenameStrategy.java From gef with Eclipse Public License 2.0 | 5 votes |
@Override public void createDeclarationUpdates(String newName, ResourceSet resourceSet, IRefactoringUpdateAcceptor updateAcceptor) { super.createDeclarationUpdates(newName, resourceSet, updateAcceptor); // perform renaming of the dependent element URI resourceURI = getTargetElementOriginalURI().trimFragment(); if (targetElement instanceof HtmlTag) { HtmlTag htmlTag = (HtmlTag) targetElement; if (!htmlTag.isSelfClosing()) { List<INode> nodes = NodeModelUtils.findNodesForFeature(htmlTag, HtmllabelPackage.Literals.HTML_TAG__CLOSE_NAME); if (nodes.size() == 1) { INode node = nodes.get(0); TextEdit referenceEdit = new ReplaceEdit(node.getOffset(), node.getLength(), newName); updateAcceptor.accept(resourceURI, referenceEdit); } else { System.err.println( "Exact 1 node is expected for the name of the html closing tag, but got " //$NON-NLS-1$ + nodes.size()); } } } }
Example 17
Source File: PackageJsonHyperlinkHelperExtension.java From n4js with Eclipse Public License 1.0 | 5 votes |
private Pair<SafeURI<?>, Region> hyperlinkToRequiredRTLibs(JSONStringLiteral mainModuleJsonLiteral) { String projectName = mainModuleJsonLiteral.getValue(); if (!Strings.isNullOrEmpty(projectName)) { SafeURI<?> pdu = getProjectDescriptionLocationForName(new N4JSProjectName(projectName)); INode node = NodeModelUtils.getNode(mainModuleJsonLiteral); if (pdu != null && node != null) { Region region = new Region(node.getOffset() + 1, node.getLength() - 2); return Tuples.pair(pdu, region); } } return null; }
Example 18
Source File: FlexerBasedJavaDocContentAssistContextFactory.java From xtext-xtend with Eclipse Public License 2.0 | 5 votes |
@Override public String getPrefix(INode node) { if(node != null) { int offsetInNode = getCompletionOffset() - node.getOffset(); String textInFront = node.getText().substring(0, offsetInNode); for (int i = offsetInNode - 1; i > 0; i--) { char c = textInFront.charAt(i); if (Character.isWhitespace(c)) { return textInFront.substring(i + 1); } } } return ""; }
Example 19
Source File: DotProposalProvider.java From gef with Eclipse Public License 2.0 | 4 votes |
private void proposeAttributeValues(String subgrammarName, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { INode currentNode = context.getCurrentNode(); String nodeText = currentNode.getText(); String prefix = context.getPrefix(); int offset = currentNode.getOffset(); String text = nodeText.trim(); if (!nodeText.contains(prefix)) { text = prefix; offset = context.getOffset() - prefix.length(); } else { boolean quoted = text.startsWith("\"") //$NON-NLS-1$ && text.endsWith("\""); //$NON-NLS-1$ boolean html = text.startsWith("<") && text.endsWith(">"); //$NON-NLS-1$ //$NON-NLS-2$ if (quoted || html) { if (quoted) { text = ID.fromString(text, Type.QUOTED_STRING).toValue(); } else { text = text.substring(1, text.length() - 1); } offset++; } } List<ConfigurableCompletionProposal> configurableCompletionProposals = new DotProposalProviderDelegator( subgrammarName).computeConfigurableCompletionProposals(text, context.getOffset() - offset); for (ConfigurableCompletionProposal configurableCompletionProposal : configurableCompletionProposals) { // adapt the replacement offset determined within the // sub-grammar context to be valid within the context of the // original text configurableCompletionProposal.setReplacementOffset(offset + configurableCompletionProposal.getReplacementOffset()); acceptor.accept(configurableCompletionProposal); } }
Example 20
Source File: ScriptError.java From openhab-core with Eclipse Public License 2.0 | 3 votes |
/** * 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(); }