use of org.eclipse.jface.text.Document in project che by eclipse.
the class MultiStateTextFileChange method getCurrentDocument.
/**
* Returns a document representing the current state of the buffer,
* prior to the application of the change.
* <p>
* The returned document should not be modified.
* </p>
*
* @param monitor
* the progress monitor to use, or <code>null</code>
* @return the current document, or the empty document
* @throws CoreException
* if no document could be acquired
*/
public final IDocument getCurrentDocument(IProgressMonitor monitor) throws CoreException {
if (monitor == null)
monitor = new NullProgressMonitor();
IDocument result = null;
//$NON-NLS-1$
monitor.beginTask("", 2);
try {
result = acquireDocument(new SubProgressMonitor(monitor, 1));
} finally {
if (result != null)
releaseDocument(result, new SubProgressMonitor(monitor, 1));
}
monitor.done();
if (result == null)
result = new Document();
return result;
}
use of org.eclipse.jface.text.Document in project che by eclipse.
the class MultiStateTextFileChange method getPreviewContent.
/*
* @see org.eclipse.ltk.core.refactoring.TextEditBasedChange#getPreviewContent(org.eclipse.ltk.core.refactoring.TextEditBasedChangeGroup[],org.eclipse.jface.text.IRegion,boolean,int,org.eclipse.core.runtime.IProgressMonitor)
*/
public final String getPreviewContent(final TextEditBasedChangeGroup[] groups, final IRegion region, final boolean expand, final int surround, final IProgressMonitor monitor) throws CoreException {
final Set cachedGroups = new HashSet(Arrays.asList(groups));
final IDocument document = new Document(getCurrentDocument(monitor).get());
// Marks the region in the document to be previewed
final Position range = new Position(region.getOffset(), region.getLength());
try {
ComposableBufferChange change = null;
final TextEditBasedChangeGroup[] changedGroups = getChangeGroups();
LinkedList compositeUndo = new LinkedList();
for (int index = 0; index < fChanges.size(); index++) {
change = (ComposableBufferChange) fChanges.get(index);
TextEdit copy = null;
try {
// Have to use a copy
fCopier = new TextEditCopier(change.getEdit());
copy = fCopier.perform();
// Create a mapping from the copied edits to its originals
final Map originalMap = new HashMap();
for (final Iterator outer = change.getGroups().iterator(); outer.hasNext(); ) {
final ComposableBufferChangeGroup group = (ComposableBufferChangeGroup) outer.next();
for (final Iterator inner = group.getCachedEdits().iterator(); inner.hasNext(); ) {
final TextEdit originalEdit = (TextEdit) inner.next();
final TextEdit copiedEdit = fCopier.getCopy(originalEdit);
if (copiedEdit != null)
originalMap.put(copiedEdit, originalEdit);
else
//$NON-NLS-1$
RefactoringCorePlugin.logErrorMessage("Could not find a copy for the indexed text edit " + originalEdit.toString());
}
}
final ComposableBufferChangeGroup[] currentGroup = { null };
final TextEdit[] currentEdit = { null };
// Text edit processor which sets the change group and
// current edit when processing
final TextEditProcessor processor = new TextEditProcessor(document, copy, TextEdit.NONE) {
protected final boolean considerEdit(final TextEdit edit) {
final TextEdit originalEdit = (TextEdit) originalMap.get(edit);
if (originalEdit != null) {
currentEdit[0] = originalEdit;
boolean found = false;
for (int offset = 0; offset < changedGroups.length && !found; offset++) {
final ComposableBufferChangeGroup group = (ComposableBufferChangeGroup) changedGroups[offset];
if (group.containsEdit(originalEdit)) {
currentGroup[0] = group;
found = true;
}
}
if (!found)
currentGroup[0] = null;
} else if (!(edit instanceof MultiTextEdit)) {
//$NON-NLS-1$
RefactoringCorePlugin.logErrorMessage("Could not find the original of the copied text edit " + edit.toString());
}
return true;
}
};
final LinkedList eventUndos = new LinkedList();
// Listener to record the undos on the document (offsets
// relative to the document event)
final IDocumentListener listener = new IDocumentListener() {
public final void documentAboutToBeChanged(final DocumentEvent event) {
final ComposableUndoEdit edit = new ComposableUndoEdit();
edit.setGroup(currentGroup[0]);
edit.setOriginal(currentEdit[0]);
edit.setUndo(createUndoEdit(document, event.getOffset(), event.getLength(), event.getText()));
eventUndos.addFirst(edit);
}
public final void documentChanged(final DocumentEvent event) {
// Do nothing
}
};
try {
// Record undos in LIFO order
document.addDocumentListener(listener);
processor.performEdits();
} finally {
document.removeDocumentListener(listener);
}
compositeUndo.addFirst(eventUndos);
} finally {
fCopier = null;
}
}
final IPositionUpdater positionUpdater = new IPositionUpdater() {
public final void update(final DocumentEvent event) {
final int eventOffset = event.getOffset();
final int eventLength = event.getLength();
final int eventOldEndOffset = eventOffset + eventLength;
final String eventText = event.getText();
final int eventNewLength = eventText == null ? 0 : eventText.length();
final int eventNewEndOffset = eventOffset + eventNewLength;
final int deltaLength = eventNewLength - eventLength;
try {
final Position[] positions = event.getDocument().getPositions(COMPOSABLE_POSITION_CATEGORY);
for (int index = 0; index < positions.length; index++) {
final Position position = positions[index];
if (position.isDeleted())
continue;
final int offset = position.getOffset();
final int length = position.getLength();
final int end = offset + length;
if (offset > eventOldEndOffset) {
// position comes way after change - shift
position.setOffset(offset + deltaLength);
} else if (end < eventOffset) {
// position comes way before change - leave
// alone
} else if (offset == eventOffset) {
// leave alone, since the edits are overlapping
} else if (offset <= eventOffset && end >= eventOldEndOffset) {
// event completely internal to the position
// -
// adjust length
position.setLength(length + deltaLength);
} else if (offset < eventOffset) {
// event extends over end of position - include
// the
// replacement text into the position
position.setLength(eventNewEndOffset - offset);
} else if (end > eventOldEndOffset) {
// event extends from before position into it -
// adjust
// offset and length, including the replacement
// text into
// the position
position.setOffset(eventOffset);
int deleted = eventOldEndOffset - offset;
position.setLength(length - deleted + eventNewLength);
} else {
// event comprises the position - keep it at the
// same
// position, but always inside the replacement
// text
int newOffset = Math.min(offset, eventNewEndOffset);
int newEndOffset = Math.min(end, eventNewEndOffset);
position.setOffset(newOffset);
position.setLength(newEndOffset - newOffset);
}
}
} catch (BadPositionCategoryException exception) {
// ignore and return
}
}
};
try {
document.addPositionCategory(COMPOSABLE_POSITION_CATEGORY);
document.addPositionUpdater(positionUpdater);
// Apply undos in LIFO order to get to the original document
// Track the undos of edits which are in change groups to be
// previewed and insert
// Undo edits for them (corresponding to the linearized net
// effect on the original document)
final LinkedList undoQueue = new LinkedList();
for (final Iterator outer = compositeUndo.iterator(); outer.hasNext(); ) {
for (final Iterator inner = ((List) outer.next()).iterator(); inner.hasNext(); ) {
final ComposableUndoEdit edit = (ComposableUndoEdit) inner.next();
final ReplaceEdit undo = edit.getUndo();
final int offset = undo.getOffset();
final int length = undo.getLength();
final String text = undo.getText();
ComposableEditPosition position = new ComposableEditPosition();
if (cachedGroups.contains(edit.getGroup())) {
if (text == null || text.equals("")) {
//$NON-NLS-1$
position.offset = offset;
if (length != 0) {
// Undo is a delete, create final insert
// edit
position.length = 0;
position.setText(edit.getOriginalText());
} else
//$NON-NLS-1$
RefactoringCorePlugin.logErrorMessage("Dubious undo edit found: " + undo.toString());
} else if (length == 0) {
position.offset = offset;
// Undo is an insert, create final delete
// edit
//$NON-NLS-1$
position.setText("");
position.length = text.length();
} else {
// Undo is a replace, create final replace edit
position.offset = offset;
position.length = length;
position.setText(edit.getOriginalText());
}
document.addPosition(COMPOSABLE_POSITION_CATEGORY, position);
}
position = new ComposableEditPosition();
position.offset = undo.getOffset();
position.length = undo.getLength();
position.setText(undo.getText());
undoQueue.add(position);
}
for (final Iterator iterator = undoQueue.iterator(); iterator.hasNext(); ) {
final ComposableEditPosition position = (ComposableEditPosition) iterator.next();
document.replace(position.offset, position.length, position.getText());
iterator.remove();
}
}
// Use a simple non deleting position updater for the range
final IPositionUpdater markerUpdater = new NonDeletingPositionUpdater(MARKER_POSITION_CATEGORY);
try {
final Position[] positions = document.getPositions(COMPOSABLE_POSITION_CATEGORY);
document.addPositionCategory(MARKER_POSITION_CATEGORY);
document.addPositionUpdater(markerUpdater);
document.addPosition(MARKER_POSITION_CATEGORY, range);
for (int index = 0; index < positions.length; index++) {
final ComposableEditPosition position = (ComposableEditPosition) positions[index];
//$NON-NLS-1$
document.replace(position.offset, position.length, position.getText() != null ? position.getText() : "");
}
} catch (BadPositionCategoryException exception) {
RefactoringCorePlugin.log(exception);
} finally {
document.removePositionUpdater(markerUpdater);
try {
document.removePosition(MARKER_POSITION_CATEGORY, range);
document.removePositionCategory(MARKER_POSITION_CATEGORY);
} catch (BadPositionCategoryException exception) {
// Cannot happen
}
}
} catch (BadPositionCategoryException exception) {
RefactoringCorePlugin.log(exception);
} finally {
document.removePositionUpdater(positionUpdater);
try {
document.removePositionCategory(COMPOSABLE_POSITION_CATEGORY);
} catch (BadPositionCategoryException exception) {
RefactoringCorePlugin.log(exception);
}
}
return getContent(document, new Region(range.offset, range.length), expand, surround);
} catch (MalformedTreeException exception) {
RefactoringCorePlugin.log(exception);
} catch (BadLocationException exception) {
RefactoringCorePlugin.log(exception);
}
return getPreviewDocument(monitor).get();
}
use of org.eclipse.jface.text.Document in project che by eclipse.
the class CUCorrectionProposal method createTextChange.
/**
* Creates the text change for this proposal.
* This method is only called once and only when no text change has been passed in
* {@link #CUCorrectionProposal(String, ICompilationUnit, TextChange, int, Image)}.
*
* @return the created text change
* @throws CoreException if the creation of the text change failed
*/
protected TextChange createTextChange() throws CoreException {
ICompilationUnit cu = getCompilationUnit();
String name = getName();
TextChange change;
if (!cu.getResource().exists()) {
String source;
try {
source = cu.getSource();
} catch (JavaModelException e) {
JavaPlugin.log(e);
// empty
source = new String();
}
Document document = new Document(source);
document.setInitialLineDelimiter(StubUtility.getLineDelimiterUsed(cu));
change = new DocumentChange(name, document);
} else {
CompilationUnitChange cuChange = new CompilationUnitChange(name, cu);
cuChange.setSaveMode(TextFileChange.LEAVE_DIRTY);
change = cuChange;
}
TextEdit rootEdit = new MultiTextEdit();
change.setEdit(rootEdit);
// initialize text change
IDocument document = change.getCurrentDocument(new NullProgressMonitor());
addEdits(document, rootEdit);
return change;
}
use of org.eclipse.jface.text.Document in project che by eclipse.
the class SearchManager method performFindUsageSearch.
private FindUsagesResponse performFindUsageSearch(IJavaElement element) throws JavaModelException, BadLocationException {
JavaSearchScopeFactory factory = JavaSearchScopeFactory.getInstance();
boolean isInsideJRE = factory.isInsideJRE(element);
JavaSearchQuery query = new JavaSearchQuery(new ElementQuerySpecification(element, IJavaSearchConstants.REFERENCES, factory.createWorkspaceScope(isInsideJRE), "workspace scope"));
NewSearchUI.runQueryInForeground(null, query);
ISearchResult result = query.getSearchResult();
JavaSearchResult javaResult = ((JavaSearchResult) result);
FindUsagesResponse response = DtoFactory.newDto(FindUsagesResponse.class);
Map<String, List<org.eclipse.che.ide.ext.java.shared.dto.search.Match>> mapMaches = new HashMap<>();
JavaElementToDtoConverter converter = new JavaElementToDtoConverter(javaResult);
for (Object o : javaResult.getElements()) {
IJavaElement javaElement = (IJavaElement) o;
IDocument document = null;
if (javaElement instanceof IMember) {
IMember member = ((IMember) javaElement);
if (member.isBinary()) {
if (member.getClassFile().getSource() != null) {
document = new Document(member.getClassFile().getSource());
}
} else {
document = getDocument(member.getCompilationUnit());
}
} else if (javaElement instanceof IPackageDeclaration) {
ICompilationUnit ancestor = (ICompilationUnit) (javaElement).getAncestor(IJavaElement.COMPILATION_UNIT);
document = getDocument(ancestor);
}
converter.addElementToProjectHierarchy(javaElement);
Match[] matches = javaResult.getMatches(o);
List<org.eclipse.che.ide.ext.java.shared.dto.search.Match> matchList = new ArrayList<>();
for (Match match : matches) {
org.eclipse.che.ide.ext.java.shared.dto.search.Match dtoMatch = DtoFactory.newDto(org.eclipse.che.ide.ext.java.shared.dto.search.Match.class);
if (document != null) {
IRegion lineInformation = document.getLineInformationOfOffset(match.getOffset());
int offsetInLine = match.getOffset() - lineInformation.getOffset();
Region matchInLine = DtoFactory.newDto(Region.class).withOffset(offsetInLine).withLength(match.getLength());
dtoMatch.setMatchInLine(matchInLine);
dtoMatch.setMatchLineNumber(document.getLineOfOffset(match.getOffset()));
dtoMatch.setMatchedLine(document.get(lineInformation.getOffset(), lineInformation.getLength()));
}
dtoMatch.setFileMatchRegion(DtoFactory.newDto(Region.class).withOffset(match.getOffset()).withLength(match.getLength()));
matchList.add(dtoMatch);
}
mapMaches.put(javaElement.getHandleIdentifier(), matchList);
}
List<JavaProject> projects = converter.getProjects();
response.setProjects(projects);
response.setMatches(mapMaches);
response.setSearchElementLabel(JavaElementLabels.getElementLabel(element, JavaElementLabels.ALL_DEFAULT));
return response;
}
use of org.eclipse.jface.text.Document in project flux by eclipse.
the class StubUtility method getMethodComment.
/*
* Don't use this method directly, use CodeGeneration.
* This method should work with all AST levels.
* @see org.eclipse.jdt.ui.CodeGeneration#getMethodComment(ICompilationUnit, String, MethodDeclaration, boolean, String, String[], String)
*/
public static String getMethodComment(ICompilationUnit cu, String typeName, MethodDeclaration decl, boolean isDeprecated, String targetName, String targetMethodDeclaringTypeName, String[] targetMethodParameterTypeNames, boolean delegate, String lineDelimiter) throws CoreException {
boolean needsTarget = targetMethodDeclaringTypeName != null && targetMethodParameterTypeNames != null;
String templateName = CodeTemplateContextType.METHODCOMMENT_ID;
if (decl.isConstructor()) {
templateName = CodeTemplateContextType.CONSTRUCTORCOMMENT_ID;
} else if (needsTarget) {
if (delegate)
templateName = CodeTemplateContextType.DELEGATECOMMENT_ID;
else
templateName = CodeTemplateContextType.OVERRIDECOMMENT_ID;
}
Template template = getCodeTemplate(templateName, cu.getJavaProject());
if (template == null) {
return null;
}
CodeTemplateContext context = new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter);
context.setCompilationUnitVariables(cu);
context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName);
context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, decl.getName().getIdentifier());
if (!decl.isConstructor()) {
context.setVariable(CodeTemplateContextType.RETURN_TYPE, ASTNodes.asString(getReturnType(decl)));
}
if (needsTarget) {
if (delegate)
context.setVariable(CodeTemplateContextType.SEE_TO_TARGET_TAG, getSeeTag(targetMethodDeclaringTypeName, targetName, targetMethodParameterTypeNames));
else
context.setVariable(CodeTemplateContextType.SEE_TO_OVERRIDDEN_TAG, getSeeTag(targetMethodDeclaringTypeName, targetName, targetMethodParameterTypeNames));
}
TemplateBuffer buffer;
try {
buffer = context.evaluate(template);
} catch (BadLocationException e) {
throw new CoreException(Status.CANCEL_STATUS);
} catch (TemplateException e) {
throw new CoreException(Status.CANCEL_STATUS);
}
if (buffer == null)
return null;
String str = buffer.getString();
if (Strings.containsOnlyWhitespaces(str)) {
return null;
}
// look if Javadoc tags have to be added
TemplateVariable position = findVariable(buffer, CodeTemplateContextType.TAGS);
if (position == null) {
return str;
}
IDocument textBuffer = new Document(str);
List<TypeParameter> typeParams = shouldGenerateMethodTypeParameterTags(cu.getJavaProject()) ? decl.typeParameters() : Collections.emptyList();
String[] typeParamNames = new String[typeParams.size()];
for (int i = 0; i < typeParamNames.length; i++) {
TypeParameter elem = typeParams.get(i);
typeParamNames[i] = elem.getName().getIdentifier();
}
List<SingleVariableDeclaration> params = decl.parameters();
String[] paramNames = new String[params.size()];
for (int i = 0; i < paramNames.length; i++) {
SingleVariableDeclaration elem = params.get(i);
paramNames[i] = elem.getName().getIdentifier();
}
String[] exceptionNames = getExceptionNames(decl);
String returnType = null;
if (!decl.isConstructor()) {
returnType = ASTNodes.asString(getReturnType(decl));
}
int[] tagOffsets = position.getOffsets();
for (int i = tagOffsets.length - 1; i >= 0; i--) {
// from last to first
try {
insertTag(textBuffer, tagOffsets[i], position.getLength(), paramNames, exceptionNames, returnType, typeParamNames, isDeprecated, lineDelimiter);
} catch (BadLocationException e) {
throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
}
}
return textBuffer.get();
}
Aggregations