/*** * 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); } }
private ValidationJob newValidationJob(final XtextEditor editor) { final IXtextDocument document = editor.getDocument(); final IAnnotationModel annotationModel = editor.getInternalSourceViewer().getAnnotationModel(); final IssueResolutionProvider issueResolutionProvider = getService(editor, IssueResolutionProvider.class); final MarkerTypeProvider markerTypeProvider = getService(editor, MarkerTypeProvider.class); final MarkerCreator markerCreator = getService(editor, MarkerCreator.class); final IValidationIssueProcessor issueProcessor = new CompositeValidationIssueProcessor( new AnnotationIssueProcessor(document, annotationModel, issueResolutionProvider), new MarkerIssueProcessor(editor.getResource(), markerCreator, markerTypeProvider)); return editor.getDocument().modify(resource -> { final IResourceServiceProvider serviceProvider = resource.getResourceServiceProvider(); final IResourceValidator resourceValidator = serviceProvider.getResourceValidator(); return new ValidationJob(resourceValidator, editor.getDocument(), issueProcessor, ALL); }); }
/** * This method makes sure that no changes are applied (no dirty state), if there are no changes. This fixes bug * GHOLD-272 */ @Override public void format(IDocument document, IRegion region) { IXtextDocument doc = (IXtextDocument) document; TextEdit e = doc.priorityReadOnly(new FormattingUnitOfWork(doc, region)); if (e == null) return; if (e instanceof ReplaceEdit) { ReplaceEdit r = (ReplaceEdit) e; if ((r.getOffset() == 0) && (r.getLength() == 0) && (r.getText().isEmpty())) { return; } } try { e.apply(document); } catch (BadLocationException ex) { throw new RuntimeException(ex); } }
/** * Insert the given string as a new line above the line at the given offset. The given string need not contain any * line delimiters and the offset need not point to the beginning of a line. If 'sameIndentation' is set to * <code>true</code>, the new line will be indented as the line at the given offset (i.e. same leading white space). */ public static IChange insertLineAbove(IXtextDocument doc, int offset, String txt, boolean sameIndentation) throws BadLocationException { final String NL = lineDelimiter(doc, offset); final IRegion currLineReg = doc.getLineInformationOfOffset(offset); String indent = ""; if (sameIndentation) { final String currLine = doc.get(currLineReg.getOffset(), currLineReg.getLength()); int idx = 0; while (idx < currLine.length() && Character.isWhitespace(currLine.charAt(idx))) { idx++; } indent = currLine.substring(0, idx); } return new Replacement(getURI(doc), currLineReg.getOffset(), 0, indent + txt + NL); }
/** * Removes text of the given length at the given offset. If 'removeEntireLineIfEmpty' is set to <code>true</code>, * the line containing the given text region will be deleted entirely iff the change would leave the line empty * (i.e. contains only white space) <em>after</em> the removal of the text region. */ public static IChange removeText(IXtextDocument doc, int offset, int length, boolean removeEntireLineIfEmpty) throws BadLocationException { if (!removeEntireLineIfEmpty) { // simple return new Replacement(getURI(doc), offset, length, ""); } else { // get entire line containing the region to be removed // OR in case the region spans multiple lines: get *all* lines affected by the removal final IRegion linesRegion = DocumentUtilN4.getLineInformationOfRegion(doc, offset, length, true); final String lines = doc.get(linesRegion.getOffset(), linesRegion.getLength()); // simulate the removal final int offsetRelative = offset - linesRegion.getOffset(); final String lineAfterRemoval = removeSubstring(lines, offsetRelative, length); final boolean isEmptyAfterRemoval = lineAfterRemoval.trim().isEmpty(); if (isEmptyAfterRemoval) { // remove entire line (or in case the removal spans multiple lines: remove all affected lines entirely) return new Replacement(getURI(doc), linesRegion.getOffset(), linesRegion.getLength(), ""); } else { // just remove the given text region return new Replacement(getURI(doc), offset, length, ""); } } }
@Override protected void computeCommentFolding(IXtextDocument xtextDocument, IFoldingRegionAcceptor<ITextRegion> foldingRegionAcceptor, ITypedRegion typedRegion, boolean initiallyFolded) { String text; try { text = xtextDocument.get(typedRegion.getOffset(), typedRegion.getLength()); int lines = Strings.countLines(text); if (shouldCreateCommentFolding(lines)) { boolean collapse = shouldCollapse(typedRegion, lines); super.computeCommentFolding(xtextDocument, foldingRegionAcceptor, typedRegion, collapse); } } catch (BadLocationException e) { log.error(e, e); } }
private void updateArchitectureViewer(final IXtextDocument xtextDocument) { final String timerId = getStringParameterValue(xtextDocument, this.architectureViewer.getCombo()); final TimerElement timer = ArchitecturesExtension.getTimer(timerId); if (timer != null) { final NamedExtensionElementsProvider provider = (NamedExtensionElementsProvider) this.architectureViewer .getContentProvider(); final int index = provider.getIndex(timer.getArchitecture().getId()); if (index >= 0) { this.architectureViewer.getCombo().select(index); } } else { this.architectureViewer.getCombo().select(0); } updateTimerViewer(xtextDocument, timer); }
private void updateTimerViewer(final IXtextDocument xtextDocument, final TimerElement timer) { final ArchitectureElement architecture = (ArchitectureElement) this.architectureViewer.getStructuredSelection() .getFirstElement(); this.timerViewer.setInput(architecture.getTimers()); if (timer != null) { final NamedExtensionElementsProvider provider = (NamedExtensionElementsProvider) this.timerViewer .getContentProvider(); final int index = provider.getIndex(timer.getId()); if (index >= 0) { this.timerViewer.getCombo().select(index); } } else { this.timerViewer.getCombo().select(0); } updateCyclePeriodControls(xtextDocument); }
/** * Mocks XtextEditor and XtextElementSelectionListener to return an element selection that has: * - given EAttribute with a specific value (AttributeValuePair) * - given EStructuralFeature * - given EOperation. * * @param attributeValuePair * EAttribute with a specific value * @param feature * the EStructuralFeature * @param operation * the EOperation * @return the EClass of the "selected" element */ @SuppressWarnings("unchecked") private EClass mockSelectedElement(final AttributeValuePair attributeValuePair, final EStructuralFeature feature, final EOperation operation) { EClass mockSelectionEClass = mock(EClass.class); when(mockSelectionListener.getSelectedElementType()).thenReturn(mockSelectionEClass); // Mockups for returning AttributeValuePair URI elementUri = URI.createURI(""); when(mockSelectionListener.getSelectedElementUri()).thenReturn(elementUri); XtextEditor mockEditor = mock(XtextEditor.class); when(mockSelectionListener.getEditor()).thenReturn(mockEditor); IXtextDocument mockDocument = mock(IXtextDocument.class); when(mockEditor.getDocument()).thenReturn(mockDocument); when(mockDocument.<ArrayList<AttributeValuePair>> readOnly(any(IUnitOfWork.class))).thenReturn(newArrayList(attributeValuePair)); // Mockups for returning EOperation BasicEList<EOperation> mockEOperationsList = new BasicEList<EOperation>(); mockEOperationsList.add(operation); when(mockSelectionEClass.getEAllOperations()).thenReturn(mockEOperationsList); // Mockups for returning EStructuralFeature BasicEList<EStructuralFeature> mockEStructuralFeatureList = new BasicEList<EStructuralFeature>(); mockEStructuralFeatureList.add(feature); mockEStructuralFeatureList.add(attributeValuePair.getAttribute()); when(mockSelectionEClass.getEAllStructuralFeatures()).thenReturn(mockEStructuralFeatureList); return mockSelectionEClass; }
/** * {@inheritDoc} Code copied from parent. Override required to run in UI because of getSourceViewer, which creates a new Shell. */ @Override public ICompletionProposal[] computeCompletionProposals(final String currentModelToParse, final int cursorPosition) throws Exception { Pair<ICompletionProposal[], BadLocationException> result = UiThreadDispatcher.dispatchAndWait(new Function<Pair<ICompletionProposal[], BadLocationException>>() { @Override public Pair<ICompletionProposal[], BadLocationException> run() { final XtextResource xtextResource = loadHelper.getResourceFor(new StringInputStream(currentModelToParse)); final IXtextDocument xtextDocument = getDocument(xtextResource, currentModelToParse); return internalComputeCompletionProposals(cursorPosition, xtextDocument); } }); if (result.getSecond() != null) { throw result.getSecond(); } return result.getFirst(); }
/** * Internally compute completion proposals. * * @param cursorPosition * the position of the cursor in the {@link IXtextDocument} * @param xtextDocument * the {@link IXtextDocument} * @return a pair of {@link ICompletionProposal}[] and {@link BadLocationException}. If the tail argument is not {@code null}, an exception occurred in the UI * thread. */ private Pair<ICompletionProposal[], BadLocationException> internalComputeCompletionProposals(final int cursorPosition, final IXtextDocument xtextDocument) { XtextSourceViewerConfiguration configuration = get(XtextSourceViewerConfiguration.class); Shell shell = new Shell(); try { ISourceViewer sourceViewer = getSourceViewer(shell, xtextDocument, configuration); IContentAssistant contentAssistant = configuration.getContentAssistant(sourceViewer); String contentType = xtextDocument.getContentType(cursorPosition); IContentAssistProcessor processor = contentAssistant.getContentAssistProcessor(contentType); if (processor != null) { return Tuples.create(processor.computeCompletionProposals(sourceViewer, cursorPosition), null); } return Tuples.create(new ICompletionProposal[0], null); } catch (BadLocationException e) { return Tuples.create(new ICompletionProposal[0], e); } finally { shell.dispose(); } }
/** * Install this reconciler on the given editor and presenter. * * @param editor * the editor * @param sourceViewer * the source viewer * @param presenter * the highlighting presenter */ @Override public void install(final XtextEditor editor, final XtextSourceViewer sourceViewer, final HighlightingPresenter presenter) { synchronized (fReconcileLock) { cleanUpAfterReconciliation = false; // prevents a potentially already running reconciliation process to clean up after itself } this.presenter = presenter; this.editor = editor; this.sourceViewer = sourceViewer; if (calculator != null) { if (editor == null) { ((IXtextDocument) sourceViewer.getDocument()).addModelListener(this); } else if (editor.getDocument() != null) { editor.getDocument().addModelListener(this); } sourceViewer.addTextInputListener(this); } refresh(); }
/** * Refreshes the highlighting. */ @Override public void refresh() { if (calculator != null) { IDocument document; if (editor != null) { document = editor.getDocument(); } else { document = sourceViewer.getDocument(); } if (document instanceof IXtextDocument) { ((IXtextDocument) document).readOnly(new IUnitOfWork.Void<XtextResource>() { @Override public void process(final XtextResource state) throws Exception { modelChanged(state); } }); } } else { Display display = getDisplay(); display.asyncExec(presenter.createSimpleUpdateRunnable()); } }
/** * Fix catalog name. * * @param issue * the issue * @param acceptor * the acceptor */ @Fix(IssueCodes.WRONG_FILE) public void fixCatalogName(final Issue issue, final IssueResolutionAcceptor acceptor) { acceptor.accept(issue, Messages.CheckQuickfixProvider_CORRECT_CATALOG_NAME_LABEL, Messages.CheckQuickfixProvider_CORRECT_CATALOG_NAME_DESCN, NO_IMAGE, new IModification() { @Override public void apply(final IModificationContext context) throws BadLocationException { IXtextDocument xtextDocument = context.getXtextDocument(); IFile file = xtextDocument.getAdapter(IFile.class); if (file != null) { final String fileName = file.getName(); final String name = fileName.indexOf('.') > 0 ? fileName.substring(0, fileName.lastIndexOf('.')) : fileName; xtextDocument.replace(issue.getOffset(), issue.getLength(), name); } } }); }
/** {@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())); } } }); }
/** * Fixes an illegally set default severity. The default severity must be within given severity range. * * @param issue * the issue * @param acceptor * the acceptor */ @Fix(IssueCodes.DEFAULT_SEVERITY_NOT_IN_RANGE) public void fixIllegalDefaultSeverity(final Issue issue, final IssueResolutionAcceptor acceptor) { if (issue.getData() != null) { for (final String severityProposal : issue.getData()) { final String label = NLS.bind(Messages.CheckQuickfixProvider_DEFAULT_SEVERITY_FIX_LABEL, severityProposal); final String descn = NLS.bind(Messages.CheckQuickfixProvider_DEFAULT_SEVERITY_FIX_DESCN, severityProposal); acceptor.accept(issue, label, descn, NO_IMAGE, new IModification() { @Override public void apply(final IModificationContext context) throws BadLocationException { IXtextDocument xtextDocument = context.getXtextDocument(); xtextDocument.replace(issue.getOffset(), issue.getLength(), severityProposal); } }); } } }
/** * Fix severity by setting it to a legal value as is defined by severity range of referenced check. Legal * severities are passed as issue data (org.eclipse.xtext.validation.Issue#getData()). * * @param issue * the issue * @param acceptor * the acceptor */ @Fix(IssueCodes.SEVERITY_NOT_ALLOWED) public void fixSeverityToMaxSeverity(final Issue issue, final IssueResolutionAcceptor acceptor) { if (issue.getData() != null) { for (final String severityProposal : issue.getData()) { final String label = NLS.bind(Messages.CheckCfgQuickfixProvider_CORRECT_SEVERITY_LABEL, severityProposal); final String descn = NLS.bind(Messages.CheckCfgQuickfixProvider_CORRECT_SEVERITY_DESCN, severityProposal); acceptor.accept(issue, label, descn, NO_IMAGE, new IModification() { public void apply(final IModificationContext context) throws BadLocationException { IXtextDocument xtextDocument = context.getXtextDocument(); xtextDocument.replace(issue.getOffset(), issue.getLength(), severityProposal); } }); } } }
protected void configureSourceViewer(SourceViewer sourceViewer) { IEditorInput editorInput = getEditorInput(sourceViewer); SourceViewerConfiguration sourceViewerConfiguration = createSourceViewerConfiguration(sourceViewer, editorInput); sourceViewer.unconfigure(); sourceViewer.configure(sourceViewerConfiguration); if (sourceViewer.getDocument() instanceof IXtextDocument) { IXtextDocument xtextDocument = (IXtextDocument) sourceViewer.getDocument(); 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)); } } }
public Object execute(final ExecutionEvent event) throws ExecutionException { final XtextEditor xtextEditor = EditorUtils.getActiveXtextEditor(event); if (xtextEditor != null) { final IXtextDocument document = xtextEditor.getDocument(); document.readOnly(new IUnitOfWork.Void<XtextResource>() { @Override public void process(XtextResource state) throws Exception { final QuickOutlinePopup quickOutlinePopup = createPopup(xtextEditor.getEditorSite().getShell()); quickOutlinePopup.setEditor(xtextEditor); quickOutlinePopup.setInput(document); quickOutlinePopup.setEvent((Event) event.getTrigger()); quickOutlinePopup.open(); } }); } return null; }
public void connect(IXtextDocument document) { if (document == null) throw new IllegalArgumentException("document may not be null"); if (this.document == document) return; if (this.document != null) throw new IllegalStateException("Dirty resource was already connected to another document"); this.document = document; document.readOnly(new IUnitOfWork.Void<XtextResource>() { @Override public void process(XtextResource resource) { if (resource != null) { DocumentBasedDirtyResource.this.normalizedUri = EcoreUtil2.getNormalizedURI(resource); initiallyProcessResource(resource); } } }); }
@Override public void run() { IXtextDocument document = editor.getDocument(); ISelection selection = editor.getSelectionProvider().getSelection(); if (selection instanceof TextSelection) { TextSelection textSelection = (TextSelection) selection; if (textSelection.getLength()==0) { IRegion region = matcher.match(document, textSelection.getOffset()); if (region != null) { if (region.getOffset()+1==textSelection.getOffset()) { editor.selectAndReveal(region.getOffset()+region.getLength(),0); } else { editor.selectAndReveal(region.getOffset()+1,0); } } } } }
@Inject(optional=true) protected void initialize(final IWorkbench workbench) { Assert.isNotNull(Display.getCurrent()); partListener = new PartListener(); pageListener = new PageListener(); for (IWorkbenchWindow window : workbench.getWorkbenchWindows()) { window.addPageListener(pageListener); for (IWorkbenchPage page : window.getPages()) { page.addPartListener(partListener); for (IEditorReference editorRef : page.getEditorReferences()) { Pair<URI, IXtextDocument> entry = getEntry(editorRef); if (entry != null) { resourceUri2document.put(entry.getFirst(), entry.getSecond()); } } } } }
@Override public IRegion getHoverRegion(final ITextViewer textViewer, final int offset) { IXtextDocument xtextDocument = XtextDocumentUtil.get(textViewer); if(xtextDocument == null) return null; //TODO this is being called on change in the UI-thread. Not a good idea to do such expensive stuff. // returning the region on a per token basis would be better. return xtextDocument.readOnly(new IUnitOfWork<IRegion, XtextResource>() { public IRegion exec(XtextResource state) throws Exception { // resource can be null e.g. read only zip/jar entry if (state == null) { return null; } Pair<EObject, IRegion> element = getXtextElementAt(state, offset); if (element != null) { return element.getSecond(); } else { return null; } } }); }
public Object getHoverInfo2(final ITextViewer textViewer, final IRegion hoverRegion) { if (hoverRegion == null) return null; IXtextDocument xtextDocument = XtextDocumentUtil.get(textViewer); if(xtextDocument == null) return null; return xtextDocument.readOnly(new IUnitOfWork<Object, XtextResource>() { public Object exec(XtextResource state) throws Exception { // resource can be null e.g. read only zip/jar entry if (state == null) { return null; } Pair<EObject, IRegion> element = getXtextElementAt(state, hoverRegion.getOffset()); if (element != null && element.getFirst() != null) { return getHoverInfo(element.getFirst(), textViewer, hoverRegion); } return null; } }); }
public void removeDirtyStateSupport(IDirtyStateEditorSupportClient client) { if (this.currentClient == null || this.currentClient != client) throw new IllegalStateException("Was configured with another client or not configured at all."); //$NON-NLS-1$ client.removeVerifyListener(this); stateChangeEventBroker.removeListener(this); if (dirtyResource.isInitialized()) dirtyStateManager.discardDirtyState(delegatingClientAwareResource); IXtextDocument document = client.getDocument(); if (document == null) document = dirtyResource.getUnderlyingDocument(); if (document != null) { dirtyResource.disconnect(document); document.removeModelListener(this); } this.delegatingClientAwareResource = null; this.currentClient = null; }
public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext invocationContext) { ISourceViewer sourceViewer = invocationContext.getSourceViewer(); if (sourceViewer == null) return new ICompletionProposal[0]; final IDocument document = sourceViewer.getDocument(); if (!(document instanceof IXtextDocument)) return new ICompletionProposal[0]; final IXtextDocument xtextDocument = (IXtextDocument) document; final IAnnotationModel annotationModel = sourceViewer.getAnnotationModel(); List<ICompletionProposal> result = Lists.newArrayList(); try { Set<Annotation> applicableAnnotations = getApplicableAnnotations(xtextDocument, annotationModel, invocationContext.getOffset()); result = createQuickfixes(invocationContext, applicableAnnotations); selectAndRevealQuickfix(invocationContext, applicableAnnotations, result); } catch (BadLocationException e) { errorMessage = e.getMessage(); } sortQuickfixes(result); return result.toArray(new ICompletionProposal[result.size()]); }
/** * @since 2.3 */ protected List<ICompletionProposal> createQuickfixes(IQuickAssistInvocationContext invocationContext, Set<Annotation> applicableAnnotations) { List<ICompletionProposal> result = Lists.newArrayList(); ISourceViewer sourceViewer = invocationContext.getSourceViewer(); IAnnotationModel annotationModel = sourceViewer.getAnnotationModel(); IXtextDocument xtextDocument = XtextDocumentUtil.get(sourceViewer); for(Annotation annotation : applicableAnnotations) { if (annotation instanceof SpellingAnnotation) { SpellingProblem spellingProblem = ((SpellingAnnotation) annotation).getSpellingProblem(); result.addAll(asList(spellingProblem.getProposals())); } else { final Issue issue = issueUtil.getIssueFromAnnotation(annotation); if (issue != null) { Iterable<IssueResolution> resolutions = getResolutions(issue, xtextDocument); if (resolutions.iterator().hasNext()) { Position pos = annotationModel.getPosition(annotation); for (IssueResolution resolution : resolutions) { result.add(create(pos, resolution)); } } } } } return result; }
protected void handleInputDocumentChanged(IDocument oldInput, IDocument newInput) { if (shouldInstallCompletionListener) { ContentAssistantFacade facade = ((ISourceViewerExtension4) textViewer).getContentAssistantFacade(); if (facade != null) { facade.addCompletionListener(documentListener); } shouldInstallCompletionListener = false; } if (oldInput instanceof IXtextDocument) { ((IXtextDocument) oldInput).removeXtextDocumentContentObserver(documentListener); } if (newInput instanceof IXtextDocument) { ((IXtextDocument) newInput).addXtextDocumentContentObserver(documentListener); final IXtextDocument document = XtextDocumentUtil.get(textViewer); strategy.setDocument(document); if (!initalProcessDone && strategy instanceof IReconcilingStrategyExtension) { initalProcessDone = true; IReconcilingStrategyExtension reconcilingStrategyExtension = (IReconcilingStrategyExtension) strategy; reconcilingStrategyExtension.initialReconcile(); } } if (oldInput != null && newInput != null) { handleDocumentChanged(new InputChangedDocumentEvent(oldInput, newInput)); } }
@Override protected IStatus run(final IProgressMonitor monitor) { if (monitor.isCanceled() || paused) return Status.CANCEL_STATUS; long start = System.currentTimeMillis(); final IXtextDocument document = XtextDocumentUtil.get(textViewer); if (document instanceof XtextDocument) { ((XtextDocument) document).internalModify(new IUnitOfWork.Void<XtextResource>() { @Override public void process(XtextResource state) throws Exception { doRun(state, monitor); } }); } if (log.isDebugEnabled()) log.debug("Reconciliation finished. Time required: " + (System.currentTimeMillis() - start)); //$NON-NLS-1$ return Status.OK_STATUS; }
private boolean checkTransliterationHasNoErrors(BTSText text2) { // XXX irgendwo fehler: wenn vorher irgendwann man errors drin waren, // bleibt das auch wenn man den text wechselt... IXtextDocument document = embeddedEditor.getDocument(); EList<EObject> objects = document .readOnly(new IUnitOfWork<EList<EObject>, XtextResource>() { @Override public EList<EObject> exec(XtextResource state) throws Exception { return state.getContents(); } }); EObject eo = objects.get(0); Resource resource = eo.eResource(); boolean valid = checkResourceErrors(resource); return valid; }
protected void updateModelFromTranscription() { if (selectedLemmaEntry != null) { IAnnotationModel am = embeddedEditor.getViewer() .getAnnotationModel(); IXtextDocument document = embeddedEditor.getDocument(); EList<EObject> objects = document .readOnly(new IUnitOfWork<EList<EObject>, XtextResource>() { @Override public EList<EObject> exec(XtextResource state) throws Exception { return state.getContents(); } }); EObject eo = objects.get(0); if (eo instanceof TextContent) { textContent = lemmaEditorController.updateModelFromTextContent(textContent, eo, am); } } }
@Override public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { if (getContentProposalProvider() == null) return null; IXtextDocument document = (IXtextDocument) viewer.getDocument(); final CancelableCompletionProposalComputer computer = createCompletionProposalComputer(viewer, offset); ICompletionProposal[] result = document .readOnly(new CancelableUnitOfWork<ICompletionProposal[], XtextResource>() { @Override public ICompletionProposal[] exec(XtextResource state, CancelIndicator cancelIndicator) throws Exception { computer.setCancelIndicator(cancelIndicator); try { return computer.exec(state); } catch (Throwable t) { return new ICompletionProposal[] {}; } } }); Arrays.sort(result, getCompletionProposalComparator()); result = getCompletionProposalPostProcessor().postProcess(result); return result; }
@Override protected void computeCommentFolding(final IXtextDocument xtextDocument, final IFoldingRegionAcceptor<ITextRegion> foldingRegionAcceptor, final ITypedRegion typedRegion, final boolean initiallyFolded) throws BadLocationException { final int offset = typedRegion.getOffset(); final int length = typedRegion.getLength(); final Matcher matcher = getTextPatternInComment().matcher(xtextDocument.get(offset, length)); ((GamaFoldingRegionAcceptor) foldingRegionAcceptor).type = typedRegion.getType(); if (matcher.find()) { final TextRegion significant = new TextRegion(offset + matcher.start(), 0); ((IFoldingRegionAcceptorExtension<ITextRegion>) foldingRegionAcceptor).accept(offset, length, initiallyFolded, significant); } else { ((IFoldingRegionAcceptorExtension<ITextRegion>) foldingRegionAcceptor).accept(offset, length, initiallyFolded); } }
private Optional<EObject> getEObjectFromUri(URI uri) { try { final EObject[] resultContainer = new EObject[] { null }; IXtextDocument xtextDocument = provider.get().getXtextDocument(uri); xtextDocument.modify(new IUnitOfWork.Void<XtextResource>() { @Override public void process(XtextResource state) throws Exception { resultContainer[0] = state.getEObject(uri.fragment()); } }); return Optional.ofNullable(resultContainer[0]); } catch (Exception e) { LOGGER.warn("GetEObject frum URI failed.", e); return Optional.empty(); } }
@Override protected void handleCursorPositionChanged() { super.handleCursorPositionChanged(); IXtextDocument document = getDocument(); CooperateXtextDocument cooperateXtextDocument = document.getAdapter(CooperateXtextDocument.class); if (cooperateXtextDocument.getResource() == null) { return; } EList<Diagnostic> errors = cooperateXtextDocument.getResource().getErrors(); if (ErrorIndicatorPreferenceHandler.INSTANCE.getErrorAreaIndicatorSetting()) { areaErrorIndicator.doSignal(errors, getCursorPosition()); } if (ErrorIndicatorPreferenceHandler.INSTANCE.getErrorLineIndicatorSetting()) { lineErrorIndicator.doSignal(errors, getCursorPosition()); } }
@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); } } } }); } }
@Override public void createPartControl(Composite parent) { super.createPartControl(parent); IXtextDocument doc = getDocument(); if (null != doc) { doc.readOnly(new IUnitOfWork<T, XtextResource>() { @SuppressWarnings("unchecked") public T exec(XtextResource resource) { EList<?> lst = resource.getContents(); T root; if (lst.isEmpty()) { root = null; } else { root = (T) resource.getContents().get(0); } if (null != resource) { AbstractXTextEditor.this.resourceUri = resource.getURI(); } return root; } }); } }
@Fix(SadlJavaValidator.AMBIGUOUS_NAME) public void addNSQualifier(final Issue issue, final IssueResolutionAcceptor acceptor) { String[] fixes = issue.getData(); Iterator<String> itr = Splitter.on(",").split(fixes[0]).iterator(); while (itr.hasNext()) { // loop over prefixes final String prefix = itr.next(); acceptor.accept(issue, prefix, "Add the namespace prefix '" + prefix + "' to disambiguate name", null, new ISemanticModification() { public void apply(EObject element, IModificationContext context) throws Exception { if (element instanceof ResourceByName) { IXtextDocument xtextDocument = context.getXtextDocument(); if (xtextDocument instanceof XtextDocument) { int insertAt = issue.getOffset(); xtextDocument.replace(insertAt, issue.getLength(), prefix); } } } }); } }
@Override public void partActivated(final IWorkbenchPart part) { if (part instanceof XtextEditor) { XtextEditor xtextEditor = (XtextEditor) part; IXtextDocument xtextDocument = xtextEditor.getDocument(); if (xtextDocument != lastActiveDocument) { selectionLinker.setXtextEditor(xtextEditor); final IFigure contents = xtextDocument.readOnly(new IUnitOfWork<IFigure, XtextResource>() { @Override public IFigure exec(final XtextResource resource) throws Exception { return createFigure(resource); } }); if (contents != null) { view.setContents(contents); if (lastActiveDocument != null) { lastActiveDocument.removeModelListener(this); } lastActiveDocument = xtextDocument; lastActiveDocument.addModelListener(this); } } } }
@Fix(Diagnostic.LINKING_DIAGNOSTIC) public void createMissingEntity(final Issue issue, final IssueResolutionAcceptor acceptor) { final ISemanticModification _function = new ISemanticModification() { @Override public void apply(final EObject element, final IModificationContext context) throws Exception { Entity _containerOfType = EcoreUtil2.<Entity>getContainerOfType(element, Entity.class); IXtextDocument _xtextDocument = context.getXtextDocument(); Integer _offset = issue.getOffset(); Integer _length = issue.getLength(); String _get = _xtextDocument.get((_offset).intValue(), (_length).intValue()); EntitiesModelUtil.addEntityAfter(_containerOfType, _get); } }; acceptor.accept(issue, "Create missing entity", "Create missing entity", "Entity.gif", _function); }