Search in sources :

Example 36 with TextEdit

use of org.eclipse.text.edits.TextEdit in project xtext-eclipse by eclipse.

the class AbstractTextEditComposerTest method testMultiEdit.

@Test
public void testMultiEdit() throws Exception {
    Resource res = getResource(newTestGrammar());
    composer.beginRecording(res);
    Grammar grammar = (Grammar) res.getContents().get(0);
    ParserRule fooRule = (ParserRule) grammar.getRules().get(0);
    ParserRule barRule = (ParserRule) grammar.getRules().get(1);
    Alternatives fooAlternatives = (Alternatives) fooRule.getAlternatives();
    barRule.setAlternatives(fooAlternatives.getElements().remove(0));
    TextEdit edit = composer.endRecording();
    assertTrue(edit instanceof MultiTextEdit);
    TextEdit[] children = ((MultiTextEdit) edit).getChildren();
    assertEquals(2, children.length);
    assertMatches("'bar' | 'baz'", children[0]);
    assertMatches("Bar: 'foo' ;", children[1]);
}
Also used : ParserRule(org.eclipse.xtext.ParserRule) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) Resource(org.eclipse.emf.ecore.resource.Resource) Grammar(org.eclipse.xtext.Grammar) Alternatives(org.eclipse.xtext.Alternatives) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) Test(org.junit.Test)

Example 37 with TextEdit

use of org.eclipse.text.edits.TextEdit in project xtext-eclipse by eclipse.

the class ChangeConverter method _handleReplacements.

protected void _handleReplacements(final ITextDocumentChange change) {
    int _size = change.getReplacements().size();
    boolean _greaterThan = (_size > 0);
    if (_greaterThan) {
        final IFile file = this.resourceUriConverter.toFile(change.getOldURI());
        boolean _canWrite = this.canWrite(file);
        boolean _not = (!_canWrite);
        if (_not) {
            StringConcatenation _builder = new StringConcatenation();
            _builder.append("Affected file \'");
            IPath _fullPath = file.getFullPath();
            _builder.append(_fullPath);
            _builder.append("\' is read-only");
            this.issues.add(RefactoringIssueAcceptor.Severity.FATAL, _builder.toString());
        }
        this.checkDerived(file);
        final Function1<ITextReplacement, ReplaceEdit> _function = (ITextReplacement replacement) -> {
            int _offset = replacement.getOffset();
            int _length = replacement.getLength();
            String _replacementText = replacement.getReplacementText();
            return new ReplaceEdit(_offset, _length, _replacementText);
        };
        final List<ReplaceEdit> textEdits = ListExtensions.<ITextReplacement, ReplaceEdit>map(change.getReplacements(), _function);
        final MultiTextEdit textEdit = new MultiTextEdit();
        textEdit.addChildren(((TextEdit[]) Conversions.unwrapArray(textEdits, TextEdit.class)));
        final ITextEditor openEditor = this.findOpenEditor(file);
        TextChange _xifexpression = null;
        if ((openEditor == null)) {
            String _lastSegment = change.getOldURI().lastSegment();
            TextFileChange _textFileChange = new TextFileChange(_lastSegment, file);
            final Procedure1<TextFileChange> _function_1 = (TextFileChange it) -> {
                it.setSaveMode(TextFileChange.FORCE_SAVE);
            };
            _xifexpression = ObjectExtensions.<TextFileChange>operator_doubleArrow(_textFileChange, _function_1);
        } else {
            String _name = this.currentChange.getName();
            _xifexpression = new EditorDocumentChange(_name, openEditor, false);
        }
        final TextChange ltkChange = _xifexpression;
        ltkChange.setEdit(textEdit);
        ltkChange.setTextType(change.getOldURI().fileExtension());
        this.addChange(ltkChange);
    }
}
Also used : IFile(org.eclipse.core.resources.IFile) ITextEditor(org.eclipse.ui.texteditor.ITextEditor) IPath(org.eclipse.core.runtime.IPath) ITextReplacement(org.eclipse.xtext.formatting2.regionaccess.ITextReplacement) TextChange(org.eclipse.ltk.core.refactoring.TextChange) TextFileChange(org.eclipse.ltk.core.refactoring.TextFileChange) EditorDocumentChange(org.eclipse.xtext.ui.refactoring.impl.EditorDocumentChange) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) StringConcatenation(org.eclipse.xtend2.lib.StringConcatenation) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit)

Example 38 with TextEdit

use of org.eclipse.text.edits.TextEdit in project xtext-eclipse by eclipse.

the class MultiImportOrganizer method organizeImports.

