Java Code Examples for org.eclipse.xtext.ui.editor.model.IXtextDocument#readOnly()
The following examples show how to use
org.eclipse.xtext.ui.editor.model.IXtextDocument#readOnly() .
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: N4JSEditorResourceAccess.java From n4js with Eclipse Public License 1.0 | 6 votes |
/*** * This method modifies the super method to handle NullPointerException when state is null. */ @Override public <R> R readOnly(final URI targetURI, final IUnitOfWork<R, ResourceSet> work) { IXtextDocument document = openDocumentTracker.getOpenDocument(targetURI.trimFragment()); if (document != null) { return document.readOnly(new IUnitOfWork<R, XtextResource>() { @Override public R exec(XtextResource state) throws Exception { // For some reason, sometimes state can be null at this point, // The resource set must be retrieved by other means in delegate.readOnly if (state == null) { return delegate.readOnly(targetURI, work); } ResourceSet localContext = state.getResourceSet(); if (localContext != null) return work.exec(localContext); return null; } }); } else { return delegate.readOnly(targetURI, work); } }
Example 2
Source File: QuickfixTestBuilder.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
public QuickfixTestBuilder create(final String fileName, final String model) { try { QuickfixTestBuilder _xblockexpression = null; { final String positionMarker = this.getPositionMarker(model); final IFile file = this._workbenchTestHelper.createFile(fileName, model.replace(positionMarker, "")); this.editor = this.openEditorSafely(file); final IXtextDocument document = this.editor.getDocument(); Assert.assertNotNull("Error getting document from editor", document); final IUnitOfWork<List<Issue>, XtextResource> _function = (XtextResource it) -> { return this.issues = this._iResourceValidator.validate(it, CheckMode.NORMAL_AND_FAST, CancelIndicator.NullImpl); }; document.<List<Issue>>readOnly(_function); this.caretOffset = model.indexOf(positionMarker); _xblockexpression = this; } return _xblockexpression; } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
Example 3
Source File: CheckQuickfixProvider.java From dsl-devkit with Eclipse Public License 1.0 | 6 votes |
/** {@inheritDoc} */ @Override public void apply(final IModificationContext context) throws BadLocationException { final IXtextDocument xtextDocument = context.getXtextDocument(); xtextDocument.readOnly(new IUnitOfWork.Void<XtextResource>() { @Override public void process(final XtextResource state) throws Exception { // NOPMD final EObject target = EcoreUtil2.getContainerOfType(state.getEObject(issue.getUriToProblem().fragment()), type); if (type.isInstance(target)) { int offset = NodeModelUtils.findActualNodeFor(target).getOffset(); int lineOfOffset = xtextDocument.getLineOfOffset(offset); int lineOffset = xtextDocument.getLineOffset(lineOfOffset); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < (offset - lineOffset); i++) { buffer.append(' '); } xtextDocument.replace(offset, 0, NLS.bind(autodocumentation, buffer.toString())); } } }); }
Example 4
Source File: TaxonomyCheckboxListView.java From slr-toolkit with Eclipse Public License 1.0 | 6 votes |
@Override public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (part instanceof XtextEditor && !selection.isEmpty()) { final XtextEditor editor = (XtextEditor) part; final IXtextDocument document = editor.getDocument(); document.readOnly(new IUnitOfWork.Void<XtextResource>() { @Override public void process(XtextResource resource) throws Exception { IParseResult parseResult = resource.getParseResult(); if (parseResult != null) { ICompositeNode root = parseResult.getRootNode(); EObject taxonomy = NodeModelUtils.findActualSemanticObjectFor(root); if (taxonomy instanceof Model) { ModelRegistryPlugin.getModelRegistry().setActiveTaxonomy((Model) taxonomy); } } } }); } }
Example 5
Source File: DefaultMergeViewer.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
protected void configureSourceViewer(SourceViewer sourceViewer) { IEditorInput editorInput = getEditorInput(sourceViewer); SourceViewerConfiguration sourceViewerConfiguration = createSourceViewerConfiguration(sourceViewer, editorInput); sourceViewer.unconfigure(); sourceViewer.configure(sourceViewerConfiguration); IXtextDocument xtextDocument = xtextDocumentUtil.getXtextDocument(sourceViewer); if (xtextDocument != null) { if (!xtextDocument.readOnly(TEST_EXISTING_XTEXT_RESOURCE)) { String[] configuredContentTypes = sourceViewerConfiguration.getConfiguredContentTypes(sourceViewer); for (String contentType : configuredContentTypes) { sourceViewer.removeTextHovers(contentType); } sourceViewer.setHyperlinkDetectors(null, sourceViewerConfiguration.getHyperlinkStateMask(sourceViewer)); } } }
Example 6
Source File: OverrideIndicatorModelListener.java From xtext-xtend with Eclipse Public License 2.0 | 5 votes |
private IStatus updateAnnotationModel(IProgressMonitor monitor) { if (xtextEditor == null || xtextEditor.getDocument() == null || xtextEditor.getInternalSourceViewer().getAnnotationModel() == null) { return Status.OK_STATUS; } IXtextDocument xtextDocument = xtextEditor.getDocument(); IAnnotationModel annotationModel = xtextEditor.getInternalSourceViewer().getAnnotationModel(); Map<Annotation, Position> annotationToPosition = xtextDocument .readOnly(new CancelableUnitOfWork<Map<Annotation, Position>, XtextResource>() { @Override public Map<Annotation, Position> exec(XtextResource xtextResource, CancelIndicator cancelIndicator) { if (xtextResource == null) return Collections.emptyMap(); return createOverrideIndicatorAnnotationMap(xtextResource, cancelIndicator); } }); if (monitor.isCanceled()) return Status.CANCEL_STATUS; if (annotationModel instanceof IAnnotationModelExtension) { IAnnotationModelExtension annotationModelExtension = (IAnnotationModelExtension) annotationModel; Object lockObject = getLockObject(annotationModel); synchronized (lockObject) { annotationModelExtension.replaceAnnotations( overrideIndicatorAnnotations.toArray(new Annotation[overrideIndicatorAnnotations.size()]), annotationToPosition); } overrideIndicatorAnnotations = annotationToPosition.keySet(); } return Status.OK_STATUS; }
Example 7
Source File: DotOutlineTreeProvider.java From gef with Eclipse Public License 2.0 | 5 votes |
private HtmlLabel getModel(IXtextDocument xtextDocument) { HtmlLabel model = xtextDocument .readOnly(new IUnitOfWork<HtmlLabel, XtextResource>() { @Override public HtmlLabel exec(XtextResource res) throws Exception { return res.getContents().size() > 0 ? (HtmlLabel) res.getContents().get(0) : null; } }); return model; }
Example 8
Source File: XtextUtil.java From dsl-devkit with Eclipse Public License 1.0 | 5 votes |
/** * Provides the Xtext resource from a Xtext Document. * * @param document * The XtextDocument * @return XtexRessource */ public static XtextResource getXtextRessource(final IXtextDocument document) { return document.readOnly(new IUnitOfWork<XtextResource, XtextResource>() { @Override public XtextResource exec(final XtextResource state) { return state; } }); }
Example 9
Source File: EmbeddedEditorModelAccess.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
public void updateModel(String model, final IUnitOfWork<ITextRegion, XtextResource> editablePartSelector) { IXtextDocument document = xtextDocumentUtil.getXtextDocument(this.viewer); this.viewer.setRedraw(false); this.viewer.getUndoManager().disconnect(); document.set(model); ITextRegion textRegion = document.readOnly(editablePartSelector); if (textRegion == null) { this.viewer.resetVisibleRegion(); } else { this.viewer.setVisibleRegion(textRegion.getOffset(), textRegion.getLength()); } this.viewer.getUndoManager().connect(this.viewer); this.viewer.setRedraw(true); }
Example 10
Source File: XtextGrammarQuickfixProviderTest.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
private List<Issue> getIssues(IXtextDocument document) { return document.readOnly(new IUnitOfWork<List<Issue>, XtextResource>() { @Override public List<Issue> exec(XtextResource state) throws Exception { return state.getResourceServiceProvider().getResourceValidator().validate(state, CheckMode.ALL, null); } }); }
Example 11
Source File: EncodingTest.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
protected void openEditorAndCheckEncoding(IFile file, final String charset) throws CoreException, Exception { XtextEditor openedEditor = openEditor(file); assertNotNull(openedEditor); IXtextDocument document = openedEditor.getDocument(); document.readOnly(new IUnitOfWork.Void<XtextResource>() { @Override public void process(XtextResource resource) throws Exception { assertEquals(charset, resource.getEncoding()); } }); openedEditor.close(false); openedEditor.dispose(); }
Example 12
Source File: Bug369087Test.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
protected void reconcile(IXtextDocument xtextDocument) { xtextDocument.readOnly(new IUnitOfWork.Void<XtextResource>() { @Override public void process(XtextResource state) throws Exception { } }); }
Example 13
Source File: GamlHyperlinkDetector.java From gama with GNU General Public License v3.0 | 5 votes |
@Override public IHyperlink[] detectHyperlinks(final ITextViewer textViewer, final IRegion region, final boolean canShowMultipleHyperlinks) { final IXtextDocument document = (IXtextDocument) textViewer.getDocument(); final IHyperlink[] importHyperlinks = importHyperlinks(document, region); if (importHyperlinks != NO_HYPERLINKS) { return importHyperlinks; } return document.readOnly(new CancelableUnitOfWork<IHyperlink[], XtextResource>() { @Override public IHyperlink[] exec(final XtextResource resource, final CancelIndicator c) { return getHelper().createHyperlinksByOffset(resource, region.getOffset(), canShowMultipleHyperlinks); } }); }
Example 14
Source File: OutlineTreeProviderTest.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
@Test public void testCreateChildren() throws Exception { final String modelAsText = "element1 { element11 {}} element2 {}"; IXtextDocument document = createXtextDocument(modelAsText); final IOutlineNode rootNode = treeProvider.createRoot(document); document.readOnly(new IUnitOfWork.Void<XtextResource>() { @Override public void process(XtextResource state) throws Exception { treeProvider.createChildren(rootNode, state.getContents().get(0)); assertEquals(1, rootNode.getChildren().size()); IOutlineNode modelNode = rootNode.getChildren().get(0); assertEquals(state.getURI().trimFileExtension().lastSegment(), modelNode.getText()); assertEquals(new TextRegion(0, modelAsText.length()), modelNode.getSignificantTextRegion()); assertEquals(new TextRegion(0, modelAsText.length()), modelNode.getFullTextRegion()); assertEquals(rootNode, modelNode.getParent()); assertTrue(modelNode.hasChildren()); assertEquals(2, modelNode.getChildren().size()); IOutlineNode element1 = modelNode.getChildren().get(0); assertEquals("element1", element1.getText().toString()); assertEquals(new TextRegion(0, 8), element1.getSignificantTextRegion()); assertEquals(new TextRegion(0, 24), element1.getFullTextRegion()); assertEquals(modelNode, element1.getParent()); assertTrue(element1.hasChildren()); IOutlineNode element2 = modelNode.getChildren().get(1); assertEquals("element2", element2.getText().toString()); assertEquals(new TextRegion(25, 8), element2.getSignificantTextRegion()); assertEquals(new TextRegion(25, 11), element2.getFullTextRegion()); assertEquals(modelNode, element2.getParent()); assertFalse(element2.hasChildren()); } }); }
Example 15
Source File: DocumentImportsOrganizer.java From n4js with Eclipse Public License 1.0 | 5 votes |
/** * Organize the imports in the N4JS document. * * @param document * N4JS document * @throws RuntimeException * wrapping a BreakException in case of user-abortion ({@link Interaction#queryUser}) or * resolution-failure({@link Interaction#breakBuild} ) */ void organizeDocument(final IXtextDocument document, final Interaction interaction) { // trigger Linking document.readOnly((XtextResource p) -> { N4JSResource.postProcess(p); return null; }); List<IChange> result = document.readOnly(prepareImportsChanges(document, interaction)); applyChangesToDocument(document, result); }
Example 16
Source File: ImportURINavigationTest.java From xtext-eclipse with Eclipse Public License 2.0 | 4 votes |
protected void doTestNavigation(IUnitOfWork<URI, IFile> uriComputation, boolean expectFQN) throws Exception { IJavaProject project = JavaProjectSetupUtil.createJavaProject("importuriuitestlanguage.project"); try { IFile first = project.getProject().getFile("src/first.importuriuitestlanguage"); first.create(new StringInputStream("type ASimpleType"), true, null); ResourceSet resourceSet = resourceSetProvider.get(project.getProject()); Resource resource = resourceFactory.createResource(URI.createURI("synthetic://second.importuriuitestlanguage")); resourceSet.getResources().add(resource); String model = "import '" + uriComputation.exec(first) + "' type MyType extends ASimpleType"; resource.load(new StringInputStream(model), null); EcoreUtil.resolveAll(resource); Assert.assertTrue(resource.getErrors().isEmpty()); IHyperlink[] hyperlinks = helper.createHyperlinksByOffset((XtextResource) resource, model.indexOf("SimpleType"), false); Assert.assertEquals(1, hyperlinks.length); IWorkbenchPage activePage = workbench.getActiveWorkbenchWindow().getActivePage(); Assert.assertNull(activePage.getActiveEditor()); if (expectFQN) { Assert.assertEquals(URI.createURI(first.getLocationURI().toString()), ((XtextHyperlink)hyperlinks[0]).getURI().trimFragment()); } else { Assert.assertEquals(URI.createPlatformResourceURI(first.getFullPath().toString(), true), ((XtextHyperlink)hyperlinks[0]).getURI().trimFragment()); } hyperlinks[0].open(); IEditorPart editor = activePage.getActiveEditor(); Assert.assertNotNull(editor); IXtextDocument document = xtextDocumentUtil.getXtextDocument(editor); document.readOnly(new IUnitOfWork.Void<XtextResource>() { @Override public void process(XtextResource state) throws Exception { Assert.assertEquals("platform:/resource/importuriuitestlanguage.project/src/first.importuriuitestlanguage", state.getURI().toString()); } }); Assert.assertEquals("type ASimpleType", document.get()); IEditorPart newPart = IDE.openEditor(activePage, first); Assert.assertEquals(1, activePage.getEditorReferences().length); Assert.assertEquals(editor, newPart); } finally { project.getProject().delete(true, null); } }
Example 17
Source File: AbstractHyperlinkingTest.java From xtext-eclipse with Eclipse Public License 2.0 | 4 votes |
protected IHyperlink[] hyperlinkingOn(IFile dslFile, int offset) { XtextEditor editor = openInEditor(dslFile); IXtextDocument document = xtextDocumentUtil.getXtextDocument(editor.getInternalSourceViewer()); XtextResource resource = document.readOnly((state) -> state); return hyperlinkHelper.createHyperlinksByOffset(resource, offset, true); }
Example 18
Source File: DotOccurrenceComputer.java From gef with Eclipse Public License 2.0 | 4 votes |
/** * The implementation of this method is mainly taken from its super * implementation */ @Override public Map<Annotation, Position> createAnnotationMap(XtextEditor editor, final ITextSelection selection, final SubMonitor monitor) { Map<Annotation, Position> annotationMap = super.createAnnotationMap( editor, selection, monitor); final IXtextDocument document = editor.getDocument(); if (document != null) { return document.readOnly( new CancelableUnitOfWork<Map<Annotation, Position>, XtextResource>() { @Override public Map<Annotation, Position> exec( XtextResource resource, final CancelIndicator cancelIndicator) throws Exception { if (resource != null && resource.getContents().size() > 0) { INode node = NodeModelUtils .findLeafNodeAtOffset( NodeModelUtils.getNode(resource .getContents().get(0)), selection.getOffset()); EObject target = eObjectAtOffsetHelper .resolveElementAt(resource, selection.getOffset()); List<ITextRegion> textRegions = new ArrayList<>(); if (target instanceof NodeId && !target.eIsProxy()) { textRegions = nodeId((NodeId) target); } else if (target instanceof Attribute && !target.eIsProxy()) { textRegions = attribute((Attribute) target, node); } for (ITextRegion occurrence : textRegions) { try { addOccurrenceAnnotation( OCCURRENCE_ANNOTATION_TYPE, document, occurrence, annotationMap); } catch (Exception exc) { // outdated index information. Ignore } } } return annotationMap; } }); } else { return annotationMap; } }
Example 19
Source File: PasteJavaCodeHandler.java From xtext-xtend with Eclipse Public License 2.0 | 4 votes |
private void doPasteJavaCode(final XtextEditor activeXtextEditor, final String javaCode, final JavaImportData javaImports) throws ExecutionException { ISourceViewer sourceViewer = activeXtextEditor.getInternalSourceViewer(); final IXtextDocument xtextDocument = activeXtextEditor.getDocument(); IJavaProject project = null; IProject iProject = null; IEditorInput editorInput = activeXtextEditor.getEditorInput(); if (editorInput instanceof IFileEditorInput) { iProject = ((IFileEditorInput) editorInput).getFile().getProject(); project = JavaCore.create(iProject); } final int selectionOffset = Math.max(0, sourceViewer.getSelectedRange().x - 1); EObject targetElement = xtextDocument.readOnly(new IUnitOfWork<EObject, XtextResource>() { @Override public EObject exec(XtextResource state) throws Exception { IParseResult parseResult = state.getParseResult(); if (parseResult == null) { return null; } ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), selectionOffset); if (leafNode == null) { return parseResult.getRootASTElement(); } return leafNode.getSemanticElement(); } }); JavaConverter javaConverter = javaConverterProvider.get(); final String xtendCode = javaConverter.toXtend(javaCode, javaImports != null ? javaImports.getImports() : null, targetElement, project, conditionalExpressionsAllowed(iProject)); if (!Strings.isEmpty(xtendCode)) { if (javaImports != null) { importsUtil.addImports(javaImports.getImports(), javaImports.getStaticImports(), new String[] {}, xtextDocument); } Point selection = sourceViewer.getSelectedRange(); try { xtextDocument.replace(selection.x, selection.y, xtendCode); } catch (BadLocationException e) { throw new ExecutionException("Failed to replace content.", e); } //TODO enable formatting, when performance became better // https://bugs.eclipse.org/bugs/show_bug.cgi?id=457814 // doFormat(sourceViewer, xtendCode, selection); } }
Example 20
Source File: ValidationHelper.java From dsl-devkit with Eclipse Public License 1.0 | 2 votes |
/** * Validates the provided document and returns a list of issues found. * * @param document * to validate * @return list of issues found */ public List<Issue> getIssues(final IXtextDocument document) { return document.readOnly(state -> state.getResourceServiceProvider().getResourceValidator().validate(state, CheckMode.ALL, null)); }