Search in sources :

Example 11 with IXtextDocument

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

the class XtendQuickfixProvider method refactorTernaryOperatorIntoNormalIf.

@Fix(IssueCodes.TERNARY_EXPRESSION_NOT_ALLOWED)
public void refactorTernaryOperatorIntoNormalIf(final Issue issue, IssueResolutionAcceptor acceptor) {
    String label = "Refactor into inline if-expression.";
    String description = "Refactor ternary expression (cond? a : b) \ninto an inline if-expression (if cond a else b).";
    String image = "delete_edit.png";
    // stop before NullpointerExceptions are thrown
    if (issue == null)
        return;
    // Fix
    acceptor.accept(issue, label, description, image, new ISemanticModification() {

        @Override
        public void apply(EObject element, IModificationContext context) throws Exception {
            // Collect basic elements
            IXtextDocument xtextDocument = context.getXtextDocument();
            if (xtextDocument == null || element == null || !(element instanceof XExpression))
                return;
            XIfExpression exp = (XIfExpression) element;
            // Collect original ternary expression information
            ICompositeNode expNode = NodeModelUtils.findActualNodeFor(exp);
            if (expNode == null)
                throw new IllegalStateException("Node to refactor may not be null");
            int expOffset = expNode.getTextRegion().getOffset();
            int expLength = expNode.getTextRegion().getLength();
            String ifExpr = this.buildIfExpression(exp, xtextDocument);
            xtextDocument.replace(expOffset, expLength, ifExpr);
        }

        /**
         * Build an inline if expression from the given ternary expression
         * Also apply this fix to nested elements in then or else part
         */
        private String buildIfExpression(XIfExpression expression, IXtextDocument document) throws Exception {
            // Basic elements
            XExpression thenPart = expression.getThen();
            XExpression elsePart = expression.getElse();
            boolean outerBracketsSet = false;
            // Collect String representations
            String ternExpStr = this.getString(NodeModelUtils.findActualNodeFor(expression), document);
            if (ternExpStr.endsWith(")"))
                outerBracketsSet = true;
            String condStr = this.getString(NodeModelUtils.findActualNodeFor(expression.getIf()), document);
            if (!condStr.contains("(")) {
                condStr = "(" + condStr + ")";
            }
            // Check if then or else part is a ternary expression, too,
            // and apply the fix to the inner elements
            String thenStr = "", elseStr = "";
            if (thenPart instanceof XIfExpression) {
                if (((XIfExpression) thenPart).isConditionalExpression()) {
                    thenStr = buildIfExpression((XIfExpression) thenPart, document);
                }
            }
            if (elsePart != null && elsePart instanceof XIfExpression) {
                if (((XIfExpression) elsePart).isConditionalExpression()) {
                    elseStr = buildIfExpression((XIfExpression) elsePart, document);
                }
            }
            // if then/else part does not contain nested ternary expressions
            if (thenStr.isEmpty()) {
                thenStr = this.getString(NodeModelUtils.findActualNodeFor(thenPart), document);
            }
            if (elsePart != null && elseStr.isEmpty()) {
                elseStr = this.getString(NodeModelUtils.findActualNodeFor(elsePart), document);
            }
            // Combine
            String ifExpStr = this.combineIfExpParts(condStr, thenStr, elseStr, outerBracketsSet);
            return ifExpStr;
        }

        /**
         * Stitch together the inline if statement
         */
        private String combineIfExpParts(String condStr, String thenStr, String elseStr, boolean outerBracketsSet) {
            String ifExpr = "if " + condStr + " " + thenStr;
            if (!elseStr.isEmpty())
                ifExpr += " else " + elseStr;
            if (outerBracketsSet)
                ifExpr = "(" + ifExpr + ")";
            return ifExpr;
        }

        /**
         * Get the String from a document Node
         * Attention! The Document will not be updated in the meantime, so offsets and thus
         * the outputString might get messed up, if the document is changed and the String
         * is fetched after that.
         */
        private String getString(ICompositeNode partNode, IXtextDocument doc) throws Exception {
            if (partNode == null)
                throw new IllegalStateException("Node to refactor may not be null");
            ITextRegion partRegion = partNode.getTextRegion();
            int partOffset = partRegion.getOffset();
            int partLength = partRegion.getLength();
            String partString = doc.get(partOffset, partLength);
            return partString;
        }
    });
}
Also used : ISemanticModification(org.eclipse.xtext.ui.editor.model.edit.ISemanticModification) CoreException(org.eclipse.core.runtime.CoreException) BadLocationException(org.eclipse.jface.text.BadLocationException) XIfExpression(org.eclipse.xtext.xbase.XIfExpression) 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) XExpression(org.eclipse.xtext.xbase.XExpression) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Fix(org.eclipse.xtext.ui.editor.quickfix.Fix)

