Search in sources :

Example 41 with IXtextDocument

use of org.eclipse.xtext.ui.editor.model.IXtextDocument in project xtext-eclipse by eclipse.

the class XbaseQuickfixProvider method fixIncompleteCasesOnEnum.

@Fix(IssueCodes.INCOMPLETE_CASES_ON_ENUM)
public void fixIncompleteCasesOnEnum(final Issue issue, IssueResolutionAcceptor acceptor) {
    acceptor.accept(issue, "Add 'default' case", "Add 'default' case", null, new ISemanticModification() {

        @Override
        public void apply(EObject element, IModificationContext context) throws Exception {
            XSwitchExpression switchExpression = EcoreUtil2.getContainerOfType(element, XSwitchExpression.class);
            if (switchExpression == null) {
                return;
            }
            int insertOffset = getInsertOffset(switchExpression);
            IXtextDocument document = context.getXtextDocument();
            ReplacingAppendable appendable = appendableFactory.create(document, (XtextResource) element.eResource(), insertOffset, 0);
            if (switchExpression.getCases().isEmpty()) {
                appendable.increaseIndentation();
            }
            appendable.newLine();
            appendable.append("default: {");
            appendable.newLine().append("}");
            appendable.commitChanges();
        }
    });
    acceptor.accept(issue, "Add missing cases", "Add missing cases", null, new ISemanticModification() {

        @Override
        public void apply(EObject element, IModificationContext context) throws Exception {
            XSwitchExpression switchExpression = EcoreUtil2.getContainerOfType(element, XSwitchExpression.class);
            if (switchExpression == null) {
                return;
            }
            int insertOffset = getInsertOffset(switchExpression);
            IXtextDocument document = context.getXtextDocument();
            ReplacingAppendable appendable = appendableFactory.create(document, (XtextResource) element.eResource(), insertOffset, 0);
            if (switchExpression.getCases().isEmpty()) {
                appendable.increaseIndentation();
            }
            for (String expectedEnumerationLiteral : issue.getData()) {
                appendable.newLine().append("case ").append(expectedEnumerationLiteral).append(": {");
                appendable.newLine().append("}");
            }
            appendable.commitChanges();
        }
    });
}
Also used : EObject(org.eclipse.emf.ecore.EObject) ISemanticModification(org.eclipse.xtext.ui.editor.model.edit.ISemanticModification) IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) XSwitchExpression(org.eclipse.xtext.xbase.XSwitchExpression) XtextResource(org.eclipse.xtext.resource.XtextResource) ReplacingAppendable(org.eclipse.xtext.xbase.ui.contentassist.ReplacingAppendable) WrappedException(org.eclipse.emf.common.util.WrappedException) BadLocationException(org.eclipse.jface.text.BadLocationException) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Fix(org.eclipse.xtext.ui.editor.quickfix.Fix)

Example 42 with IXtextDocument

use of org.eclipse.xtext.ui.editor.model.IXtextDocument in project xtext-eclipse by eclipse.

the class ExtractVariableHandler method execute.

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    try {
        syncUtil.totalSync(false);
        final XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
        if (editor != null) {
            final ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
            final IXtextDocument document = editor.getDocument();
            XtextResource resource = document.priorityReadOnly(new IUnitOfWork<XtextResource, XtextResource>() {

                @Override
                public XtextResource exec(XtextResource state) throws Exception {
                    return resourceCopier.loadIntoNewResourceSet(state);
                }
            });
            XExpression expression = expressionUtil.findSelectedExpression(resource, selection);
            if (expression != null) {
                ExtractVariableRefactoring introduceVariableRefactoring = refactoringProvider.get();
                if (introduceVariableRefactoring.initialize(editor, expression)) {
                    ITextRegion region = locationInFileProvider.getFullTextRegion(expression);
                    editor.selectAndReveal(region.getOffset(), region.getLength());
                    ExtractVariableWizard wizard = new ExtractVariableWizard(introduceVariableRefactoring);
                    RefactoringWizardOpenOperation_NonForking openOperation = new RefactoringWizardOpenOperation_NonForking(wizard);
                    openOperation.run(editor.getSite().getShell(), "Extract Local Variable");
                }
            }
        }
    } catch (InterruptedException e) {
        return null;
    } catch (Exception exc) {
        LOG.error("Error during refactoring", exc);
        MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error during refactoring", exc.getMessage() + "\nSee log for details");
    }
    return null;
}
Also used : XtextEditor(org.eclipse.xtext.ui.editor.XtextEditor) XtextResource(org.eclipse.xtext.resource.XtextResource) ITextSelection(org.eclipse.jface.text.ITextSelection) ExecutionException(org.eclipse.core.commands.ExecutionException) RefactoringWizardOpenOperation_NonForking(org.eclipse.xtext.ui.refactoring.ui.RefactoringWizardOpenOperation_NonForking) ITextRegion(org.eclipse.xtext.util.ITextRegion) XExpression(org.eclipse.xtext.xbase.XExpression) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument)

