Search in sources :

Example 81 with IXtextDocument

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

the class XtendHoverInEditorTest method testHoverOfReferencedElement.

@Test
public void testHoverOfReferencedElement() {
    try {
        StringConcatenation _builder = new StringConcatenation();
        _builder.append("/**");
        _builder.newLine();
        _builder.append(" ");
        _builder.append("* Hello Foo");
        _builder.newLine();
        _builder.append(" ");
        _builder.append("*/");
        _builder.newLine();
        _builder.append("class Foo {}");
        _builder.newLine();
        final String contentFoo = _builder.toString();
        StringConcatenation _builder_1 = new StringConcatenation();
        _builder_1.append("class Bar extends Foo {}");
        _builder_1.newLine();
        final String contentBar = _builder_1.toString();
        final IFile fileFoo = this.helper.createFile("Foo.xtend", contentFoo);
        final IFile fileBar = this.helper.createFile("Bar.xtend", contentBar);
        this._syncUtil.waitForBuild(null);
        final XtextEditor editor = this.helper.openEditor(fileBar);
        ISourceViewer _internalSourceViewer = editor.getInternalSourceViewer();
        Region _region = new Region(19, 1);
        Object _hoverInfo2 = ((ITextHoverExtension2) this.hoverer).getHoverInfo2(((ITextViewer) _internalSourceViewer), _region);
        final XtextBrowserInformationControlInput info = ((XtextBrowserInformationControlInput) _hoverInfo2);
        Assert.assertTrue(info.getHtml().contains("Hello Foo"));
        final XtextEditor fooEditor = this.helper.openEditor(fileFoo);
        IXtextDocument _document = fooEditor.getDocument();
        StringConcatenation _builder_2 = new StringConcatenation();
        _builder_2.append("/**");
        _builder_2.newLine();
        _builder_2.append(" ");
        _builder_2.append("* Hello BAZ");
        _builder_2.newLine();
        _builder_2.append(" ");
        _builder_2.append("*/");
        _builder_2.newLine();
        _builder_2.append("class Foo {}");
        _builder_2.newLine();
        _document.set(_builder_2.toString());
        this._syncUtil.waitForReconciler(fooEditor);
        this._syncUtil.waitForReconciler(editor);
        ISourceViewer _internalSourceViewer_1 = editor.getInternalSourceViewer();
        Region _region_1 = new Region(19, 1);
        Object _hoverInfo2_1 = ((ITextHoverExtension2) this.hoverer).getHoverInfo2(((ITextViewer) _internalSourceViewer_1), _region_1);
        final XtextBrowserInformationControlInput info2 = ((XtextBrowserInformationControlInput) _hoverInfo2_1);
        Assert.assertFalse(info2.getHtml().contains("Hello Foo"));
        Assert.assertTrue(info2.getHtml().contains("Hello BAZ"));
    } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
    }
}
Also used : IFile(org.eclipse.core.resources.IFile) XtextEditor(org.eclipse.xtext.ui.editor.XtextEditor) StringConcatenation(org.eclipse.xtend2.lib.StringConcatenation) Region(org.eclipse.jface.text.Region) ITextHoverExtension2(org.eclipse.jface.text.ITextHoverExtension2) XtextBrowserInformationControlInput(org.eclipse.xtext.ui.editor.hover.html.XtextBrowserInformationControlInput) ISourceViewer(org.eclipse.jface.text.source.ISourceViewer) ITextViewer(org.eclipse.jface.text.ITextViewer) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Test(org.junit.Test)

Example 82 with IXtextDocument

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

the class XtendQuickfixProvider method internalDoAddAbstractKeyword.

protected void internalDoAddAbstractKeyword(EObject element, IModificationContext context) throws BadLocationException {
    if (element instanceof XtendFunction) {
        element = element.eContainer();
    }
    if (element instanceof XtendClass) {
        XtendClass clazz = (XtendClass) element;
        IXtextDocument document = context.getXtextDocument();
        ICompositeNode clazzNode = NodeModelUtils.findActualNodeFor(clazz);
        if (clazzNode == null)
            throw new IllegalStateException("Cannot determine node for clazz " + clazz.getName());
        int offset = -1;
        for (ILeafNode leafNode : clazzNode.getLeafNodes()) {
            if (leafNode.getText().equals("class")) {
                offset = leafNode.getOffset();
                break;
            }
        }
        ReplacingAppendable appendable = appendableFactory.create(document, (XtextResource) clazz.eResource(), offset, 0);
        appendable.append("abstract ");
        appendable.commitChanges();
    }
}
Also used : XtendFunction(org.eclipse.xtend.core.xtend.XtendFunction) ILeafNode(org.eclipse.xtext.nodemodel.ILeafNode) XtendClass(org.eclipse.xtend.core.xtend.XtendClass) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) ReplacingAppendable(org.eclipse.xtext.xbase.ui.contentassist.ReplacingAppendable) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument)