/**
 * @param files
 *            ordered by corresponding {@link IProject}
 * @param mon
 * @return Creates {@link Change}s for each {@link IFile} using {@link ImportOrganizer}
 * @throws InterruptedException
 */
public List<Change> organizeImports(Multimap<IProject, IFile> files, IProgressMonitor mon) throws InterruptedException {
    List<Change> result = Lists.newArrayList();
    for (IProject project : files.keySet()) {
        ResourceSet resSet = resSetProvider.get(project);
        for (IFile file : files.get(project)) {
            mon.subTask("Calculating imports in - " + file.getName());
            URI uri = storageMapper.getUri(file);
            if (uri != null) {
                XtextResource resource = (XtextResource) resSet.getResource(uri, true);
                List<ReplaceRegion> replace = importOrganizer.getOrganizedImportChanges(resource);
                // TODO - find out why \n\n changes are produced, even if there are any unused imports
                if (replace == null) {
                    continue;
                }
                TextEdit textEdit = replaceConverter.convertToTextEdit(replace);
                IRefactoringDocument iRefactoringDocument = provider.get(uri, status);
                Change change = iRefactoringDocument.createChange(Messages.OrganizeImports, textEdit);
                if (change instanceof EditorDocumentChange) {
                    if (((EditorDocument) iRefactoringDocument).getEditor().isDirty()) {
                        ((EditorDocumentChange) change).setDoSave(false);
                    }
                }
                result.add(change);
            }
            mon.worked(1);
            if (mon.isCanceled()) {
                throw new InterruptedException();
            }
        }
    }
    return result;
}
Also used : IFile(org.eclipse.core.resources.IFile) IRefactoringDocument(org.eclipse.xtext.ui.refactoring.impl.IRefactoringDocument) XtextResource(org.eclipse.xtext.resource.XtextResource) Change(org.eclipse.ltk.core.refactoring.Change) EditorDocumentChange(org.eclipse.xtext.ui.refactoring.impl.EditorDocumentChange) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) URI(org.eclipse.emf.common.util.URI) IProject(org.eclipse.core.resources.IProject) EditorDocumentChange(org.eclipse.xtext.ui.refactoring.impl.EditorDocumentChange) ReplaceRegion(org.eclipse.xtext.util.ReplaceRegion) TextEdit(org.eclipse.text.edits.TextEdit)

Example 39 with TextEdit

use of org.eclipse.text.edits.TextEdit in project xtext-eclipse by eclipse.

the class JavaTypeQuickfixes method createConstructorProposals.

@SuppressWarnings("restriction")
protected boolean createConstructorProposals(final JvmDeclaredType contextType, final Issue issue, String typeName, IJavaSearchScope searchScope, final IssueResolutionAcceptor acceptor) throws JavaModelException {
    final boolean[] result = new boolean[] { false };
    if (contextType != null) {
        final IVisibilityHelper visibilityHelper = getVisibilityHelper(contextType);
        final Pair<String, String> packageAndType = typeNameGuesser.guessPackageAndTypeName(contextType, typeName);
        final String wantedPackageName = packageAndType.getFirst();
        final String wantedTypeName = packageAndType.getSecond();
        if (typeName.endsWith(wantedTypeName)) {
            return false;
        }
        org.eclipse.jdt.internal.core.search.BasicSearchEngine searchEngine = new org.eclipse.jdt.internal.core.search.BasicSearchEngine();
        final char[] wantedPackageChars = (isEmpty(wantedPackageName)) ? null : wantedPackageName.toCharArray();
        searchEngine.searchAllTypeNames(wantedPackageChars, SearchPattern.R_EXACT_MATCH, wantedTypeName.toCharArray(), SearchPattern.R_EXACT_MATCH, IJavaSearchConstants.TYPE, searchScope, new org.eclipse.jdt.internal.core.search.IRestrictedAccessTypeRequestor() {

            @Override
            public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, org.eclipse.jdt.internal.compiler.env.AccessRestriction access) {
                final String qualifiedTypeName = getQualifiedTypeName(packageName, enclosingTypeNames, simpleTypeName);
                if (access == null || (access.getProblemId() != IProblem.ForbiddenReference && !access.ignoreIfBetter())) {
                    JvmType importType = services.getTypeReferences().findDeclaredType(qualifiedTypeName, contextType);
                    if (importType instanceof JvmDeclaredType && visibilityHelper.isVisible((JvmDeclaredType) importType)) {
                        result[0] = true;
                        StringBuilder label = new StringBuilder("Change to constructor call 'new ");
                        label.append(simpleTypeName);
                        label.append("()'");
                        if (!equal(wantedPackageName, new String(packageName))) {
                            label.append(" (");
                            label.append(packageName);
                            if (enclosingTypeNames.length > 0) {
                                for (char[] enclosingTypeName : enclosingTypeNames) {
                                    label.append(".");
                                    label.append(enclosingTypeName);
                                }
                            }
                            label.append(")");
                        }
                        acceptor.accept(issue, label.toString(), label.toString(), "impc_obj.gif", new ISemanticModification() {

                            @Override
                            public void apply(EObject element, IModificationContext context) throws Exception {
                                IXtextDocument document = context.getXtextDocument();
                                DocumentRewriter rewriter = rewriterFactory.create(document, (XtextResource) element.eResource());
                                final int typeEndOffset = document.get().indexOf(wantedTypeName, issue.getOffset() + wantedPackageName.length()) + wantedTypeName.length();
                                final Section section = rewriter.newSection(issue.getOffset(), typeEndOffset - issue.getOffset());
                                section.append(services.getTypeReferences().findDeclaredType(qualifiedTypeName, element));
                                section.append("()");
                                final TextEdit textEdit = replaceConverter.convertToTextEdit(rewriter.getChanges());
                                textEdit.apply(document);
                            }
                        }, jdtTypeRelevance.getRelevance(qualifiedTypeName, wantedTypeName) + 100);
                    }
                }
            }
        }, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, new NullProgressMonitor());
    }
    return result[0];
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) JvmDeclaredType(org.eclipse.xtext.common.types.JvmDeclaredType) JvmType(org.eclipse.xtext.common.types.JvmType) EObject(org.eclipse.emf.ecore.EObject) ISemanticModification(org.eclipse.xtext.ui.editor.model.edit.ISemanticModification) IVisibilityHelper(org.eclipse.xtext.xbase.typesystem.util.IVisibilityHelper) XImportSection(org.eclipse.xtext.xtype.XImportSection) Section(org.eclipse.xtext.xbase.ui.document.DocumentRewriter.Section) TextEdit(org.eclipse.text.edits.TextEdit) DocumentRewriter(org.eclipse.xtext.xbase.ui.document.DocumentRewriter) IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument)