Example 43 with IXtextDocument

use of org.eclipse.xtext.ui.editor.model.IXtextDocument in project xtext-eclipse by eclipse.

the class XtextGrammarQuickfixProviderTest method assertAndApplyAllResolutions.

private void assertAndApplyAllResolutions(XtextEditor xtextEditor, String issueCode, int issueDataCount, int issueCount, String resolutionLabel) throws CoreException {
    InternalBuilderTest.setAutoBuild(true);
    if (xtextEditor.isDirty()) {
        xtextEditor.doSave(new NullProgressMonitor());
    }
    InternalBuilderTest.fullBuild();
    IXtextDocument document = xtextEditor.getDocument();
    validateInEditor(document);
    List<Issue> issues = getIssues(document);
    assertFalse("Document has no issues, but should.", issues.isEmpty());
    issues.iterator().forEachRemaining((issue) -> {
        assertEquals(issueCode, issue.getCode());
        assertNotNull(issue.getData());
        assertEquals(issueDataCount, issue.getData().length);
    });
    IResource resource = xtextEditor.getResource();
    IMarker[] problems = resource.findMarkers(MarkerTypes.FAST_VALIDATION, true, IResource.DEPTH_INFINITE);
    assertEquals("Resource should have " + issueCount + " error marker.", issueCount, problems.length);
    validateInEditor(document);
    MarkerResolutionGenerator instance = injector.getInstance(MarkerResolutionGenerator.class);
    List<IMarkerResolution> resolutions = Lists.newArrayList(instance.getResolutions(problems[0]));
    assertEquals(1, resolutions.size());
    IMarkerResolution resolution = resolutions.iterator().next();
    assertTrue(resolution instanceof WorkbenchMarkerResolution);
    WorkbenchMarkerResolution workbenchResolution = (WorkbenchMarkerResolution) resolution;
    IMarker primaryMarker = problems[0];
    List<IMarker> others = Lists.newArrayList(workbenchResolution.findOtherMarkers(problems));
    assertFalse(others.contains(primaryMarker));
    assertEquals(problems.length - 1, others.size());
    others.add(primaryMarker);
    workbenchResolution.run(others.toArray(new IMarker[others.size()]), new NullProgressMonitor());
    if (xtextEditor.isDirty()) {
        xtextEditor.doSave(null);
    }
    InternalBuilderTest.cleanBuild();
    problems = resource.findMarkers(MarkerTypes.FAST_VALIDATION, true, IResource.DEPTH_INFINITE);
    assertEquals("Resource should have no error marker.", 0, problems.length);
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) Issue(org.eclipse.xtext.validation.Issue) IMarkerResolution(org.eclipse.ui.IMarkerResolution) IMarker(org.eclipse.core.resources.IMarker) MarkerResolutionGenerator(org.eclipse.xtext.ui.editor.quickfix.MarkerResolutionGenerator) WorkbenchMarkerResolution(org.eclipse.ui.views.markers.WorkbenchMarkerResolution) IResource(org.eclipse.core.resources.IResource) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument)

Example 44 with IXtextDocument

use of org.eclipse.xtext.ui.editor.model.IXtextDocument in project xtext-eclipse by eclipse.

the class XtextGrammarQuickfixProvider method fixImportedPackageFromSuperGrammar.