Example 83 with IXtextDocument

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

the class XtendQuickfixProvider method removeUnusedPrivateMember.

@Fix(IssueCodes.UNUSED_PRIVATE_MEMBER)
public void removeUnusedPrivateMember(final Issue issue, IssueResolutionAcceptor acceptor) {
    // use the same label, description and image
    // to be able to use the quickfixes (issue resolution) in batch mode
    String label = "Remove member.";
    String description = "Remove the unused private member.";
    String image = "delete_edit.png";
    acceptor.accept(issue, label, description, image, new IModification() {

        @Override
        public void apply(IModificationContext context) throws Exception {
            final IXtextDocument document = context.getXtextDocument();
            document.modify(new IUnitOfWork.Void<XtextResource>() {

                @Override
                public void process(XtextResource state) throws Exception {
                    final EObject element = state.getEObject(issue.getUriToProblem().fragment());
                    final ICompositeNode elementNode = NodeModelUtils.findActualNodeFor(element);
                    final Position elementPosition = new Position(elementNode.getOffset(), elementNode.getLength());
                    document.addPosition(elementPosition);
                    if (element instanceof XtendField) {
                        final JvmField field = associations.getJvmField((XtendField) element);
                        final List<Position> assignments = EcoreUtil2.eAllContentsAsList(element.eResource()).stream().filter(XAssignment.class::isInstance).map(XAssignment.class::cast).filter(assignment -> field == assignment.getFeature()).map(assignment -> {
                            final ICompositeNode assignmentNode = NodeModelUtils.findActualNodeFor(assignment);
                            final int offset = assignmentNode.getOffset();
                            final XExpression assignmentValue = assignment.getValue();
                            int length = assignmentNode.getLength();
                            if (expressionHelper.hasSideEffects(assignmentValue)) {
                                length -= NodeModelUtils.findActualNodeFor(assignmentValue).getLength();
                            }
                            return new Position(offset, length);
                        }).collect(Collectors.toList());
                        for (final Position assignment : assignments) {
                            document.addPosition(assignment);
                        }
                        for (final Position assignment : assignments) {
                            document.replace(assignment.getOffset(), assignment.getLength(), "");
                        }
                    }
                    document.replace(elementPosition.getOffset(), elementPosition.getLength(), "");
                }
            });
            organizeImportsHandler.doOrganizeImports(document);
        }
    });
}
Also used : XtendField(org.eclipse.xtend.core.xtend.XtendField) ITextualMultiModification(org.eclipse.xtext.ui.editor.model.edit.ITextualMultiModification) CoreException(org.eclipse.core.runtime.CoreException) IssueResolutionAcceptor(org.eclipse.xtext.ui.editor.quickfix.IssueResolutionAcceptor) ILeafNode(org.eclipse.xtext.nodemodel.ILeafNode) OrganizeImportsHandler(org.eclipse.xtext.xbase.ui.imports.OrganizeImportsHandler) IRenameRefactoringProvider(org.eclipse.xtext.ui.refactoring.IRenameRefactoringProvider) JvmOperation(org.eclipse.xtext.common.types.JvmOperation) PlatformUI(org.eclipse.ui.PlatformUI) Strings(org.eclipse.xtext.util.Strings) Set(java.util.Set) ISemanticModification(org.eclipse.xtext.ui.editor.model.edit.ISemanticModification) IssueResolution(org.eclipse.xtext.ui.editor.quickfix.IssueResolution) XtendFunction(org.eclipse.xtend.core.xtend.XtendFunction) RenameElementProcessor(org.eclipse.xtext.ui.refactoring.impl.RenameElementProcessor) JvmTypeReference(org.eclipse.xtext.common.types.JvmTypeReference) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Singleton(com.google.inject.Singleton) Iterables(com.google.common.collect.Iterables) ResourcesPlugin(org.eclipse.core.resources.ResourcesPlugin) IJavaProjectProvider(org.eclipse.xtext.common.types.access.jdt.IJavaProjectProvider) URI(org.eclipse.emf.common.util.URI) InsertionOffsets(org.eclipse.xtend.ide.codebuilder.InsertionOffsets) StopWatch(org.eclipse.xtext.util.StopWatch) JvmGenericType(org.eclipse.xtext.common.types.JvmGenericType) Diagnostic(org.eclipse.xtext.diagnostics.Diagnostic) NodeModelUtils(org.eclipse.xtext.nodemodel.util.NodeModelUtils) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) ArrayList(java.util.ArrayList) TypesPackage(org.eclipse.xtext.common.types.TypesPackage) IModification(org.eclipse.xtext.ui.editor.model.edit.IModification) Lists(com.google.common.collect.Lists) XtendTypeDeclaration(org.eclipse.xtend.core.xtend.XtendTypeDeclaration) OverrideHelper(org.eclipse.xtext.xbase.typesystem.override.OverrideHelper) XbaseQuickfixProvider(org.eclipse.xtext.xbase.ui.quickfix.XbaseQuickfixProvider) IFile(org.eclipse.core.resources.IFile) BadLocationException(org.eclipse.jface.text.BadLocationException) IXtendJvmAssociations(org.eclipse.xtend.core.jvmmodel.IXtendJvmAssociations) JvmConstructor(org.eclipse.xtext.common.types.JvmConstructor) EReference(org.eclipse.emf.ecore.EReference) XtendFile(org.eclipse.xtend.core.xtend.XtendFile) XtendPackage(org.eclipse.xtend.core.xtend.XtendPackage) JvmIdentifiableElement(org.eclipse.xtext.common.types.JvmIdentifiableElement) XAssignment(org.eclipse.xtext.xbase.XAssignment) Junit5LibClasspathAdder(org.eclipse.xtend.ide.buildpath.Junit5LibClasspathAdder) Issue(org.eclipse.xtext.validation.Issue) TextSelection(org.eclipse.jface.text.TextSelection) PerformChangeOperation(org.eclipse.ltk.core.refactoring.PerformChangeOperation) ResolvedConstructor(org.eclipse.xtext.xbase.typesystem.override.ResolvedConstructor) XAnnotation(org.eclipse.xtext.xbase.annotations.xAnnotations.XAnnotation) LightweightTypeReference(org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference) ResolvedFeatures(org.eclipse.xtext.xbase.typesystem.override.ResolvedFeatures) RefactoringCore(org.eclipse.ltk.core.refactoring.RefactoringCore) Inject(com.google.inject.Inject) EStructuralFeature(org.eclipse.emf.ecore.EStructuralFeature) IssueCodes(org.eclipse.xtend.core.validation.IssueCodes) Logger(org.apache.log4j.Logger) Junit4LibClasspathAdder(org.eclipse.xtend.ide.buildpath.Junit4LibClasspathAdder) IPath(org.eclipse.core.runtime.IPath) IRenameContextFactory(org.eclipse.xtext.ui.refactoring.ui.IRenameContextFactory) Change(org.eclipse.ltk.core.refactoring.Change) IRenameElementContext(org.eclipse.xtext.ui.refactoring.ui.IRenameElementContext) INode(org.eclipse.xtext.nodemodel.INode) Objects(com.google.common.base.Objects) Position(org.eclipse.jface.text.Position) IJavaProject(org.eclipse.jdt.core.IJavaProject) EObject(org.eclipse.emf.ecore.EObject) XFeatureCall(org.eclipse.xtext.xbase.XFeatureCall) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) XtendGrammarAccess(org.eclipse.xtend.core.services.XtendGrammarAccess) Keyword(org.eclipse.xtext.Keyword) List(java.util.List) ReplacingAppendable(org.eclipse.xtext.xbase.ui.contentassist.ReplacingAppendable) IBatchTypeResolver(org.eclipse.xtext.xbase.typesystem.IBatchTypeResolver) DisplayRunHelper(org.eclipse.xtext.ui.util.DisplayRunHelper) XBlockExpression(org.eclipse.xtext.xbase.XBlockExpression) TypeReferences(org.eclipse.xtext.common.types.util.TypeReferences) ProjectUtil(org.eclipse.xtext.ui.refactoring.impl.ProjectUtil) XtendLibClasspathAdder(org.eclipse.xtend.ide.buildpath.XtendLibClasspathAdder) XIfExpression(org.eclipse.xtext.xbase.XIfExpression) MemberFromSuperImplementor(org.eclipse.xtend.ide.codebuilder.MemberFromSuperImplementor) JvmType(org.eclipse.xtext.common.types.JvmType) IssueModificationContext(org.eclipse.xtext.ui.editor.model.edit.IssueModificationContext) EcoreUtil2(org.eclipse.xtext.EcoreUtil2) XtextResource(org.eclipse.xtext.resource.XtextResource) ICompositeModification(org.eclipse.xtext.ui.editor.model.edit.ICompositeModification) XExpression(org.eclipse.xtext.xbase.XExpression) IUnitOfWork(org.eclipse.xtext.util.concurrent.IUnitOfWork) IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) XtendClass(org.eclipse.xtend.core.xtend.XtendClass) XtendExecutable(org.eclipse.xtend.core.xtend.XtendExecutable) JvmField(org.eclipse.xtext.common.types.JvmField) ProcessorBasedRefactoring(org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring) EList(org.eclipse.emf.common.util.EList) OptionalParameters(org.eclipse.xtext.xbase.ui.document.DocumentSourceAppender.Factory.OptionalParameters) JvmDeclaredType(org.eclipse.xtext.common.types.JvmDeclaredType) ITextRegion(org.eclipse.xtext.util.ITextRegion) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IResource(org.eclipse.core.resources.IResource) Fix(org.eclipse.xtext.ui.editor.quickfix.Fix) XtendExpressionHelper(org.eclipse.xtend.core.typing.XtendExpressionHelper) Position(org.eclipse.jface.text.Position) XtextResource(org.eclipse.xtext.resource.XtextResource) CoreException(org.eclipse.core.runtime.CoreException) BadLocationException(org.eclipse.jface.text.BadLocationException) XtendField(org.eclipse.xtend.core.xtend.XtendField) EObject(org.eclipse.emf.ecore.EObject) IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) XExpression(org.eclipse.xtext.xbase.XExpression) JvmField(org.eclipse.xtext.common.types.JvmField) IModification(org.eclipse.xtext.ui.editor.model.edit.IModification) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) XAssignment(org.eclipse.xtext.xbase.XAssignment) Fix(org.eclipse.xtext.ui.editor.quickfix.Fix)

