Search in sources :

Example 56 with InsertEdit

use of org.eclipse.text.edits.InsertEdit in project AutoRefactor by JnRouvignac.

the class ASTCommentRewriter method replaceLineCommentBeforeJavaElement.

private void replaceLineCommentBeforeJavaElement(final List<TextEdit> commentEdits, final LineComment lineComment, final List<LineComment> lineComments, final int i, final String source, final TreeSet<Integer> lineStarts) {
    // $NON-NLS-1$
    int replaceLength = "//".length();
    boolean isFirst = i == 0;
    String replacementText;
    SourceLocation indentLoc = getIndentForJavadoc(lineComment, source, lineStarts);
    if (isFirst) {
        // TODO JNR how to obey configured indentation?
        // $NON-NLS-1$ //$NON-NLS-2$
        replacementText = "/**" + lineSeparator + indentLoc.substring(source) + " *";
    } else {
        // $NON-NLS-1$
        replacementText = " *";
    }
    boolean commentStartsWithSlash = source.charAt(lineComment.getStartPosition() + replaceLength) == '/';
    if (commentStartsWithSlash) {
        // $NON-NLS-1$
        replacementText += " ";
    }
    commentEdits.add(new ReplaceEdit(lineComment.getStartPosition(), replaceLength, replacementText));
    replaceEndsOfBlockCommentFromCommentText(commentEdits, lineComment, source);
    boolean isLast = i == lineComments.size() - 1;
    if (isLast) {
        // TODO JNR how to obey configured indentation?
        int position = SourceLocation.getEndPosition(lineComment);
        // $NON-NLS-1$
        commentEdits.add(new InsertEdit(position, lineSeparator + indentLoc.substring(source) + " */"));
    }
}
Also used : InsertEdit(org.eclipse.text.edits.InsertEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit)

Example 57 with InsertEdit

use of org.eclipse.text.edits.InsertEdit in project titan.EclipsePlug-ins by eclipse.

the class AddImport method run.

