use of org.eclipse.text.edits.DeleteEdit 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;
}
use of org.eclipse.text.edits.DeleteEdit in project titan.EclipsePlug-ins by eclipse.
the class ChangeCreator method createFileChange.
private Change createFileChange(final IFile toVisit) {
if (toVisit == null) {
return null;
}
final ProjectSourceParser sourceParser = GlobalParser.getProjectSourceParser(toVisit.getProject());
final Module module = sourceParser.containedModule(toVisit);
if (module == null) {
return null;
}
// find all locations in the module that should be edited
final DefinitionVisitor vis = new DefinitionVisitor();
module.accept(vis);
final NavigableSet<Definition> nodes = vis.getLocations();
if (nodes.isEmpty()) {
return null;
}
// calculate edit locations
final List<Definition> locations = new ArrayList<Definition>();
try {
final WorkspaceJob job1 = calculateEditLocations(nodes, toVisit, locations);
job1.join();
} catch (InterruptedException ie) {
ErrorReporter.logExceptionStackTrace(ie);
} catch (CoreException ce) {
ErrorReporter.logError("UngroupModuleparRefactoring/CreateChange.createFileChange(): " + "CoreException while calculating edit locations. ");
ErrorReporter.logExceptionStackTrace(ce);
}
if (locations.isEmpty()) {
return null;
}
// create a change for each edit location
final TextFileChange tfc = new TextFileChange(toVisit.getName(), toVisit);
final MultiTextEdit rootEdit = new MultiTextEdit();
tfc.setEdit(rootEdit);
int precedeOffset = -1;
final String fileContents = loadFileContent(toVisit);
for (Definition node : locations) {
final Location l = node.getCumulativeDefinitionLocation();
final Location typeLocation = node.getType(CompilationTimeStamp.getBaseTimestamp()).getLocation();
final Location identifierLocation = node.getIdentifier().getLocation();
if (precedeOffset != l.getOffset()) {
precedeOffset = l.getOffset();
final int len = l.getEndOffset() - l.getOffset();
rootEdit.addChild(new DeleteEdit(l.getOffset(), len + 1));
}
String typeText = fileContents.substring(typeLocation.getOffset(), typeLocation.getEndOffset()).trim();
String name = fileContents.substring(identifierLocation.getOffset(), identifierLocation.getEndOffset()).trim();
String newModulePar = "";
if (node instanceof Def_ModulePar) {
Def_ModulePar modulePar = (Def_ModulePar) node;
if (modulePar.getDefaultValue() != null) {
final Location valueLocation = modulePar.getDefaultValue().getLocation();
String valueText = fileContents.substring(valueLocation.getOffset(), valueLocation.getEndOffset()).trim();
newModulePar = "modulepar " + typeText + " " + name + " := " + valueText + ";\n";
} else {
newModulePar = "modulepar " + typeText + " " + name + ";\n";
}
} else if (node instanceof Def_ModulePar_Template) {
Def_ModulePar_Template modulePar = (Def_ModulePar_Template) node;
if (modulePar.getDefaultTemplate() != null) {
final Location valueLocation = modulePar.getDefaultTemplate().getLocation();
String temlateText = fileContents.substring(valueLocation.getOffset(), valueLocation.getEndOffset()).trim();
newModulePar = "modulepar template " + typeText + " " + name + " := " + temlateText + ";\n";
} else {
newModulePar = "modulepar template " + typeText + " " + name + ";\n";
}
}
rootEdit.addChild(new InsertEdit(l.getOffset(), newModulePar));
}
return tfc;
}
use of org.eclipse.text.edits.DeleteEdit 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();
resultEdit.addChild(insertEdit);
resultEdit.addChild(removeEdit);
return resultEdit;
}
use of org.eclipse.text.edits.DeleteEdit in project flux by eclipse.
the class StubUtility method fixEmptyVariables.
// remove lines for empty variables
private static String fixEmptyVariables(TemplateBuffer buffer, String[] variables) throws MalformedTreeException, BadLocationException {
IDocument doc = new Document(buffer.getString());
int nLines = doc.getNumberOfLines();
MultiTextEdit edit = new MultiTextEdit();
HashSet<Integer> removedLines = new HashSet<Integer>();
for (int i = 0; i < variables.length; i++) {
// look if Javadoc tags have to be added
TemplateVariable position = findVariable(buffer, variables[i]);
if (position == null || position.getLength() > 0) {
continue;
}
int[] offsets = position.getOffsets();
for (int k = 0; k < offsets.length; k++) {
int line = doc.getLineOfOffset(offsets[k]);
IRegion lineInfo = doc.getLineInformation(line);
int offset = lineInfo.getOffset();
String str = doc.get(offset, lineInfo.getLength());
if (Strings.containsOnlyWhitespaces(str) && nLines > line + 1 && removedLines.add(new Integer(line))) {
int nextStart = doc.getLineOffset(line + 1);
edit.addChild(new DeleteEdit(offset, nextStart - offset));
}
}
}
edit.apply(doc, 0);
return doc.get();
}
use of org.eclipse.text.edits.DeleteEdit in project flux by eclipse.
the class Utils method getOffsetAdjustment.
public static int getOffsetAdjustment(TextEdit edit, final int offset) {
final int[] holder = new int[] { 0 };
edit.accept(new TextEditVisitor() {
@Override
public boolean visit(DeleteEdit edit) {
if (offset >= edit.getOffset()) {
holder[0] -= edit.getLength();
}
return super.visit(edit);
}
@Override
public boolean visit(InsertEdit edit) {
if (offset >= edit.getOffset()) {
holder[0] += edit.getText().length();
}
return super.visit(edit);
}
@Override
public boolean visit(ReplaceEdit edit) {
if (offset >= edit.getOffset()) {
holder[0] += edit.getText().length() - edit.getLength();
}
return super.visit(edit);
}
});
return holder[0];
}
Aggregations