Example 84 with IXtextDocument

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

the class XtendQuickfixProvider method doOverrideMethods.

protected void doOverrideMethods(final Issue issue, IssueResolutionAcceptor acceptor, String label, final String[] operationUris) {
    acceptor.accept(issue, label, label, "fix_indent.gif", new ISemanticModification() {

        @Override
        public void apply(EObject element, IModificationContext context) throws Exception {
            XtendTypeDeclaration clazz = (XtendTypeDeclaration) element;
            JvmGenericType inferredType = (JvmGenericType) associations.getInferredType(clazz);
            ResolvedFeatures resolvedOperations = overrideHelper.getResolvedFeatures(inferredType);
            IXtextDocument document = context.getXtextDocument();
            final int offset = insertionOffsets.getNewMethodInsertOffset(null, clazz);
            int currentIndentation = appendableFactory.getIndentationLevelAtOffset(offset, document, (XtextResource) clazz.eResource());
            final int indentationToUse = clazz.getMembers().isEmpty() ? currentIndentation + 1 : currentIndentation;
            ReplacingAppendable appendable = appendableFactory.create(document, (XtextResource) clazz.eResource(), offset, 0, new OptionalParameters() {

                {
                    ensureEmptyLinesAround = true;
                    baseIndentationLevel = indentationToUse;
                }
            });
            boolean isFirst = true;
            for (String operationUriAsString : operationUris) {
                URI operationURI = URI.createURI(operationUriAsString);
                EObject overridden = clazz.eResource().getResourceSet().getEObject(operationURI, true);
                if (overridden instanceof JvmOperation) {
                    if (!isFirst)
                        appendable.newLine().newLine();
                    isFirst = false;
                    superMemberImplementor.appendOverrideFunction(clazz, resolvedOperations.getResolvedOperation((JvmOperation) overridden), appendable);
                }
            }
            appendable.commitChanges();
        }
    });
}
Also used : ResolvedFeatures(org.eclipse.xtext.xbase.typesystem.override.ResolvedFeatures) ISemanticModification(org.eclipse.xtext.ui.editor.model.edit.ISemanticModification) JvmGenericType(org.eclipse.xtext.common.types.JvmGenericType) XtextResource(org.eclipse.xtext.resource.XtextResource) ReplacingAppendable(org.eclipse.xtext.xbase.ui.contentassist.ReplacingAppendable) URI(org.eclipse.emf.common.util.URI) CoreException(org.eclipse.core.runtime.CoreException) BadLocationException(org.eclipse.jface.text.BadLocationException) JvmOperation(org.eclipse.xtext.common.types.JvmOperation) OptionalParameters(org.eclipse.xtext.xbase.ui.document.DocumentSourceAppender.Factory.OptionalParameters) EObject(org.eclipse.emf.ecore.EObject) IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) XtendTypeDeclaration(org.eclipse.xtend.core.xtend.XtendTypeDeclaration) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument)