@Override
public void run(final IAction action) {
    TITANDebugConsole.println("Add import called: ");
    if (targetEditor == null || !(targetEditor instanceof TTCN3Editor)) {
        return;
    }
    targetEditor.getEditorSite().getActionBars().getStatusLineManager().setErrorMessage(null);
    IFile file = (IFile) targetEditor.getEditorInput().getAdapter(IFile.class);
    if (file == null) {
        targetEditor.getEditorSite().getActionBars().getStatusLineManager().setErrorMessage(FILENOTIDENTIFIABLE);
        return;
    }
    if (!TITANNature.hasTITANNature(file.getProject())) {
        targetEditor.getEditorSite().getActionBars().getStatusLineManager().setErrorMessage(TITANNature.NO_TITAN_FILE_NATURE_FOUND);
        return;
    }
    IPreferencesService prefs = Platform.getPreferencesService();
    boolean reportDebugInformation = prefs.getBoolean(ProductConstants.PRODUCT_ID_DESIGNER, PreferenceConstants.DISPLAYDEBUGINFORMATION, true, null);
    int offset;
    if (!selection.isEmpty() && selection instanceof TextSelection && !"".equals(((TextSelection) selection).getText())) {
        if (reportDebugInformation) {
            TITANDebugConsole.println("text selected: " + ((TextSelection) selection).getText());
        }
        TextSelection tSelection = (TextSelection) selection;
        offset = tSelection.getOffset() + tSelection.getLength();
    } else {
        offset = ((TTCN3Editor) targetEditor).getCarretOffset();
    }
    DeclarationCollector declarationCollector = OpenDeclarationHelper.findVisibleDeclarations(targetEditor, new TTCN3ReferenceParser(false), ((TTCN3Editor) targetEditor).getDocument(), offset, false);
    if (declarationCollector == null) {
        return;
    }
    List<DeclarationCollectionHelper> collected = declarationCollector.getCollected();
    if (collected.isEmpty()) {
        // FIXME add semantic check guard on project level.
        ProjectSourceParser projectSourceParser = GlobalParser.getProjectSourceParser(file.getProject());
        if (reportDebugInformation) {
            TITANDebugConsole.println("No visible elements found");
        }
        for (String moduleName2 : projectSourceParser.getKnownModuleNames()) {
            Module module2 = projectSourceParser.getModuleByName(moduleName2);
            if (module2 != null) {
                // Visit each file in the project one by
                // one instead of
                // "module2.getAssignments().addDeclaration(declarationCollector)".
                Assignments assignments = module2.getAssignments();
                for (int i = 0; i < assignments.getNofAssignments(); i++) {
                    assignments.getAssignmentByIndex(i).addDeclaration(declarationCollector, 0);
                }
            }
        }
        if (declarationCollector.getCollectionSize() == 0) {
            targetEditor.getEditorSite().getActionBars().getStatusLineManager().setErrorMessage(NOTTTCN3DECLARATION);
            return;
        }
        if (reportDebugInformation) {
            TITANDebugConsole.println("Elements were only found in not visible modules");
        }
        DeclarationCollectionHelper resultToInsert = null;
        if (collected.size() == 1) {
            resultToInsert = collected.get(0);
        } else {
            OpenDeclarationLabelProvider labelProvider = new OpenDeclarationLabelProvider();
            ElementListSelectionDialog dialog = new ElementListSelectionDialog(null, labelProvider);
            dialog.setTitle("Add Import");
            dialog.setMessage("Choose element to generate an import statement for.");
            dialog.setElements(collected.toArray());
            if (dialog.open() == Window.OK) {
                if (reportDebugInformation) {
                    TITANDebugConsole.getConsole().newMessageStream().println("Selected: " + dialog.getFirstResult());
                }
                resultToInsert = (DeclarationCollectionHelper) dialog.getFirstResult();
            }
        }
        if (resultToInsert == null) {
            return;
        }
        IFile newfile = (IFile) resultToInsert.location.getFile();
        Module newModule = projectSourceParser.containedModule(newfile);
        if (newModule == null) {
            targetEditor.getEditorSite().getActionBars().getStatusLineManager().setErrorMessage("Could not identify the module in file " + newfile.getName());
            return;
        }
        String ttcnName = newModule.getIdentifier().getTtcnName();
        TITANDebugConsole.println("the new module to insert: " + ttcnName);
        final IFile actualFile = (IFile) targetEditor.getEditorInput().getAdapter(IFile.class);
        Module actualModule = projectSourceParser.containedModule(actualFile);
        int insertionOffset = ((TTCN3Module) actualModule).getAssignmentsScope().getLocation().getOffset() + 1;
        MultiTextEdit multiEdit = new MultiTextEdit(insertionOffset, 0);
        RewriteSessionEditProcessor processor = new RewriteSessionEditProcessor(((TTCN3Editor) targetEditor).getDocument(), multiEdit, TextEdit.UPDATE_REGIONS | TextEdit.CREATE_UNDO);
        multiEdit.addChild(new InsertEdit(insertionOffset, "\nimport from " + ttcnName + " all;\n"));
        try {
            processor.performEdits();
        } catch (BadLocationException e) {
            ErrorReporter.logExceptionStackTrace(e);
        }
    } else {
        if (reportDebugInformation) {
            for (DeclarationCollectionHelper foundDeclaration : collected) {
                TITANDebugConsole.println("declaration:" + foundDeclaration.location.getFile() + ": " + foundDeclaration.location.getOffset() + " - " + foundDeclaration.location.getEndOffset() + " is available");
            }
        }
    }
    Display.getDefault().asyncExec(new Runnable() {

        @Override
        public void run() {
            MessageDialog.openWarning(null, "Study feature", "Adding a missing importation is still under study");
        }
    });
}
Also used : TTCN3Editor(org.eclipse.titan.designer.editors.ttcn3editor.TTCN3Editor) InsertEdit(org.eclipse.text.edits.InsertEdit) IFile(org.eclipse.core.resources.IFile) DeclarationCollector(org.eclipse.titan.designer.editors.actions.DeclarationCollector) TTCN3ReferenceParser(org.eclipse.titan.designer.editors.ttcn3editor.TTCN3ReferenceParser) TextSelection(org.eclipse.jface.text.TextSelection) Assignments(org.eclipse.titan.designer.AST.Assignments) OpenDeclarationLabelProvider(org.eclipse.titan.designer.editors.actions.OpenDeclarationLabelProvider) IPreferencesService(org.eclipse.core.runtime.preferences.IPreferencesService) ProjectSourceParser(org.eclipse.titan.designer.parsers.ProjectSourceParser) DeclarationCollectionHelper(org.eclipse.titan.designer.editors.actions.DeclarationCollectionHelper) RewriteSessionEditProcessor(org.eclipse.jface.text.RewriteSessionEditProcessor) ElementListSelectionDialog(org.eclipse.ui.dialogs.ElementListSelectionDialog) Module(org.eclipse.titan.designer.AST.Module) TTCN3Module(org.eclipse.titan.designer.AST.TTCN3.definitions.TTCN3Module) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 58 with InsertEdit