Example 40 with TextEdit

use of org.eclipse.text.edits.TextEdit in project eclipse.platform.text by eclipse.

the class DocumentUndoManagerTest method testCompoundTextEdit.

public void testCompoundTextEdit() throws ExecutionException, BadLocationException {
    final int RANDOM_STRING_LENGTH = 50;
    final int RANDOM_REPLACE_COUNT = 100;
    assertTrue(RANDOM_REPLACE_COUNT >= 1);
    assertTrue(RANDOM_REPLACE_COUNT <= MAX_UNDO_LEVEL);
    String original = createRandomString(RANDOM_STRING_LENGTH);
    final IDocument document = new Document(original);
    createUndoManager(document);
    // fUndoManager.beginCompoundChange();
    MultiTextEdit fRoot = new MultiTextEdit();
    TextEdit e1 = new DeleteEdit(3, 1);
    fRoot.addChild(e1);
    fRoot.apply(document);
    fRoot = new MultiTextEdit();
    TextEdit e2 = new DeleteEdit(3, 1);
    fRoot.addChild(e2);
    fRoot.apply(document);
    // fUndoManager.endCompoundChange();
    assertTrue(fUndoManager.undoable());
    // while (fUndoManager.undoable())
    fUndoManager.undo();
    assertTrue(!fUndoManager.undoable());
    final String reverted = document.get();
    assertEquals(original, reverted);
}
Also used : MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) DeleteEdit(org.eclipse.text.edits.DeleteEdit) IDocument(org.eclipse.jface.text.IDocument) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit)

Aggregations

TextEdit (org.eclipse.text.edits.TextEdit)190 MultiTextEdit (org.eclipse.text.edits.MultiTextEdit)113 Test (org.junit.Test)49 IDocument (org.eclipse.jface.text.IDocument)48 ReplaceEdit (org.eclipse.text.edits.ReplaceEdit)48 BadLocationException (org.eclipse.jface.text.BadLocationException)34 Document (org.eclipse.jface.text.Document)33 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)32 UndoEdit (org.eclipse.text.edits.UndoEdit)26 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)23 InsertEdit (org.eclipse.text.edits.InsertEdit)22 CoreException (org.eclipse.core.runtime.CoreException)20 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)19 MalformedTreeException (org.eclipse.text.edits.MalformedTreeException)19 DeleteEdit (org.eclipse.text.edits.DeleteEdit)17 MoveSourceEdit (org.eclipse.text.edits.MoveSourceEdit)16 ArrayList (java.util.ArrayList)15 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)15 MoveTargetEdit (org.eclipse.text.edits.MoveTargetEdit)15 TextEditGroup (org.eclipse.text.edits.TextEditGroup)15