Example 85 with IXtextDocument

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

the class XtendQuickfixProvider method surroundWithTryCatch.

@Fix(org.eclipse.xtext.xbase.validation.IssueCodes.UNHANDLED_EXCEPTION)
public void surroundWithTryCatch(final Issue issue, IssueResolutionAcceptor acceptor) {
    if (issue.getData() == null || issue.getData().length <= 1) {
        return;
    }
    IModificationContext modificationContext = getModificationContextFactory().createModificationContext(issue);
    IXtextDocument xtextDocument = modificationContext.getXtextDocument();
    if (xtextDocument == null) {
        return;
    }
    if (isJvmConstructorCall(xtextDocument, issue)) {
        return;
    }
    acceptor.accept(issue, "Surround with try/catch block", "Surround with try/catch block", "fix_indent.gif", new ISemanticModification() {

        @Override
        public void apply(EObject element, IModificationContext context) throws Exception {
            String[] issueData = issue.getData();
            URI childURI = URI.createURI(issueData[issueData.length - 1]);
            XtextResource xtextResource = (XtextResource) element.eResource();
            List<JvmType> exceptions = getExceptions(issueData, xtextResource);
            if (exceptions.size() > 0) {
                EObject childThrowingException = xtextResource.getResourceSet().getEObject(childURI, true);
                XExpression toBeSurrounded = findContainerExpressionInBlockExpression(childThrowingException);
                IXtextDocument xtextDocument = context.getXtextDocument();
                if (toBeSurrounded != null) {
                    ICompositeNode toBeSurroundedNode = NodeModelUtils.findActualNodeFor(toBeSurrounded);
                    if (toBeSurroundedNode == null)
                        throw new IllegalStateException("toBeSurroundedNode may not be null");
                    ITextRegion toBeSurroundedRegion = toBeSurroundedNode.getTextRegion();
                    ReplacingAppendable appendable = appendableFactory.create(context.getXtextDocument(), (XtextResource) childThrowingException.eResource(), toBeSurroundedRegion.getOffset(), toBeSurroundedRegion.getLength());
                    appendable.append("try {").increaseIndentation().newLine().append(xtextDocument.get(toBeSurroundedRegion.getOffset(), toBeSurroundedRegion.getLength())).decreaseIndentation().newLine();
                    for (JvmType exceptionType : exceptions) {
                        appendable.append("} catch (").append(exceptionType).append(" exc) {").increaseIndentation().newLine().append("throw new RuntimeException(\"auto-generated try/catch\", exc)").decreaseIndentation().newLine();
                    }
                    appendable.append("}");
                    appendable.commitChanges();
                }
            }
        }
    });
}
Also used : ISemanticModification(org.eclipse.xtext.ui.editor.model.edit.ISemanticModification) XtextResource(org.eclipse.xtext.resource.XtextResource) ReplacingAppendable(org.eclipse.xtext.xbase.ui.contentassist.ReplacingAppendable) JvmType(org.eclipse.xtext.common.types.JvmType) URI(org.eclipse.emf.common.util.URI) CoreException(org.eclipse.core.runtime.CoreException) BadLocationException(org.eclipse.jface.text.BadLocationException) ITextRegion(org.eclipse.xtext.util.ITextRegion) EObject(org.eclipse.emf.ecore.EObject) IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) ArrayList(java.util.ArrayList) List(java.util.List) EList(org.eclipse.emf.common.util.EList) XExpression(org.eclipse.xtext.xbase.XExpression) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Fix(org.eclipse.xtext.ui.editor.quickfix.Fix)

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