use of org.eclipse.text.edits.InsertEdit in project titan.EclipsePlug-ins by eclipse.

the class ImportSelectionDialog method organizeImportsEdit.

/**
 * Organize the imports according to the global preferences. If set,
 * <ul>
 * <li>Add imports necessary for missing references,</li>
 * <li>Remove unused imports,</li>
 * <li>Sort the import statements.</li>
 * </ul>
 * <p>
 * These changes are not applied in the function, just collected in a
 * <link>MultiTextEdit</link>, which is then returned.
 * </p>
 * TODO: notice and handle ambiguous references
 *
 * @param module
 *            The module which import statements are to organize.
 * @param document
 *            The document that contains the module.
 *
 * @return The edit, which contains the proper changes.
 */
private static MultiTextEdit organizeImportsEdit(final TTCN3Module module, final IDocument document) throws BadLocationException {
    final IProject prj = module.getProject();
    final String doc = document.get();
    final MultiTextEdit insertEdit = new MultiTextEdit();
    final MultiTextEdit removeEdit = new MultiTextEdit();
    final List<ImportText> newImports = new ArrayList<ImportText>();
    final List<ImportText> importsKept = new ArrayList<ImportText>();
    boolean needSorting = false;
    if (addImports) {
        // register the new needed imports
        final Set<String> importNamesAdded = new HashSet<String>();
        for (final Reference ref : module.getMissingReferences()) {
            final Location missLoc = findReferenceInProject(ref, prj);
            if (missLoc != null) {
                final IFile file = (IFile) missLoc.getFile();
                final ProjectSourceParser parser = GlobalParser.getProjectSourceParser(file.getProject());
                final Module addMod = parser.containedModule(file);
                final String importName = addMod.getIdentifier().getTtcnName();
                if (!importNamesAdded.contains(importName)) {
                    final StringBuilder impText = new StringBuilder("import from ").append(importName).append(" all;");
                    // if (importChangeMethod.equals(OrganizeImportPreferencePage.COMMENT_THEM)) {
                    impText.append(" // Added automatically to resolve ").append(ref.getDisplayName());
                    // }
                    newImports.add(new ImportText(importName, impText.toString() + NEWLINE));
                    importNamesAdded.add(importName);
                    if (reportDebug) {
                        final StringBuilder sb = new StringBuilder("For ").append(ref.getDisplayName()).append(": ");
                        sb.append(impText.toString());
                        TITANDebugConsole.println(sb.toString());
                    }
                }
            }
        }
        if (sortImports && !newImports.isEmpty()) {
            needSorting = true;
        }
    }
    if (!needSorting && sortImports) {
        // are the imports already sorted ?
        final List<ImportModule> oldImports = module.getImports();
        for (int size = oldImports.size(), i = 0; i < size - 1 && !needSorting; i++) {
            if (oldImports.get(i).getName().compareTo(oldImports.get(i + 1).getName()) > 0) {
                needSorting = true;
            }
            if (oldImports.get(i).getLocation().getOffset() > oldImports.get(i + 1).getLocation().getOffset()) {
                needSorting = true;
            }
        }
        if (!needSorting && oldImports.size() > 1) {
            // are the import strictly before the definitions ?
            final int lastImportOffset = oldImports.get(oldImports.size() - 1).getLocation().getOffset();
            final Definitions defs = module.getAssignmentsScope();
            if (defs.getNofAssignments() > 0 && !oldImports.isEmpty()) {
                for (int i = 0, size = defs.getNofAssignments(); i < size; ++i) {
                    final int temp = defs.getAssignmentByIndex(i).getLocation().getOffset();
                    if (temp < lastImportOffset) {
                        needSorting = true;
                    }
                }
            }
        }
    }
    if (needSorting || removeImports) {
        // remove the imports not needed, or every if sorting is required
        for (final ImportModule m : module.getImports()) {
            final Location delImp = m.getLocation();
            final IRegion startLineRegion = document.getLineInformationOfOffset(delImp.getOffset());
            final IRegion endLineRegion = document.getLineInformationOfOffset(delImp.getEndOffset());
            final String delimeter = document.getLineDelimiter(document.getLineOfOffset(delImp.getEndOffset()));
            final int delLength = delimeter == null ? 0 : delimeter.length();
            if (needSorting || (removeImports && !m.getUsedForImportation())) {
                if (reportDebug) {
                    final MessageConsoleStream stream = TITANDebugConsole.getConsole().newMessageStream();
                    TITANDebugConsole.println("Removing " + "'" + doc.substring(startLineRegion.getOffset(), endLineRegion.getOffset() + endLineRegion.getLength() + delLength) + "'", stream);
                    TITANDebugConsole.println("From " + startLineRegion.getOffset() + " till " + ((endLineRegion.getOffset() - startLineRegion.getOffset()) + endLineRegion.getLength() + delLength), stream);
                }
                /*if (importChangeMethod.equals(OrganizeImportPreferencePage.COMMENT_THEM)) {
						removeEdit.addChild(new InsertEdit(m.getLocation().getOffset(), "/*"));
						// hack to handle the semicolon
						removeEdit.addChild(new InsertEdit(m.getLocation().getEndOffset() + 1, "")); 
					} else {*/
                removeEdit.addChild(new DeleteEdit(startLineRegion.getOffset(), (endLineRegion.getOffset() - startLineRegion.getOffset()) + endLineRegion.getLength() + delLength));
            // }
            }
            if (needSorting && (!removeImports || m.getUsedForImportation())) {
                importsKept.add(new ImportText(m.getName(), doc.substring(startLineRegion.getOffset(), endLineRegion.getOffset() + endLineRegion.getLength() + delLength)));
            }
        }
    }
    if (!newImports.isEmpty() || (sortImports && needSorting)) {
        // always insert at the beginning of the file
        final int line = document.getLineOfOffset(module.getAssignmentsScope().getLocation().getOffset());
        final IRegion lineRegion = document.getLineInformation(line);
        final String delimeter = document.getLineDelimiter(line);
        final int delimeterLength = delimeter == null ? 0 : delimeter.length();
        final int startPos = lineRegion.getOffset() + lineRegion.getLength() + delimeterLength;
        if (sortImports) {
            if (needSorting || !newImports.isEmpty()) {
                final List<ImportText> results = new ArrayList<ImportText>();
                results.addAll(importsKept);
                results.addAll(newImports);
                Collections.sort(results);
                for (final ImportText i : results) {
                    insertEdit.addChild(new InsertEdit(startPos, i.getText()));
                }
            }
        } else {
            Collections.sort(newImports);
            for (final ImportText i : newImports) {
                insertEdit.addChild(new InsertEdit(startPos, i.getText()));
            }
        }
    }
    final MultiTextEdit resultEdit = new MultiTextEdit();
    if (insertEdit.hasChildren()) {
        resultEdit.addChild(insertEdit);
    }
    if (removeEdit.hasChildren()) {
        resultEdit.addChild(removeEdit);
    }
    return resultEdit;
}
Also used : InsertEdit(org.eclipse.text.edits.InsertEdit) IFile(org.eclipse.core.resources.IFile) Reference(org.eclipse.titan.designer.AST.Reference) Definitions(org.eclipse.titan.designer.AST.TTCN3.definitions.Definitions) ArrayList(java.util.ArrayList) MessageConsoleStream(org.eclipse.ui.console.MessageConsoleStream) DeleteEdit(org.eclipse.text.edits.DeleteEdit) IProject(org.eclipse.core.resources.IProject) ProjectSourceParser(org.eclipse.titan.designer.parsers.ProjectSourceParser) ImportModule(org.eclipse.titan.designer.AST.TTCN3.definitions.ImportModule) IRegion(org.eclipse.jface.text.IRegion) Module(org.eclipse.titan.designer.AST.Module) ImportModule(org.eclipse.titan.designer.AST.TTCN3.definitions.ImportModule) TTCN3Module(org.eclipse.titan.designer.AST.TTCN3.definitions.TTCN3Module) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) HashSet(java.util.HashSet) Location(org.eclipse.titan.designer.AST.Location)

