use of org.eclipse.text.edits.MalformedTreeException in project eclipse.platform.text by eclipse.
the class LinkedPositionGroup method handleEvent.
/**
* Creates an edition of a document change that will forward any
* modification in one position to all linked siblings. The return value is
* a map from <code>IDocument</code> to <code>TextEdit</code>.
*
* @param event the document event to check
* @return a map of edits, grouped by edited document, or <code>null</code>
* if there are no edits
*/
Map<IDocument, TextEdit> handleEvent(DocumentEvent event) {
if (fLastPosition != null) {
Map<IDocument, List<ReplaceEdit>> map = new HashMap<>();
int relativeOffset = event.getOffset() - fLastRegion.getOffset();
if (relativeOffset < 0) {
relativeOffset = 0;
}
int eventEnd = event.getOffset() + event.getLength();
int lastEnd = fLastRegion.getOffset() + fLastRegion.getLength();
int length;
if (eventEnd > lastEnd)
length = lastEnd - relativeOffset - fLastRegion.getOffset();
else
length = eventEnd - relativeOffset - fLastRegion.getOffset();
String text = event.getText();
if (text == null)
// $NON-NLS-1$
text = "";
for (LinkedPosition p : fPositions) {
if (p == fLastPosition || p.isDeleted())
// don't re-update the origin of the change
continue;
List<ReplaceEdit> edits = map.get(p.getDocument());
if (edits == null) {
edits = new ArrayList<>();
map.put(p.getDocument(), edits);
}
if (fMustEnforceEqualContents) {
try {
edits.add(new ReplaceEdit(p.getOffset(), p.getLength(), fLastPosition.getContent()));
} catch (BadLocationException e) {
// should not happen
throw new RuntimeException(e);
}
} else {
edits.add(new ReplaceEdit(p.getOffset() + relativeOffset, length, text));
}
}
fMustEnforceEqualContents = false;
try {
Map<IDocument, TextEdit> result = new HashMap<>();
for (IDocument d : map.keySet()) {
TextEdit edit = new MultiTextEdit(0, d.getLength());
edit.addChildren(map.get(d).toArray(new TextEdit[0]));
result.put(d, edit);
}
return result;
} catch (MalformedTreeException x) {
// manager
return null;
}
}
return null;
}
use of org.eclipse.text.edits.MalformedTreeException in project eclipse.jdt.ls by eclipse.
the class AnonymousTypeCompletionProposal method createNewBody.
private String createNewBody(ImportRewrite importRewrite) throws CoreException {
if (importRewrite == null) {
return null;
}
ICompilationUnit workingCopy = null;
try {
// $NON-NLS-1$
String name = "Type" + System.currentTimeMillis();
workingCopy = fCompilationUnit.getPrimary().getWorkingCopy(null);
ISourceRange range = fSuperType.getSourceRange();
boolean sameUnit = range != null && fCompilationUnit.equals(fSuperType.getCompilationUnit());
String dummyClassContent = createDummyType(name);
StringBuffer workingCopyContents = new StringBuffer(fCompilationUnit.getSource());
int insertPosition;
if (sameUnit) {
insertPosition = range.getOffset() + range.getLength();
} else {
ISourceRange firstTypeRange = fCompilationUnit.getTypes()[0].getSourceRange();
insertPosition = firstTypeRange.getOffset();
}
if (fSuperType.isLocal()) {
workingCopyContents.insert(insertPosition, '{' + dummyClassContent + '}');
insertPosition++;
} else {
// $NON-NLS-1$
workingCopyContents.insert(insertPosition, dummyClassContent + "\n\n");
}
workingCopy.getBuffer().setContents(workingCopyContents.toString());
ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
parser.setResolveBindings(true);
parser.setStatementsRecovery(true);
parser.setSource(workingCopy);
CompilationUnit astRoot = (CompilationUnit) parser.createAST(new NullProgressMonitor());
ASTNode newType = NodeFinder.perform(astRoot, insertPosition, dummyClassContent.length());
if (!(newType instanceof AbstractTypeDeclaration)) {
return null;
}
AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) newType;
ITypeBinding dummyTypeBinding = declaration.resolveBinding();
if (dummyTypeBinding == null) {
return null;
}
IMethodBinding[] bindings = StubUtility2.getOverridableMethods(astRoot.getAST(), dummyTypeBinding, true);
if (fSuperType.isInterface()) {
ITypeBinding[] dummySuperInterfaces = dummyTypeBinding.getInterfaces();
if (dummySuperInterfaces.length == 0 || dummySuperInterfaces.length == 1 && dummySuperInterfaces[0].isRawType()) {
bindings = new IMethodBinding[0];
}
} else {
ITypeBinding dummySuperclass = dummyTypeBinding.getSuperclass();
if (dummySuperclass == null || dummySuperclass.isRawType()) {
bindings = new IMethodBinding[0];
}
}
CodeGenerationSettings settings = PreferenceManager.getCodeGenerationSettings(fJavaProject.getProject());
IMethodBinding[] methodsToOverride = null;
settings.createComments = false;
List<IMethodBinding> result = new ArrayList<>();
for (int i = 0; i < bindings.length; i++) {
IMethodBinding curr = bindings[i];
if (Modifier.isAbstract(curr.getModifiers())) {
result.add(curr);
}
}
methodsToOverride = result.toArray(new IMethodBinding[result.size()]);
// used to find @NonNullByDefault effective at that current context
IBinding contextBinding = null;
if (fCompilationUnit.getJavaProject().getOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, true).equals(JavaCore.ENABLED)) {
ASTNode focusNode = NodeFinder.perform(astRoot, fReplacementOffset + dummyClassContent.length(), 0);
contextBinding = getEnclosingDeclaration(focusNode);
}
ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
ITrackedNodePosition trackedDeclaration = rewrite.track(declaration);
ListRewrite rewriter = rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
for (int i = 0; i < methodsToOverride.length; i++) {
boolean snippetSupport = i == methodsToOverride.length - 1 ? fSnippetSupport : false;
IMethodBinding curr = methodsToOverride[i];
MethodDeclaration stub = StubUtility2.createImplementationStub(workingCopy, rewrite, importRewrite, null, curr, dummyTypeBinding, settings, dummyTypeBinding.isInterface(), contextBinding, snippetSupport);
rewriter.insertFirst(stub, null);
}
IDocument document = new Document(workingCopy.getSource());
try {
rewrite.rewriteAST().apply(document);
int bodyStart = trackedDeclaration.getStartPosition() + dummyClassContent.indexOf('{');
int bodyEnd = trackedDeclaration.getStartPosition() + trackedDeclaration.getLength();
return document.get(bodyStart, bodyEnd - bodyStart);
} catch (MalformedTreeException exception) {
JavaLanguageServerPlugin.logException(exception.getMessage(), exception);
} catch (BadLocationException exception) {
JavaLanguageServerPlugin.logException(exception.getMessage(), exception);
}
return null;
} finally {
if (workingCopy != null) {
workingCopy.discardWorkingCopy();
}
}
}
use of org.eclipse.text.edits.MalformedTreeException in project eclipse.jdt.ls by eclipse.
the class DocumentLifeCycleHandler method handleChanged.
public void handleChanged(DidChangeTextDocumentParams params) {
ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri());
if (unit == null || !unit.isWorkingCopy() || params.getContentChanges().isEmpty()) {
return;
}
try {
if (unit.equals(sharedASTProvider.getActiveJavaElement())) {
sharedASTProvider.disposeAST();
}
List<TextDocumentContentChangeEvent> contentChanges = params.getContentChanges();
for (TextDocumentContentChangeEvent changeEvent : contentChanges) {
Range range = changeEvent.getRange();
int length;
if (range != null) {
length = changeEvent.getRangeLength().intValue();
} else {
// range is optional and if not given, the whole file content is replaced
length = unit.getSource().length();
range = JDTUtils.toRange(unit, 0, length);
}
int startOffset = JsonRpcHelpers.toOffset(unit.getBuffer(), range.getStart().getLine(), range.getStart().getCharacter());
TextEdit edit = null;
String text = changeEvent.getText();
if (length == 0) {
edit = new InsertEdit(startOffset, text);
} else if (text.isEmpty()) {
edit = new DeleteEdit(startOffset, length);
} else {
edit = new ReplaceEdit(startOffset, length, text);
}
IDocument document = JsonRpcHelpers.toDocument(unit.getBuffer());
edit.apply(document, TextEdit.NONE);
}
triggerValidation(unit);
} catch (JavaModelException | MalformedTreeException | BadLocationException e) {
JavaLanguageServerPlugin.logException("Error while handling document change", e);
}
}
use of org.eclipse.text.edits.MalformedTreeException in project jbosstools-hibernate by jbosstools.
the class CodeGenExternalProcessExecutionTest method formatJavaFile.
/**
* format string as java file.
*
* @param str
* @return
*/
public String formatJavaFile(String str) {
Document doc = new Document(str);
TextEdit edit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, str, 0, str.length(), 0, null);
try {
edit.apply(doc);
} catch (MalformedTreeException e) {
} catch (BadLocationException e) {
}
return doc.get();
}
use of org.eclipse.text.edits.MalformedTreeException in project jbosstools-hibernate by jbosstools.
the class AllEntitiesProcessor method performCommit.
protected void performCommit(final Map<String, EntityInfo> entities) {
final ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
for (int i = 0; i < changes.size(); i++) {
ChangeStructure cs = changes.get(i);
if (cs.textEdit != null && ((cs.change != null && cs.change.isEnabled()) || (cs.change == null))) {
ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(cs.path, LocationKind.IFILE);
IDocument document = textFileBuffer.getDocument();
try {
cs.textEdit.apply(document);
} catch (MalformedTreeException e) {
// $NON-NLS-1$
HibernateConsolePlugin.getDefault().logErrorMessage("MalformedTreeException: ", e);
} catch (BadLocationException e) {
// $NON-NLS-1$
HibernateConsolePlugin.getDefault().logErrorMessage("BadLocationException: ", e);
}
try {
// commit changes to underlying file
textFileBuffer.commit(null, true);
} catch (CoreException e) {
// $NON-NLS-1$
HibernateConsolePlugin.getDefault().logErrorMessage("CoreException: ", e);
}
}
}
}
Aggregations