下面列出了怎么用org.eclipse.jface.text.DocumentRewriteSession的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Applies all given changes to the given document. This method assumes that 'changes' contains only changes
* intended for the given document; the actual URI stored in the changes is ignored.
*/
public void applyAllInSameDocument(Collection<? extends IAtomicChange> changes, IDocument document)
throws BadLocationException {
DocumentRewriteSession rewriteSession = null;
try {
// prepare
if (document instanceof IDocumentExtension4) {
rewriteSession = ((IDocumentExtension4) document).startRewriteSession(
DocumentRewriteSessionType.UNRESTRICTED);
}
// perform replacements
for (IAtomicChange currRepl : changes) {
currRepl.apply(document);
}
} finally {
// cleanup
if (rewriteSession != null)
((IDocumentExtension4) document).stopRewriteSession(rewriteSession);
}
}
@Override
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
IDocument document = viewer.getDocument();
// ImportsVariableResolver may add imports, so start a rewrite session if possible.
// This will compound all document changes in one Undo entry.
if (document instanceof IDocumentExtension4) {
IDocumentExtension4 docExt4 = (IDocumentExtension4) document;
DocumentRewriteSession session = docExt4.startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
super.apply(viewer, trigger, stateMask, offset);
if (session != null) {
docExt4.stopRewriteSession(session);
}
} else {
super.apply(viewer, trigger, stateMask, offset);
}
}
public void doOrganizeImports(final IXtextDocument document) {
List<ReplaceRegion> result = document.priorityReadOnly(new IUnitOfWork<List<ReplaceRegion>, XtextResource>() {
@Override
public List<ReplaceRegion> exec(XtextResource state) throws Exception {
return importOrganizer.getOrganizedImportChanges(state);
}
});
if (result == null || result.isEmpty())
return;
try {
DocumentRewriteSession session = null;
if(document instanceof IDocumentExtension4) {
session = ((IDocumentExtension4)document).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
}
replaceConverter.convertToTextEdit(result).apply(document);
if(session != null) {
((IDocumentExtension4)document).stopRewriteSession(session);
}
} catch (BadLocationException e) {
LOG.error(Messages.OrganizeImportsHandler_organizeImportsErrorMessage, e);
}
}
/**
* Sets text to a document
* @param document
* @param message
* @param append
* @throws BadLocationException
* Has to be run from non-UI thread
*/
public static synchronized void setDocumentText(final Document document, final String message,
final boolean append) {
UIHelper.runUIAsync(new Runnable() {
public void run() {
try {
DocumentRewriteSession rewriteSession;
if (append && !isDefaultLabel(document)) {
rewriteSession = document.startRewriteSession(DocumentRewriteSessionType.SEQUENTIAL);
// append to existing document (0 length is valid and means message is going to be appended)
document.replace(document.getLength(), 0, message + ((message.endsWith(CR)) ? EMPTY : CR));
} else {
rewriteSession = document.startRewriteSession(DocumentRewriteSessionType.STRICTLY_SEQUENTIAL);
// replace of complete document
document.replace(0, document.getLength(), message + ((message.endsWith(CR)) ? EMPTY : CR));
}
document.stopRewriteSession(rewriteSession);
} catch (BadLocationException ignored) {
}
}
});
}
@Override
public void commit(boolean onSave) {
BusinessObjectModel workingCopy = formPage.observeWorkingCopy().getValue();
JobSafeStructuredDocument document = (JobSafeStructuredDocument) formPage.getDocument();
DocumentRewriteSession session = null;
try {
session = document.startRewriteSession(DocumentRewriteSessionType.STRICTLY_SEQUENTIAL);
document.set(new String(formPage.getParser().marshall(formPage.getConverter().toEngineModel(workingCopy))));
BDMArtifactDescriptor bdmArtifactDescriptor = new BDMArtifactDescriptor();
bdmArtifactDescriptor.setGroupId(workingCopy.getGroupId());
formPage.getEditorContribution().saveBdmArtifactDescriptor(bdmArtifactDescriptor);
} catch (final JAXBException | IOException | SAXException e) {
throw new RuntimeException("Fail to update the document", e);
} finally {
if (session != null) {
document.stopRewriteSession(session);
}
}
super.commit(onSave);
if (onSave) {
getManagedForm().dirtyStateChanged();
}
}
/**
* @since 2.2
*/
@Override
public void startRewriteSession(DocumentRewriteSession session) throws IllegalStateException {
if (fActiveRewriteSession != null)
throw new IllegalStateException();
fActiveRewriteSession = session;
}
protected UndoEdit performEdits(IDocument document) throws BadLocationException, MalformedTreeException {
DocumentRewriteSession session = null;
try {
if (document instanceof IDocumentExtension4) {
session = ((IDocumentExtension4) document).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
}
return undoEdit.apply(document);
} finally {
if (session != null) {
((IDocumentExtension4) document).stopRewriteSession(session);
}
}
}
/**
* Stop a rewrite session
*/
public static void endWrite(IDocument doc, DocumentRewriteSession session) {
if (doc instanceof IDocumentExtension4 && session != null) {
IDocumentExtension4 d = (IDocumentExtension4) doc;
d.stopRewriteSession(session);
}
}
/**
* Starts a rewrite session (keep things in a single undo/redo)
*/
public static DocumentRewriteSession startWrite(IDocument doc) {
if (doc instanceof IDocumentExtension4) {
IDocumentExtension4 d = (IDocumentExtension4) doc;
return d.startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
}
return null;
}
@Override
public void startRewriteSession(DocumentRewriteSession session) throws IllegalStateException {
if (fActiveRewriteSession != null) {
throw new IllegalStateException();
}
fActiveRewriteSession = session;
}
/**
* {@inheritDoc}
* <p>
* May be extended by subclasses.
* </p>
*/
@Override
public void stopRewriteSession(DocumentRewriteSession session) {
if (fActiveRewriteSession == session) {
flushRewriteSession();
}
}
/**
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
@Override
public void run(IAction action) {
try {
if (!canModifyEditor()) {
return;
}
PyEdit pyEdit = getPyEdit();
PySelection ps = PySelectionFromEditor.createPySelectionFromEditor(pyEdit);
final IDocument doc = ps.getDoc();
if (ps.getStartLineIndex() == ps.getEndLineIndex()) {
organizeImports(pyEdit, doc, null, ps);
} else {
DocumentRewriteSession session = TextSelectionUtils.startWrite(doc);
try {
ps.performSimpleSort(doc, ps.getStartLineIndex(), ps.getEndLineIndex());
} finally {
TextSelectionUtils.endWrite(doc, session);
}
}
} catch (Exception e) {
Log.log(e);
beep(e);
}
}
/**
* {@inheritDoc}
*/
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
try {
ITextSelection selection = WorkbenchUtils.getActiveTextSelection();
IDocument doc = WorkbenchUtils.getActiveDocument();
IEditorInput input = WorkbenchUtils.getActiveInput();
IEditorPart editor = WorkbenchUtils.getActiveEditor(false);
boolean isTextOperationAllowed = (selection != null) && (doc != null)
&& (input != null) && (editor != null)
&& (editor instanceof ModulaEditor);
if (isTextOperationAllowed) {
ITextEditor iTextEditor = (ITextEditor)editor;
final ITextOperationTarget operationTarget = (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class);
String commentPrefix = ((SourceCodeTextEditor)editor).getEOLCommentPrefix();
isTextOperationAllowed = (operationTarget != null)
&& (operationTarget instanceof TextViewer)
&& (validateEditorInputState(iTextEditor))
&& (commentPrefix != null);
if ((isTextOperationAllowed)) {
int startLine = selection.getStartLine();
int endLine = selection.getEndLine();
int selOffset = selection.getOffset();
int selLen = selection.getLength();
int realEndLine = doc.getLineOfOffset(selOffset + selLen); // for selection end at pos=0 (endLine is line before here)
// Are cursor and anchor at 0 positions?
boolean is0pos = false;
if (doc.getLineOffset(startLine) == selOffset) {
if ((doc.getLineOffset(endLine) + doc.getLineLength(endLine) == selOffset + selLen)) {
is0pos = true;
}
}
ArrayList<ReplaceEdit> edits = null;
int offsAfter[] = {0};
if (is0pos || selLen == 0) {
edits = commentWholeLines(startLine, (selLen == 0) ? startLine : endLine, realEndLine, doc, offsAfter);
} else {
edits = commentRange(selOffset, selLen, "(*", "*)", offsAfter); //$NON-NLS-1$ //$NON-NLS-2$
}
if (edits != null && !edits.isEmpty()) {
DocumentRewriteSession drws = null;
try {
if (doc instanceof IDocumentExtension4) {
drws = ((IDocumentExtension4)doc).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
}
MultiTextEdit edit= new MultiTextEdit(0, doc.getLength());
edit.addChildren((TextEdit[]) edits.toArray(new TextEdit[edits.size()]));
edit.apply(doc, TextEdit.CREATE_UNDO);
iTextEditor.getSelectionProvider().setSelection(new TextSelection(offsAfter[0], 0));
}
finally {
if (doc instanceof IDocumentExtension4 && drws != null) {
((IDocumentExtension4)doc).stopRewriteSession(drws);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
* @param document
* @param ast
* @param begPos begin offset of the formatted area (0 to format all)
* @param endPos end offset of the formatted area (doc.getLength() to format all)
*/
public void doFormat(IDocument doc, ModulaAst ast, int begPos, int endPos, boolean indentOnly) throws Exception {
buildChunksModel(doc, ast, doc.getLength());
if (chunks.size() == 0) {
return; // Nothing to do
}
int firstChunkIdx = chunkIdxAtPos(begPos);
int lastChunkIdx = chunkIdxAtPos(endPos-1);
{ // Fix selection margins to include whole chunks:
begPos = chunks.get(firstChunkIdx).getOffsetInDoc();
Chunk c = chunks.get(lastChunkIdx);
endPos = c.getOffsetInDoc() + c.getLengthInDoc();
}
if (lastChunkIdx == chunks.size()-1) {
// chunks[lastChunkIdx+1] should always be some chunk with offset,
// it will be required to build format edits from chunk model
chunks.add(Chunk.createNoPlnChunkFromDoc(doc, doc.getLength(), 0));
}
// lastChunkIdx may be changed with model so use terminalChunk:
Chunk terminalChunk = chunks.get(lastChunkIdx+1);
if (!indentOnly) {
processNewLines(doc, firstChunkIdx, terminalChunk);
}
processWhitespaces(doc, firstChunkIdx, terminalChunk, indentOnly);
if (!indentOnly) {
processWrapLines(doc, firstChunkIdx, terminalChunk);
}
ArrayList<ReplaceEdit> edits = buildEditsFromModel(doc, firstChunkIdx, terminalChunk);
DocumentRewriteSession drws = null;
try {
if (doc instanceof IDocumentExtension4) {
drws = ((IDocumentExtension4)doc).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
}
MultiTextEdit edit= new MultiTextEdit(0, doc.getLength());
edit.addChildren((TextEdit[]) edits.toArray(new TextEdit[edits.size()]));
edit.apply(doc, TextEdit.CREATE_UNDO);
}
finally {
if (doc instanceof IDocumentExtension4 && drws != null) {
((IDocumentExtension4)doc).stopRewriteSession(drws);
}
}
}
public void startRewriteSession(DocumentRewriteSession session) throws IllegalStateException {
if (fActiveRewriteSession != null)
throw new IllegalStateException();
fActiveRewriteSession= session;
}
@Override
public DocumentRewriteSession startRewriteSession(DocumentRewriteSessionType sessionType)
throws IllegalStateException {
throw new RuntimeException("not implemented");
}
@Override
public void stopRewriteSession(DocumentRewriteSession session) {
throw new RuntimeException("not implemented");
}
@Override
public DocumentRewriteSession getActiveRewriteSession() {
throw new RuntimeException("not implemented");
}
/**
* {@inheritDoc}
* <p>
* May be extended by subclasses.
* </p>
*
* @since 2.2
*/
@Override
public void stopRewriteSession(DocumentRewriteSession session) {
if (fActiveRewriteSession == session)
flushRewriteSession();
}
/**
* {@inheritDoc}
* <p>
* May be extended by subclasses.
* </p>
*
* @since 2.2
*/
@Override
public DocumentRewriteSession getActiveRewriteSession() {
return fActiveRewriteSession;
}
/**
* {@inheritDoc}
* <p>
* May be extended by subclasses.
* </p>
*/
public void stopRewriteSession(DocumentRewriteSession session) {
if (fActiveRewriteSession == session)
flushRewriteSession();
}
/**
* {@inheritDoc}
* <p>
* May be extended by subclasses.
* </p>
*/
public DocumentRewriteSession getActiveRewriteSession() {
return fActiveRewriteSession;
}
/**
* {@inheritDoc}
* <p>
* May be extended by subclasses.
* </p>
*/
@Override
public DocumentRewriteSession getActiveRewriteSession() {
return fActiveRewriteSession;
}