Example 59 with InsertEdit

use of org.eclipse.text.edits.InsertEdit in project titan.EclipsePlug-ins by eclipse.

the class ExtractModuleParRefactoring method createChange.

private WorkspaceJob createChange() {
    final WorkspaceJob job = new WorkspaceJob("ExtractModulePar: writing to target project") {

        @Override
        public IStatus runInWorkspace(final IProgressMonitor monitor) throws CoreException {
            if (copyMap == null) {
                ErrorReporter.logError("ExtractModuleParRefactoring::createChange(): Reading dependencies did not finish.");
                return Status.CANCEL_STATUS;
            }
            if (filesToCopy == null) {
                ErrorReporter.logError("ExtractModuleParRefactoring::createChange(): Reading dependencies did not finish (2).");
                return Status.CANCEL_STATUS;
            }
            // create files & write dependencies in them
            for (Entry<IPath, StringBuilder> e : copyMap.entrySet()) {
                IFile targetFile = createFile(e.getKey());
                if (targetFile == null) {
                    ErrorReporter.logError("Unable to create file `" + e.getKey() + "' while extracting module parameters.");
                    return Status.CANCEL_STATUS;
                }
                TextFileChange change = new TextFileChange("extract_append", targetFile);
                MultiTextEdit rootEdit = new MultiTextEdit();
                change.setEdit(rootEdit);
                TextEdit edit = new InsertEdit(0, e.getValue().toString());
                rootEdit.addChild(edit);
                change.perform(new NullProgressMonitor());
            }
            // copy files from 'filesToCopy' without opening them
            for (IFile f : filesToCopy) {
                if (copyFile(f) == null) {
                    ErrorReporter.logError("Unable to copy file `" + (f == null ? "null" : f.getProjectRelativePath()) + "' while extracting module aprameters.");
                    return Status.CANCEL_STATUS;
                }
            }
            return Status.OK_STATUS;
        }
    };
    job.setUser(true);
    job.schedule();
    return job;
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) InsertEdit(org.eclipse.text.edits.InsertEdit) IFile(org.eclipse.core.resources.IFile) IPath(org.eclipse.core.runtime.IPath) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) WorkspaceJob(org.eclipse.core.resources.WorkspaceJob) TextFileChange(org.eclipse.ltk.core.refactoring.TextFileChange) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit)