Example 12 with IXtextDocument

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

the class XtendQuickfixProvider method removeUnnecessaryModifier.

@Fix(IssueCodes.UNNECESSARY_MODIFIER)
public void removeUnnecessaryModifier(final Issue issue, IssueResolutionAcceptor acceptor) {
    String[] issueData = issue.getData();
    if (issueData == null || issueData.length == 0) {
        return;
    }
    // use the same label, description and image
    // to be able to use the quickfixes (issue resolution) in batch mode
    String label = "Remove the unnecessary modifier.";
    String description = "The modifier is unnecessary and could be removed.";
    String image = "fix_indent.gif";
    acceptor.accept(issue, label, description, image, new ITextualMultiModification() {

        @Override
        public void apply(IModificationContext context) throws Exception {
            if (context instanceof IssueModificationContext) {
                Issue theIssue = ((IssueModificationContext) context).getIssue();
                Integer offset = theIssue.getOffset();
                IXtextDocument document = context.getXtextDocument();
                document.replace(offset, theIssue.getLength(), "");
                while (Character.isWhitespace(document.getChar(offset))) {
                    document.replace(offset, 1, "");
                }
            }
        }
    });
}
Also used : IssueModificationContext(org.eclipse.xtext.ui.editor.model.edit.IssueModificationContext) Issue(org.eclipse.xtext.validation.Issue) IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) ITextualMultiModification(org.eclipse.xtext.ui.editor.model.edit.ITextualMultiModification) CoreException(org.eclipse.core.runtime.CoreException) BadLocationException(org.eclipse.jface.text.BadLocationException) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Fix(org.eclipse.xtext.ui.editor.quickfix.Fix)

Example 13 with IXtextDocument

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

the class CreateMemberQuickfixes method newLocalVariableQuickfix.

protected void newLocalVariableQuickfix(final String variableName, boolean isFinal, XAbstractFeatureCall call, Issue issue, IssueResolutionAcceptor issueResolutionAcceptor) {
    LightweightTypeReference variableType = getNewMemberType(call);
    final StringBuilderBasedAppendable localVarDescriptionBuilder = new StringBuilderBasedAppendable();
    localVarDescriptionBuilder.append("...").newLine();
    final String defaultValueLiteral = getDefaultValueLiteral(variableType);
    localVarDescriptionBuilder.append(isFinal ? "val " : "var ").append(variableName).append(" = ").append(defaultValueLiteral);
    localVarDescriptionBuilder.newLine().append("...");
    issueResolutionAcceptor.accept(issue, "Create local " + (isFinal ? "value" : "variable") + " '" + variableName + "'", localVarDescriptionBuilder.toString(), "fix_local_var.png", new SemanticModificationWrapper(issue.getUriToProblem(), new ISemanticModification() {

        @Override
        public void apply(/* @Nullable */
        final EObject element, /* @Nullable */
        final IModificationContext context) throws Exception {
            if (element != null) {
                XtendMember xtendMember = EcoreUtil2.getContainerOfType(element, XtendMember.class);
                if (xtendMember != null) {
                    int offset = getFirstOffsetOfKeyword(xtendMember, "{");
                    IXtextDocument xtextDocument = context.getXtextDocument();
                    if (offset != -1 && xtextDocument != null) {
                        final ReplacingAppendable appendable = appendableFactory.create(xtextDocument, (XtextResource) element.eResource(), offset, 0, new OptionalParameters() {

                            {
                                baseIndentationLevel = 1;
                            }
                        });
                        appendable.increaseIndentation().newLine().append(isFinal ? "val " : "var ").append(variableName).append(" = ").append(defaultValueLiteral);
                        appendable.commitChanges();
                    }
                }
            }
        }
    }));
}
Also used : OptionalParameters(org.eclipse.xtext.xbase.ui.document.DocumentSourceAppender.Factory.OptionalParameters) LightweightTypeReference(org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference) XtendMember(org.eclipse.xtend.core.xtend.XtendMember) SemanticModificationWrapper(org.eclipse.xtext.ui.editor.model.edit.SemanticModificationWrapper) EObject(org.eclipse.emf.ecore.EObject) ISemanticModification(org.eclipse.xtext.ui.editor.model.edit.ISemanticModification) IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) StringBuilderBasedAppendable(org.eclipse.xtext.xbase.compiler.StringBuilderBasedAppendable) ReplacingAppendable(org.eclipse.xtext.xbase.ui.contentassist.ReplacingAppendable) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument)

