org.eclipse.xtext.util.TextRegion Java Examples
The following examples show how to use
org.eclipse.xtext.util.TextRegion.
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: 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 #2
Source File: ImportsCollectorTests.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
private ImportsAcceptor.DefaultImportsAcceptor collect(final CharSequence xtendFile) { try { String contentAsString = xtendFile.toString(); int start = 0; int end = contentAsString.length(); int selector = contentAsString.indexOf("|"); if ((selector != (-1))) { start = selector; contentAsString = contentAsString.replaceFirst("\\|", ""); selector = contentAsString.indexOf("|"); end = contentAsString.length(); if ((selector != (-1))) { end = selector; contentAsString = contentAsString.replaceFirst("\\|", ""); } } final Resource resource = this.file(contentAsString).eResource(); final ImportsAcceptor.DefaultImportsAcceptor acceptor = new ImportsAcceptor.DefaultImportsAcceptor(); TextRegion _textRegion = new TextRegion(start, (end - start)); this.importsCollector.collectImports(((XtextResource) resource), _textRegion, acceptor); return acceptor; } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
Example #3
Source File: XtendHighlightingCalculatorTest.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
@Override public void addPosition(int offset, int length, String... ids) { if (logEnabled ) { System.out.print("acceptor.addPosition(" + (offset-22) + ", " + length); for(String id: ids) { System.out.print(", \"" + id + "\""); } System.out.println(");"); } assertTrue("length = " + length, length >= 0); TextRegion region = new TextRegion(offset, length); assertEquals(1, ids.length); // I deactivated the following check as it is to strict/to simple in the face of the new fine-grained coloring // assertFalse(region.toString() + " is not contained in " + expectedRegions, expectedRegions.isEmpty()); Collection<String> expectedIds = expectedRegions.get(region); if(strictMode && expectedIds.isEmpty()) fail("No Region for (offset: "+offset+", length : "+length+", id : "+ids[0]+") expected."); if(expectedIds.size() > 0) assertTrue("expected: " + expectedRegions.toString() + " but was: " + region + " (" + ids[0] + ")", expectedIds.contains(ids[0])); if(expectedIds.contains(ids[0])) expectedRegions.remove(region, ids[0]); Collection<String> unexpectedIds = explicitNotExpectedRegions.get(region); assertFalse("unexpected highlighting as position: " + region + " (" + ids[0] + ")", unexpectedIds.contains(ids[0])); }
Example #4
Source File: XtextResource.java From xtext-core with Eclipse Public License 2.0 | 6 votes |
public void update(int offset, int replacedTextLength, String newText) { if (!isLoaded()) { throw new IllegalStateException("You can't update an unloaded resource."); } try { isUpdating = true; IParseResult oldParseResult = parseResult; ReplaceRegion replaceRegion = new ReplaceRegion(new TextRegion(offset, replacedTextLength), newText); IParseResult newParseResult; ParserRule oldEntryPoint = NodeModelUtils.getEntryParserRule(oldParseResult.getRootNode()); if (entryPoint == null || entryPoint == oldEntryPoint) { newParseResult = getParser().reparse(oldParseResult, replaceRegion); } else { StringBuilder builder = new StringBuilder(oldParseResult.getRootNode().getText()); replaceRegion.applyTo(builder); newParseResult = getParser().parse(entryPoint, new StringReader(builder.toString())); } updateInternalState(oldParseResult, newParseResult); } finally { isUpdating = false; } }
Example #5
Source File: AbstractIdeTemplateProposalProvider.java From xtext-core with Eclipse Public License 2.0 | 6 votes |
@Override protected String getStringRepresentation(Object object) { if (object instanceof Variable) { String varName = ((Variable) object).name; int offset = context.getReplaceRegion().getOffset() + getCurrentOffset(); entry.getEditPositions().add(new TextRegion(offset, varName.length())); return varName; } else { if (object instanceof Cursor) { entry.setEscapePosition( Integer.valueOf(context.getReplaceRegion().getOffset() + getCurrentOffset())); return null; } else { return object.toString(); } } }
Example #6
Source File: FlexTokenRegionProvider.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
@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 #7
Source File: AbstractXtendFormatterTest.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
public void assertFormatted(final Procedure1<? super MapBasedPreferenceValues> cfg, final CharSequence expectation, final CharSequence toBeFormatted, final String prefix, final String postfix, final boolean allowErrors) { final Procedure1<FormatterTestRequest> _function = (FormatterTestRequest it) -> { final Procedure1<MapBasedPreferenceValues> _function_1 = (MapBasedPreferenceValues it_1) -> { it_1.<Integer>put(FormatterPreferenceKeys.maxLineWidth, Integer.valueOf(80)); it_1.<Boolean>put(XtendFormatterPreferenceKeys.keepOneLineMethods, Boolean.valueOf(false)); if (cfg!=null) { cfg.apply(it_1); } }; it.preferences(_function_1); it.setExpectation(((prefix + expectation) + postfix)); it.setToBeFormatted(((prefix + toBeFormatted) + postfix)); Collection<ITextRegion> _regions = it.getRequest().getRegions(); int _length = prefix.length(); int _length_1 = toBeFormatted.length(); TextRegion _textRegion = new TextRegion(_length, _length_1); _regions.add(_textRegion); it.setAllowSyntaxErrors(allowErrors); }; this.tester.assertFormatted(_function); }
Example #8
Source File: FlexTokenRegionProviderTest.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
@Test public void testTokenRegionContainsRegion() throws Exception { String modelAsString = "a1 / /* comment */ b2"; List<CommonToken> tokens = getTokens(modelAsString); for(int length=0; length < modelAsString.length(); ++length) { for(int offset = 0; offset + length < modelAsString.length(); ++offset) { ITextRegion tokenRegion = tokenRegionProvider.getTokenRegion(modelAsString, new TextRegion(offset, length)); // System.out.println(offset + ":" + length + " -> " + tokenRegion); CommonToken firstToken = findTokenStartingAt(tokenRegion.getOffset(), tokens); assertTrue(firstToken.getStartIndex() <= offset); if(tokenRegion.getLength() != 0) { CommonToken lastToken = findTokenStopingAt(tokenRegion.getOffset() + tokenRegion.getLength()-1, tokens); assertTrue(lastToken.getStopIndex() >= offset + length -1); } } } }
Example #9
Source File: AstSelectionProviderTest.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
@Test public void testSelectEnclosing() throws Exception { String zonk = "zonk{}"; String zink = "zink{}"; String baz = "baz{"+zonk+zink+"}"; String bar = "bar{}"; String all = "foo(baz){"+bar+baz+"}"; EObject model = super.getModel(all); AstSelectionProvider provider = get(AstSelectionProvider.class); final XtextResource res = (XtextResource) model.eResource(); int indexOfZonk = all.indexOf(zonk); ITextRegion selection = provider.selectEnclosing(res, new TextRegion(indexOfZonk,0)); assertEquals(region(all, "zonk"), selection); selection = provider.selectEnclosing(res, selection); assertEquals(region(all, zonk), selection); selection = provider.selectEnclosing(res, selection); assertEquals(region(all,baz), selection); selection = provider.selectEnclosing(res, selection); assertEquals(region(all,all), selection); assertEquals(ITextRegion.EMPTY_REGION, provider.selectEnclosing(res, selection)); }
Example #10
Source File: XtendTraceTests.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
@Test public void testNoEmptyTraces() throws Exception { testHelper.createFile("test/Foo.java", "package test;\n" + "public class Foo {\n" + " public void foo(Object it) {}\n" + " public void _foo(Object it) {}\n" + "}"); IFile sourceFile = testHelper.createFile("test/Zar", "package test\n" + "class Bar extends Foo {\n" + " def dispatch foo(String it) {print(it)}\n" + "}"); waitForBuild(); ITrace trace = traceInformation.getTraceToTarget(sourceFile); assertNotNull(trace); trace.getBestAssociatedLocation(new TextRegion(65, 0)); }
Example #11
Source File: EObjectAtOffsetTest.java From xtext-core with Eclipse Public License 2.0 | 6 votes |
@Test public void testGetCrossReferenceNode() throws Exception { String firstPart = "foo Foo1=X.Y foo Foo2=X.Y zonk bar Bar1 Foo1=X.Y"; String modelAsString = firstPart+",Foo2=X.Y"; XtextResource resource = getResourceFromString(modelAsString); INode node = eObjectAtOffsetHelper.getCrossReferenceNode(resource, new TextRegion(firstPart.length(), 0)); assertEquals(firstPart.length()-8, node.getOffset()); assertEquals(8, node.getLength()); assertNull(eObjectAtOffsetHelper.getCrossReferenceNode(resource, new TextRegion(firstPart.length(), 1))); node = eObjectAtOffsetHelper.getCrossReferenceNode(resource, new TextRegion(firstPart.length()+1, 0)); assertEquals(firstPart.length()+1, node.getOffset()); assertEquals(8, node.getLength()); node = eObjectAtOffsetHelper.getCrossReferenceNode(resource, new TextRegion(firstPart.length()+1, 5)); assertEquals(firstPart.length()+1, node.getOffset()); assertEquals(8, node.getLength()); node = eObjectAtOffsetHelper.getCrossReferenceNode(resource, new TextRegion(firstPart.length()+1, 8)); assertEquals(firstPart.length()+1, node.getOffset()); assertEquals(8, node.getLength()); assertNull(eObjectAtOffsetHelper.getCrossReferenceNode(resource, new TextRegion(firstPart.length()+1, 9))); }
Example #12
Source File: CheckHyperlinkHelper.java From dsl-devkit with Eclipse Public License 1.0 | 6 votes |
@Override public void createHyperlinksByOffset(final XtextResource resource, final int offset, final IHyperlinkAcceptor acceptor) { IEditorPart activeEditor = workbench.getActiveWorkbenchWindow().getActivePage().getActiveEditor(); if (activeEditor.getEditorInput() instanceof XtextReadonlyEditorInput) { INode crossRefNode = eObjectAtOffsetHelper.getCrossReferenceNode(resource, new TextRegion(offset, 0)); if (crossRefNode == null) { return; } EObject crossLinkedEObject = eObjectAtOffsetHelper.getCrossReferencedElement(crossRefNode); if (crossLinkedEObject != null && crossLinkedEObject.eClass().getEPackage() != CheckPackage.eINSTANCE) { return; } // if EPackage of referenced object is CheckPackage, try to provide hyperlinks: works for included catalogs } super.createHyperlinksByOffset(resource, offset, acceptor); }
Example #13
Source File: XbaseHyperLinkHelper.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
/** * If multiple links are requested, all ambiguous candidates are provided for feature and constructor calls. */ @Override public IHyperlink[] createHyperlinksByOffset(XtextResource resource, int offset, boolean createMultipleHyperlinks) { List<IHyperlink> links = Lists.newArrayList(); IHyperlinkAcceptor acceptor = new XbaseHyperlinkAcceptor(links, createMultipleHyperlinks); super.createHyperlinksByOffset(resource, offset, acceptor); INode crossRefNode = getEObjectAtOffsetHelper().getCrossReferenceNode(resource, new TextRegion(offset, 0)); if (crossRefNode == null) { this.createHyperlinksByOffset(resource, offset, acceptor); } else { this.createHyperlinksForCrossRef(resource, crossRefNode, acceptor); } if (!links.isEmpty()) return Iterables.toArray(links, IHyperlink.class); return null; }
Example #14
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 #15
Source File: FormattingService.java From xtext-core with Eclipse Public License 2.0 | 6 votes |
/** * @since 2.14 */ public List<TextEdit> format(XtextResource resource, Document document, int offset, int length, FormattingOptions options) { String indent = indentationInformation.getIndentString(); if (options != null) { if (options.isInsertSpaces()) { indent = Strings.padEnd("", options.getTabSize(), ' '); } } List<TextEdit> result = new ArrayList<>(); if (this.formatter2Provider != null) { MapBasedPreferenceValues preferences = new MapBasedPreferenceValues(); preferences.put("indentation", indent); List<ITextReplacement> replacements = format2(resource, new TextRegion(offset, length), preferences); for (ITextReplacement r : replacements) { result.add(toTextEdit(document, r.getReplacementText(), r.getOffset(), r.getLength())); } } return result; }
Example #16
Source File: UiToIdeContentProposalProvider.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
private ContentAssistContext getIdeContext(org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext cac) { Builder builder = builderProvider.get(); Region replaceRegion = cac.getReplaceRegion(); builder // .setPrefix(cac.getPrefix()) // .setSelectedText(cac.getSelectedText()) // .setRootModel(cac.getRootModel()) // .setRootNode(cac.getRootNode()) // .setCurrentModel(cac.getCurrentModel()) // .setPreviousModel(cac.getPreviousModel()) // .setCurrentNode(cac.getCurrentNode()) // .setLastCompleteNode(cac.getLastCompleteNode()) // .setOffset(cac.getOffset()) // .setReplaceRegion(new TextRegion(replaceRegion.getOffset(), replaceRegion.getLength())) // .setResource(cac.getResource()); cac.getFirstSetGrammarElements().forEach(grammarElement -> builder.accept(grammarElement)); return builder.toContext(); }
Example #17
Source File: ExtractMethodRefactoring.java From xtext-xtend with Eclipse Public License 2.0 | 5 votes |
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 #18
Source File: TokenRegionProviderTest.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
@Test public void testTokenMerge() throws Exception { String model = " "; ITextRegion tokenRegion = tokenRegionProvider.getTokenRegion(model, new TextRegion(1, 0)); assertEquals(0, tokenRegion.getOffset()); assertEquals(2, tokenRegion.getLength()); }
Example #19
Source File: TokenRegionProviderTest.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
@Test public void testTokenMerge_1() throws Exception { String model = " ab "; ITextRegion tokenRegion = tokenRegionProvider.getTokenRegion(model, new TextRegion(2, 0)); assertEquals(1, tokenRegion.getOffset()); assertEquals(2, tokenRegion.getLength()); }
Example #20
Source File: EObjectAtOffsetHelper.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
/** * @return the cross referenced EObject under, right or left to the cursor (in that order) or * <code>null</code> if there is no cross referenced object next to the offset. */ public EObject resolveCrossReferencedElementAt(XtextResource resource, int offset) { INode node = getCrossReferenceNode(resource, new TextRegion(offset, 0)); if (node != null) return getCrossReferencedElement(node); return null; }
Example #21
Source File: JavaBreakPointProvider.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
private ILocationInEclipseResource getJavaLocation(final IJavaStratumLineBreakpoint breakpoint) throws CoreException { IEclipseTrace javaTrace = getJavaTrace(breakpoint); if (javaTrace == null) return null; TextRegion textRegion = new TextRegion(breakpoint.getCharStart(), 0); ILocationInEclipseResource javaLocation = javaTrace.getBestAssociatedLocation(textRegion); if (javaLocation == null) return null; return javaLocation; }
Example #22
Source File: DefaultRenameElementHandler.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
protected boolean isRefactoringEnabled(IRenameElementContext renameElementContext, XtextResource resource) { ResourceSet resourceSet = resource.getResourceSet(); if (renameElementContext != null && resourceSet != null) { EObject targetElement = resourceSet.getEObject(renameElementContext.getTargetElementURI(), true); if (targetElement != null && !targetElement.eIsProxy()) { if(targetElement.eResource() == resource && renameElementContext.getTriggeringEditorSelection() instanceof ITextSelection) { ITextSelection textSelection = (ITextSelection) renameElementContext.getTriggeringEditorSelection(); ITextRegion selectedRegion = new TextRegion(textSelection.getOffset(), textSelection.getLength()); INode crossReferenceNode = eObjectAtOffsetHelper.getCrossReferenceNode(resource, selectedRegion); if(crossReferenceNode == null) { // selection is on the declaration. make sure it's the name ITextRegion significantRegion = locationInFileProvider.getSignificantTextRegion(targetElement); if(!significantRegion.contains(selectedRegion)) return false; } } IRenameStrategy.Provider renameStrategyProvider = globalServiceProvider.findService(targetElement, IRenameStrategy.Provider.class); try { if (renameStrategyProvider.get(targetElement, renameElementContext) != null) { return true; } else { IRenameStrategy2 strategy2 = globalServiceProvider.findService(targetElement, IRenameStrategy2.class); ISimpleNameProvider simpleNameProvider = globalServiceProvider.findService(targetElement, ISimpleNameProvider.class); return strategy2 != null && simpleNameProvider.canRename(targetElement); } } catch (NoSuchStrategyException e) { MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Cannot rename element", e.getMessage()); } } } return false; }
Example #23
Source File: HyperlinkHelper.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
public void createHyperlinksByOffset(XtextResource resource, int offset, IHyperlinkAcceptor acceptor) { INode crossRefNode = eObjectAtOffsetHelper.getCrossReferenceNode(resource, new TextRegion(offset, 0)); if (crossRefNode == null) return; EObject crossLinkedEObject = eObjectAtOffsetHelper.getCrossReferencedElement(crossRefNode); if (crossLinkedEObject != null && !crossLinkedEObject.eIsProxy()) { createHyperlinksTo(resource, crossRefNode, crossLinkedEObject, acceptor); } }
Example #24
Source File: NodeModelStreamer.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
@Override public ITextRegion feedTokenStream(ITokenStream out, ICompositeNode in, int offset, int length) throws IOException { List<INode> nodes = getLeafs(in, offset, offset + length); if (nodes.isEmpty()) return new TextRegion(in.getOffset(), 0); if (out instanceof ITokenStreamExtension) ((ITokenStreamExtension) out).init(findRootRuleForRegion(nodes.get(0))); boolean lastIsTokenOrComment = false; for (INode node : nodes) { boolean currentIsTokenOrComment = tokenUtil.isCommentNode(node) || tokenUtil.isToken(node); if (lastIsTokenOrComment && currentIsTokenOrComment) writeHiddenEmpty(out); lastIsTokenOrComment = currentIsTokenOrComment; if (node instanceof ILeafNode) { ILeafNode leaf = (ILeafNode) node; if (leaf.isHidden()) writeHidden(out, leaf); else writeSemantic(out, leaf); } else if (node instanceof ICompositeNode) writeSemantic(out, (ICompositeNode) node); } out.flush(); int rStart = nodes.get(0).getOffset(); int rLength = nodes.get(nodes.size() - 1).getEndOffset() - rStart; return new TextRegion(rStart, rLength); }
Example #25
Source File: TokenRegionProviderTest.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
@Test public void testTokenSplit() throws Exception { String model = " a b "; ITextRegion tokenRegion = tokenRegionProvider.getTokenRegion(model, new TextRegion(2, 1)); assertEquals(2, tokenRegion.getOffset()); assertEquals(1, tokenRegion.getLength()); }
Example #26
Source File: IdeContentProposalProvider.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
protected void _createProposals(Assignment assignment, ContentAssistContext context, IIdeContentProposalAcceptor acceptor) { AbstractElement terminal = assignment.getTerminal(); if (terminal instanceof CrossReference) { createProposals(terminal, context, acceptor); } else { if (terminal instanceof RuleCall) { AbstractRule rule = ((RuleCall) terminal).getRule(); if (rule instanceof TerminalRule && context.getPrefix().isEmpty()) { final String proposal; if ("STRING".equals(rule.getName())) { proposal = "\"" + assignment.getFeature() + "\""; } else { proposal = assignment.getFeature(); } ContentAssistEntry entry = proposalCreator.createProposal(proposal, context, (ContentAssistEntry it) -> { if ("STRING".equals(rule.getName())) { it.getEditPositions() .add(new TextRegion(context.getOffset() + 1, proposal.length() - 2)); it.setKind(ContentAssistEntry.KIND_TEXT); } else { it.getEditPositions().add(new TextRegion(context.getOffset(), proposal.length())); it.setKind(ContentAssistEntry.KIND_VALUE); } it.setDescription(rule.getName()); }); acceptor.accept(entry, proposalPriorities.getDefaultPriority(entry)); } } } }
Example #27
Source File: ContentAssistContextTestHelper.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
public String firstSetGrammarElementsToString(final ContentAssistContextFactory factory) { final int offset = this.document.indexOf(this.cursor); Preconditions.checkArgument((offset >= 0), "you forgot to provide a cursor"); final String doc = this.document.replace(this.cursor, ""); final XtextResource res = this.parse(doc); factory.setPool(Executors.newCachedThreadPool()); TextRegion _textRegion = new TextRegion(0, 0); final ContentAssistContext[] ctxs = factory.create(doc, _textRegion, offset, res); final GrammarElementTitleSwitch f = new GrammarElementTitleSwitch().showAssignments().showQualified().showRule(); StringConcatenation _builder = new StringConcatenation(); { Iterable<Pair<Integer, ContentAssistContext>> _indexed = IterableExtensions.<ContentAssistContext>indexed(((Iterable<? extends ContentAssistContext>)Conversions.doWrapArray(ctxs))); for(final Pair<Integer, ContentAssistContext> ctx : _indexed) { _builder.append("context"); Integer _key = ctx.getKey(); _builder.append(_key); _builder.append(" {"); _builder.newLineIfNotEmpty(); { ImmutableList<AbstractElement> _firstSetGrammarElements = ctx.getValue().getFirstSetGrammarElements(); for(final AbstractElement ele : _firstSetGrammarElements) { _builder.append("\t"); String _name = ele.eClass().getName(); _builder.append(_name, "\t"); _builder.append(": "); String _apply = f.apply(ele); _builder.append(_apply, "\t"); _builder.newLineIfNotEmpty(); } } _builder.append("}"); _builder.newLine(); } } return _builder.toString(); }
Example #28
Source File: ContentAssistService.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
public CompletionList createCompletionList(Document document, XtextResource resource, CompletionParams params, CancelIndicator cancelIndicator) { try { CompletionList result = new CompletionList(); result.setIsIncomplete(true); IdeContentProposalAcceptor acceptor = proposalAcceptorProvider.get(); int caretOffset = document.getOffSet(params.getPosition()); Position caretPosition = params.getPosition(); TextRegion position = new TextRegion(caretOffset, 0); try { createProposals(document.getContents(), position, caretOffset, resource, acceptor); } catch (Throwable t) { if (!operationCanceledManager.isOperationCanceledException(t)) { throw t; } } int idx = 0; for (ContentAssistEntry it : acceptor.getEntries()) { CompletionItem item = toCompletionItem(it, caretOffset, caretPosition, document); item.setSortText(Strings.padStart(Integer.toString(idx), 5, '0')); result.getItems().add(item); idx++; } return result; } catch (Throwable e) { throw Exceptions.sneakyThrow(e); } }
Example #29
Source File: AstSelectionAction.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
@Override public void run() { ITextSelection selection = (ITextSelection) xtextEditor.getSelectionProvider().getSelection(); ITextRegion currentEditorSelection = new TextRegion(selection.getOffset(), selection.getLength()); ITextRegion nextSelection = xtextEditor.getDocument().priorityReadOnly(createTextSelectionWork(currentEditorSelection)); if (nextSelection == null || nextSelection == ITextRegion.EMPTY_REGION || nextSelection.equals(currentEditorSelection)) { return; } xtextEditor.selectAndReveal(nextSelection.getOffset(), nextSelection.getLength()); }
Example #30
Source File: ImportsAwareClipboardAction.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
private XbaseClipboardData createClipboardData() { try { IEditorInput editorInput = getTextEditor().getEditorInput(); final String sourceIdentifier = editorInput != null ? editorInput.toString() : "nullEditorInput"; IXtextDocument document = getXtextDocument(); final ISelection selection = getTextEditor().getSelectionProvider().getSelection(); if (selection instanceof ITextSelection && !selection.isEmpty()) { final ITextSelection textSelection = (ITextSelection) selection; return document.tryReadOnly(new IUnitOfWork<XbaseClipboardData, XtextResource>() { @Override public XbaseClipboardData exec(XtextResource state) throws Exception { ITextRegion region = new TextRegion(textSelection.getOffset(), textSelection.getLength() - 1); Triple<Set<String>, Set<String>, Set<String>> imports = importsUtil.collectImports(state, region); XbaseClipboardData clipboardData = new XbaseClipboardData(sourceIdentifier, Iterables.toArray(imports.getFirst(), String.class), Iterables.toArray(imports.getSecond(), String.class), Iterables.toArray(imports.getThird(), String.class)); return clipboardData; } }); } } catch (Exception e) { //TODO Log exception return null; } return null; }