Example 60 with InsertEdit

use of org.eclipse.text.edits.InsertEdit in project titan.EclipsePlug-ins by eclipse.

the class ChangeCreator method createTextEdit.

private TextEdit createTextEdit(final Log_Statement toEdit, final Context toAdd) {
    // get insert location
    final LogInsertLocationFinder vis = new LogInsertLocationFinder();
    toEdit.accept(vis);
    int insertOffset = vis.calculateEndOffset();
    if (insertOffset < 0) {
        ErrorReporter.logError("ChangeCreator.createTextEdit(): Warning! No arguments in log statement! ");
        insertOffset = toEdit.getLocation().getEndOffset() - 1;
    }
    // find variable names that are already present in the log statement
    final Set<String> varsAlreadyPresent;
    final Context bottomContext = toAdd.getBottom();
    if (bottomContext.getNode() instanceof Log_Statement) {
        final LoggedVariableFinder vis2 = new LoggedVariableFinder();
        final Log_Statement logst = (Log_Statement) bottomContext.getNode();
        logst.accept(vis2);
        varsAlreadyPresent = vis2.getVarsAlreadyPresent();
    } else {
        varsAlreadyPresent = new HashSet<String>();
    }
    // create inserted text
    toAdd.process();
    final List<String> contextInfos = toAdd.createLogParts(varsAlreadyPresent);
    final int len = Math.min(contextInfos.size(), toAdd.getVarCountLimitOption());
    if (len == 0) {
        return null;
    }
    final StringBuilder sb = new StringBuilder();
    for (int i = 0; i < len; i++) {
        sb.append(contextInfos.get(i));
    }
    // create edit from location and text
    return new InsertEdit(insertOffset, sb.toString());
}
Also used : Context(org.eclipse.titanium.refactoring.logging.context.Context) InsertEdit(org.eclipse.text.edits.InsertEdit) Log_Statement(org.eclipse.titan.designer.AST.TTCN3.statements.Log_Statement)

Aggregations

InsertEdit (org.eclipse.text.edits.InsertEdit)65 MultiTextEdit (org.eclipse.text.edits.MultiTextEdit)33 ReplaceEdit (org.eclipse.text.edits.ReplaceEdit)24 TextEdit (org.eclipse.text.edits.TextEdit)22 DeleteEdit (org.eclipse.text.edits.DeleteEdit)20 Test (org.junit.Test)18 UndoEdit (org.eclipse.text.edits.UndoEdit)13 BadLocationException (org.eclipse.jface.text.BadLocationException)12 ArrayList (java.util.ArrayList)9 TextFileChange (org.eclipse.ltk.core.refactoring.TextFileChange)8 MalformedTreeException (org.eclipse.text.edits.MalformedTreeException)8 Location (org.eclipse.titan.designer.AST.Location)8 Module (org.eclipse.titan.designer.AST.Module)7 ProjectSourceParser (org.eclipse.titan.designer.parsers.ProjectSourceParser)7 WorkspaceJob (org.eclipse.core.resources.WorkspaceJob)5 CoreException (org.eclipse.core.runtime.CoreException)5 IFile (org.eclipse.core.resources.IFile)4 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)4 IDocument (org.eclipse.jface.text.IDocument)4 IRegion (org.eclipse.jface.text.IRegion)4