Example 14 with IXtextDocument

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

the class XtendFoldingRegionProviderTest method calculateFoldingRegions.

private Collection<FoldedPosition> calculateFoldingRegions(String fileName, String content) throws Exception {
    IFile iFile = testHelper.createFile(fileName, content);
    XtextEditor editor = testHelper.openEditor(iFile);
    IXtextDocument document = editor.getDocument();
    return foldingRegionProvider.getFoldingRegions(document);
}
Also used : IFile(org.eclipse.core.resources.IFile) XtextEditor(org.eclipse.xtext.ui.editor.XtextEditor) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument)

Example 15 with IXtextDocument

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

the class HighlightingReconcilerTest method testOpenedEditorHasSemanticHighlighting.

@Test
public void testOpenedEditorHasSemanticHighlighting() {
    try {
        StringConcatenation _builder = new StringConcatenation();
        _builder.append("class Foo {");
        _builder.newLine();
        _builder.append("  ");
        _builder.append("static val foo = \'\'");
        _builder.newLine();
        _builder.append("}");
        _builder.newLine();
        final String model = _builder.toString();
        final XtextEditor editor = this.helper.openEditor("Foo.xtend", model);
        final IXtextDocument document = editor.getDocument();
        final Function0<Boolean> _function = () -> {
            try {
                boolean _xblockexpression = false;
                {
                    final Function1<String, Boolean> _function_1 = (String it) -> {
                        return Boolean.valueOf(it.startsWith(HighlightingPresenter.class.getCanonicalName()));
                    };
                    final String highlighterCategory = IterableExtensions.<String>findFirst(((Iterable<String>) Conversions.doWrapArray(document.getPositionCategories())), _function_1);
                    final Function1<Position, String> _function_2 = (Position it) -> {
                        try {
                            return document.get(it.offset, it.length);
                        } catch (Throwable _e) {
                            throw Exceptions.sneakyThrow(_e);
                        }
                    };
                    final List<String> semanticSnippets = ListExtensions.<Position, String>map(((List<Position>) Conversions.doWrapArray(document.getPositions(highlighterCategory))), _function_2);
                    int _size = semanticSnippets.size();
                    _xblockexpression = (_size > 0);
                }
                return Boolean.valueOf(_xblockexpression);
            } catch (Throwable _e) {
                throw Exceptions.sneakyThrow(_e);
            }
        };
        this.helper.awaitUIUpdate(_function, HighlightingReconcilerTest.VALIDATION_TIMEOUT);
        final Function1<String, Boolean> _function_1 = (String it) -> {
            return Boolean.valueOf(it.startsWith(HighlightingPresenter.class.getCanonicalName()));
        };
        final String highlighterCategory = IterableExtensions.<String>findFirst(((Iterable<String>) Conversions.doWrapArray(document.getPositionCategories())), _function_1);
        final Function1<Position, String> _function_2 = (Position it) -> {
            try {
                return document.get(it.offset, it.length);
            } catch (Throwable _e) {
                throw Exceptions.sneakyThrow(_e);
            }
        };
        final List<String> semanticSnippets = ListExtensions.<Position, String>map(((List<Position>) Conversions.doWrapArray(document.getPositions(highlighterCategory))), _function_2);
        String _join = IterableExtensions.join(semanticSnippets, ",");
        String _plus = ("Highlighting regions broken " + _join);
        Assert.assertEquals(_plus, 2, semanticSnippets.size());
        Assert.assertEquals("Foo", IterableExtensions.<String>head(semanticSnippets));
        Assert.assertEquals("foo", IterableExtensions.<String>last(semanticSnippets));
    } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
    }
}
Also used : Position(org.eclipse.jface.text.Position) XtextEditor(org.eclipse.xtext.ui.editor.XtextEditor) StringConcatenation(org.eclipse.xtend2.lib.StringConcatenation) List(java.util.List) HighlightingPresenter(org.eclipse.xtext.ui.editor.syntaxcoloring.HighlightingPresenter) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Test(org.junit.Test)

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