use of org.eclipse.text.edits.MalformedTreeException in project AutoRefactor by JnRouvignac.
the class TestHelper method normalizeJavaSourceCode.
public static String normalizeJavaSourceCode(String source) {
final CodeFormatter codeFormatter = createCodeFormatter(getJava7Options());
final TextEdit edit = // source to format
codeFormatter.format(// source to format
K_COMPILATION_UNIT, // source to format
source, // source to format
0, // source to format
source.length(), // initial indentation and line separator //$NON-NLS-1$
0, // initial indentation and line separator //$NON-NLS-1$
System.getProperty("line.separator"));
try {
final IDocument document = new Document(source);
edit.apply(document);
return document.get();
} catch (MalformedTreeException | BadLocationException e) {
throw new RuntimeException(e);
}
}
use of org.eclipse.text.edits.MalformedTreeException in project eclipse-pmd by acanda.
the class JavaQuickFix method fixMarkersInFile.
/**
* Fixes all provided markers in a file.
*
* @param markers The markers to fix. There is at least one marker in this collection and all markers can be fixed
* by this quick fix.
*/
protected void fixMarkersInFile(final IFile file, final List<IMarker> markers, final IProgressMonitor monitor) {
monitor.subTask(file.getFullPath().toOSString());
final Optional<ICompilationUnit> optionalCompilationUnit = getCompilationUnit(file);
if (!optionalCompilationUnit.isPresent()) {
return;
}
final ICompilationUnit compilationUnit = optionalCompilationUnit.get();
ITextFileBufferManager bufferManager = null;
final IPath path = compilationUnit.getPath();
try {
bufferManager = FileBuffers.getTextFileBufferManager();
bufferManager.connect(path, LocationKind.IFILE, null);
final ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.IFILE);
final IDocument document = textFileBuffer.getDocument();
final IAnnotationModel annotationModel = textFileBuffer.getAnnotationModel();
final ASTParser astParser = ASTParser.newParser(AST.JLS4);
astParser.setKind(ASTParser.K_COMPILATION_UNIT);
astParser.setResolveBindings(needsTypeResolution());
astParser.setSource(compilationUnit);
final SubProgressMonitor parserMonitor = new SubProgressMonitor(monitor, 100);
final CompilationUnit ast = (CompilationUnit) astParser.createAST(parserMonitor);
parserMonitor.done();
startFixingMarkers(ast);
final Map<?, ?> options = compilationUnit.getJavaProject().getOptions(true);
for (final IMarker marker : markers) {
try {
final MarkerAnnotation annotation = getMarkerAnnotation(annotationModel, marker);
// if the annotation is null it means that is was deleted by a previous quick fix
if (annotation != null) {
final Optional<T> node = getNodeFinder(annotationModel.getPosition(annotation)).findNode(ast);
if (node.isPresent()) {
final boolean isSuccessful = fixMarker(node.get(), document, options);
if (isSuccessful) {
marker.delete();
}
}
}
} finally {
monitor.worked(100);
}
}
finishFixingMarkers(ast, document, options);
// commit changes to underlying file if it is not opened in an editor
if (!isEditorOpen(file)) {
final SubProgressMonitor commitMonitor = new SubProgressMonitor(monitor, 100);
textFileBuffer.commit(commitMonitor, false);
commitMonitor.done();
} else {
monitor.worked(100);
}
} catch (CoreException | MalformedTreeException | BadLocationException e) {
// TODO: log error
// PMDPlugin.getDefault().error("Error processing quickfix", e);
} finally {
if (bufferManager != null) {
try {
bufferManager.disconnect(path, LocationKind.IFILE, null);
} catch (final CoreException e) {
// TODO: log error
// PMDPlugin.getDefault().error("Error processing quickfix", e);
}
}
}
}
use of org.eclipse.text.edits.MalformedTreeException in project che by eclipse.
the class SmartSemicolonAutoEditStrategy method customizeDocumentCommand.
/*
* @see org.eclipse.jface.text.IAutoEditStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand)
*/
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
if (command.text == null)
return;
if (command.text.equals(SEMICOLON))
fCharacter = SEMICHAR;
else if (command.text.equals(BRACE))
fCharacter = BRACECHAR;
else
return;
// IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
// if (fCharacter == SEMICHAR && !store.getBoolean(PreferenceConstants.EDITOR_SMART_SEMICOLON))
// return;
// if (fCharacter == BRACECHAR && !store.getBoolean(PreferenceConstants.EDITOR_SMART_OPENING_BRACE))
// return;
//
// IWorkbenchPage page= JavaPlugin.getActivePage();
// if (page == null)
// return;
// IEditorPart part= page.getActiveEditor();
// if (!(part instanceof CompilationUnitEditor))
// return;
// CompilationUnitEditor editor= (CompilationUnitEditor)part;
// if (editor.getInsertMode() != ITextEditorExtension3.SMART_INSERT || !editor.isEditable())
// return;
// ITextEditorExtension2 extension= (ITextEditorExtension2)editor.getAdapter(ITextEditorExtension2.class);
// if (extension != null && !extension.validateEditorInputState())
// return;
// if (isMultilineSelection(document, command))
// return;
// 1: find concerned line / position in java code, location in statement
int pos = command.offset;
ITextSelection line;
try {
IRegion l = document.getLineInformationOfOffset(pos);
line = new TextSelection(document, l.getOffset(), l.getLength());
} catch (BadLocationException e) {
return;
}
// 2: choose action based on findings (is for-Statement?)
// for now: compute the best position to insert the new character
int positionInLine = computeCharacterPosition(document, line, pos - line.getOffset(), fCharacter, fPartitioning);
int position = positionInLine + line.getOffset();
// never position before the current position!
if (position < pos)
return;
// never double already existing content
if (alreadyPresent(document, fCharacter, position))
return;
// don't do special processing if what we do is actually the normal behaviour
String insertion = adjustSpacing(document, position, fCharacter);
if (command.offset == position && insertion.equals(command.text))
return;
try {
// final SmartBackspaceManager manager= (SmartBackspaceManager) editor.getAdapter(SmartBackspaceManager.class);
// if (manager != null && JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_BACKSPACE)) {
// TextEdit e1= new ReplaceEdit(command.offset, command.text.length(), document.get(command.offset, command.length));
// UndoSpec s1= new UndoSpec(command.offset + command.text.length(),
// new Region(command.offset, 0),
// new TextEdit[] {e1},
// 0,
// null);
//
// DeleteEdit smart= new DeleteEdit(position, insertion.length());
// ReplaceEdit raw= new ReplaceEdit(command.offset, command.length, command.text);
// UndoSpec s2= new UndoSpec(position + insertion.length(),
// new Region(command.offset + command.text.length(), 0),
// new TextEdit[] {smart, raw},
// 2,
// s1);
// manager.register(s2);
// }
// 3: modify command
command.offset = position;
command.length = 0;
command.caretOffset = position;
command.text = insertion;
command.doit = true;
command.owner = null;
} catch (MalformedTreeException e) {
JavaPlugin.log(e);
}
}
use of org.eclipse.text.edits.MalformedTreeException in project che by eclipse.
the class InlineTempRefactoring method createParameterizedInvocation.
private String createParameterizedInvocation(Expression invocation, ITypeBinding[] typeArguments, CompilationUnitRewrite cuRewrite) throws JavaModelException {
ASTRewrite rewrite = ASTRewrite.create(invocation.getAST());
ListRewrite typeArgsRewrite = Invocations.getInferredTypeArgumentsRewrite(rewrite, invocation);
for (int i = 0; i < typeArguments.length; i++) {
Type typeArgumentNode = cuRewrite.getImportRewrite().addImport(typeArguments[i], cuRewrite.getAST());
typeArgsRewrite.insertLast(typeArgumentNode, null);
}
if (invocation instanceof MethodInvocation) {
MethodInvocation methodInvocation = (MethodInvocation) invocation;
Expression expression = methodInvocation.getExpression();
if (expression == null) {
IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
if (methodBinding != null && Modifier.isStatic(methodBinding.getModifiers())) {
expression = cuRewrite.getAST().newName(cuRewrite.getImportRewrite().addImport(methodBinding.getDeclaringClass().getTypeDeclaration()));
} else {
expression = invocation.getAST().newThisExpression();
}
rewrite.set(invocation, MethodInvocation.EXPRESSION_PROPERTY, expression, null);
}
}
IDocument document = new Document(fCu.getBuffer().getContents());
final RangeMarker marker = new RangeMarker(invocation.getStartPosition(), invocation.getLength());
IJavaProject project = fCu.getJavaProject();
TextEdit[] rewriteEdits = rewrite.rewriteAST(document, project.getOptions(true)).removeChildren();
marker.addChildren(rewriteEdits);
try {
marker.apply(document, TextEdit.UPDATE_REGIONS);
String rewrittenInitializer = document.get(marker.getOffset(), marker.getLength());
IRegion region = document.getLineInformation(document.getLineOfOffset(marker.getOffset()));
int oldIndent = Strings.computeIndentUnits(document.get(region.getOffset(), region.getLength()), project);
//$NON-NLS-1$
return Strings.changeIndent(rewrittenInitializer, oldIndent, project, "", TextUtilities.getDefaultLineDelimiter(document));
} catch (MalformedTreeException e) {
JavaPlugin.log(e);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
//fallback:
return fCu.getBuffer().getText(invocation.getStartPosition(), invocation.getLength());
}
use of org.eclipse.text.edits.MalformedTreeException in project che by eclipse.
the class TextChange method perform.
/**
* {@inheritDoc}
*/
public Change perform(IProgressMonitor pm) throws CoreException {
//$NON-NLS-1$
pm.beginTask("", 3);
IDocument document = null;
try {
document = acquireDocument(new SubProgressMonitor(pm, 1));
UndoEdit undo = performEdits(document);
commit(document, new SubProgressMonitor(pm, 1));
return createUndoChange(undo);
} catch (BadLocationException e) {
throw Changes.asCoreException(e);
} catch (MalformedTreeException e) {
throw Changes.asCoreException(e);
} finally {
releaseDocument(document, new SubProgressMonitor(pm, 1));
pm.done();
}
}
Aggregations