@Fix(INVALID_PACKAGE_REFERENCE_INHERITED)
public void fixImportedPackageFromSuperGrammar(final Issue issue, IssueResolutionAcceptor acceptor) {
    if (issue.getData().length == 1)
        acceptor.accept(issue, "Change to '" + issue.getData()[0] + "'", "Fix the bogus package import\n" + "import '" + issue.getData()[0] + "'", NULL_QUICKFIX_IMAGE, new IModification() {

            @Override
            public void apply(IModificationContext context) throws BadLocationException {
                String replaceString = valueConverterService.toString(issue.getData()[0], "STRING");
                IXtextDocument document = context.getXtextDocument();
                String delimiter = document.get(issue.getOffset(), 1);
                if (!replaceString.startsWith(delimiter)) {
                    replaceString = delimiter + replaceString.substring(1, replaceString.length() - 1) + delimiter;
                }
                document.replace(issue.getOffset(), issue.getLength(), replaceString);
            }
        });
}
Also used : IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) IModification(org.eclipse.xtext.ui.editor.model.edit.IModification) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Fix(org.eclipse.xtext.ui.editor.quickfix.Fix)

Example 45 with IXtextDocument

use of org.eclipse.xtext.ui.editor.model.IXtextDocument in project xtext-eclipse by eclipse.

the class ToSaveOrNotToSaveTest method renameFooToFooBar.

protected void renameFooToFooBar(final XtextEditor contextEditor) throws Exception {
    contextEditor.getEditorSite().getPage().activate(contextEditor);
    waitForDisplay();
    IXtextDocument document = contextEditor.getDocument();
    final int offset = document.get().indexOf("foo");
    contextEditor.selectAndReveal(offset, 3);
    EvaluationContext evaluationContext = new EvaluationContext(null, new Object());
    evaluationContext.addVariable(ISources.ACTIVE_EDITOR_NAME, contextEditor);
    ExecutionEvent executionEvent = new ExecutionEvent(null, newHashMap(), null, evaluationContext);
    renameElementHandler.execute(executionEvent);
    // syncUtil.totalSync(refactoringPreferences.isSaveAllBeforeRefactoring());
    // IRenameElementContext context = document.readOnly(new IUnitOfWork<IRenameElementContext, XtextResource>() {
    // public IRenameElementContext exec(XtextResource state) throws Exception {
    // EObject target = eObjectAtOffsetHelper.resolveElementAt(state, offset);
    // return renameContextFactory.createRenameElementContext(target, contextEditor, new TextSelection(offset,
    // 3), state);
    // }
    // });
    // controller.initialize(context);
    // waitForDisplay();
    // controller.startRefactoring(RefactoringType.LINKED_EDITING);
    // waitForDisplay();
    pressKeys(contextEditor, "fooBar\n");
    waitForDisplay();
    waitForReconciler(fooEditor);
    waitForReconciler(barEditor);
    waitForDisplay();
}
Also used : ExecutionEvent(org.eclipse.core.commands.ExecutionEvent) EvaluationContext(org.eclipse.core.expressions.EvaluationContext) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument)

Aggregations

IXtextDocument (org.eclipse.xtext.ui.editor.model.IXtextDocument)147 XtextResource (org.eclipse.xtext.resource.XtextResource)51 Test (org.junit.Test)46 XtextEditor (org.eclipse.xtext.ui.editor.XtextEditor)38 IFile (org.eclipse.core.resources.IFile)37 BadLocationException (org.eclipse.jface.text.BadLocationException)26 AbstractEditorTest (org.eclipse.xtext.ui.testing.AbstractEditorTest)26 IUnitOfWork (org.eclipse.xtext.util.concurrent.IUnitOfWork)25 IModificationContext (org.eclipse.xtext.ui.editor.model.edit.IModificationContext)23 EObject (org.eclipse.emf.ecore.EObject)22 DefaultFoldingRegionProvider (org.eclipse.xtext.ui.editor.folding.DefaultFoldingRegionProvider)18 FoldedPosition (org.eclipse.xtext.ui.editor.folding.FoldedPosition)18 Fix (org.eclipse.xtext.ui.editor.quickfix.Fix)16 List (java.util.List)12 ICompletionProposal (org.eclipse.jface.text.contentassist.ICompletionProposal)12 ArrayList (java.util.ArrayList)11 Issue (org.eclipse.xtext.validation.Issue)11 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)10 URI (org.eclipse.emf.common.util.URI)9 IRegion (org.eclipse.jface.text.IRegion)9