下面列出了org.eclipse.ui.IPartListener#org.eclipse.ui.texteditor.ITextEditor 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void createContributionItems(IServiceLocator serviceLocator, IContributionRoot additions) {
ITextEditor editor = (ITextEditor)
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
IVerticalRulerInfo rulerInfo = editor.getAdapter(IVerticalRulerInfo.class);
try {
List<IMarker> markers = getMarkers(editor, rulerInfo);
additions.addContributionItem(new ReviewMarkerMenuContribution(editor, markers), null);
if (!markers.isEmpty()) {
additions.addContributionItem(new Separator(), null);
}
} catch (CoreException e) {
AppraiseUiPlugin.logError("Error creating marker context menus", e);
}
}
@Test
public void testDTDFile() throws Exception {
final IFile file = project.getFile("blah.dtd");
file.create(new ByteArrayInputStream("FAIL".getBytes()), true, null);
ITextEditor editor = (ITextEditor) IDE
.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file);
editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("<!--<!-- -->");
assertTrue("Diagnostic not published", new DisplayHelper() {
@Override
protected boolean condition() {
try {
return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0;
} catch (CoreException e) {
return false;
}
}
}.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000));
}
/**
* @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(ITextEditor, IDocument, ITextSelection, ExecutionEvent)
*/
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection, ExecutionEvent event)
throws BadLocationException {
prefix = INITIAL_PREFIX; //reset in case of M-x invocation
UniversalMinibuffer mini = new UniversalMinibuffer(this);
Object eTrigger = event.getTrigger();
if (eTrigger instanceof Event) {
Event ev = (Event)eTrigger;
prefix = mini.getTrigger(ev.keyCode,ev.stateMask);
}
if (KbdMacroSupport.getInstance().isExecuting()) {
// call without asynchronous wrapper
// TODO: with ^U, key sequences (instead of commands) appear in kbd macro
return bufferTransform(mini, editor, event);
} else {
return miniTransform(mini, editor, event);
}
}
/**
* @see com.mulgasoft.emacsplus.minibuffer.IMinibufferExecutable#executeResult(ITextEditor, java.lang.Object)
*/
public boolean doExecuteResult(ITextEditor editor, Object minibufferResult) {
if (minibufferResult != null) {
EmacsPlusConsole console = EmacsPlusConsole.getInstance();
console.clear();
console.activate();
ICommandResult commandR = (ICommandResult) minibufferResult;
String name = commandR.getName();
Command cmd = commandR.getCommand();
console.printBold(name + CR);
printCmdDetails(cmd, console);
}
return true;
}
@Override
public void showMatch(Match match, int offset, int length, boolean activate) throws PartInitException {
IEditorPart editor= fEditorOpener.openMatch(match);
if (editor != null && activate)
editor.getEditorSite().getPage().activate(editor);
Object element= match.getElement();
if (editor instanceof ITextEditor) {
ITextEditor textEditor= (ITextEditor) editor;
textEditor.selectAndReveal(offset, length);
} else if (editor != null) {
if (element instanceof IFile) {
IFile file= (IFile) element;
showWithMarker(editor, file, offset, length);
}
} else if (getInput() instanceof JavaSearchResult) {
JavaSearchResult result= (JavaSearchResult) getInput();
IMatchPresentation participant= result.getSearchParticpant(element);
if (participant != null)
participant.showMatch(match, offset, length, activate);
}
}
/**
* Builds the ITextEditor mock.
*
* @return the ITextEditor mock
* @see #withLineOffsetLookupAnswer(int, int)
*/
private ITextEditor build() {
IDocument document = documentBuilder.build();
IEditorInput editorInput = EasyMock.createNiceMock(IEditorInput.class);
EasyMock.replay(editorInput);
IDocumentProvider documentProvider = EasyMock.createNiceMock(IDocumentProvider.class);
EasyMock.expect(documentProvider.getDocument(editorInput)).andReturn(document).anyTimes();
EasyMock.replay(documentProvider);
editor = EasyMock.createNiceMock(ITextEditor.class);
EasyMock.expect(editor.getDocumentProvider()).andReturn(documentProvider).anyTimes();
EasyMock.expect(editor.getEditorInput()).andReturn(editorInput).anyTimes();
EasyMock.replay(editor);
return editor;
}
public void contributeToStatusLine(IStatusLineManager statusLineManager)
{
if (this.activeEditor instanceof ITextEditor)
{
if (statusLineManager.find(cursorPositionStatusField.getId()) == null)
{
// add the cursor position if not already there
statusLineManager.add(cursorPositionStatusField);
}
} else
{
// remove cursor position if the active editor is not a text editor
statusLineManager.remove(cursorPositionStatusField);
}
// must update to show changes in UI
statusLineManager.update(true);
}
/**
* @see com.mulgasoft.emacsplus.minibuffer.IMinibufferExecutable#executeResult(org.eclipse.ui.texteditor.ITextEditor, java.lang.Object)
*/
public boolean executeResult(ITextEditor editor, Object minibufferResult) {
String summary = EMPTY_STR;
if (minibufferResult != null) {
IBindingResult bindingR = (IBindingResult) minibufferResult;
String name = bindingR.getKeyString();
if (bindingR == null || bindingR.getKeyBinding() == null) {
summary = String.format(CMD_NO_RESULT, name) + CMD_NO_BINDING;
} else {
summary = String.format(CMD_KEY_RESULT,name);
Binding binding = bindingR.getKeyBinding();
try {
Command com = getCommand(binding);
if (com != null) {
summary += normalizeCommandName(com.getName());
}
} catch (NotDefinedException e) {
// can't happen as the Command will be null or valid
}
}
}
showResultMessage(editor, summary, false);
return true;
}
/**
* Wrap selection provider setSelection within a block disabling highlight
* range to protect against the JavaEditor from changing the narrow focus in
* - org.eclipse.jdt.internal.ui.javaeditor.TogglePresentationAction -
*
* @param editor
* @param selection
* in model coords
*/
public static ITextSelection setSelection(ITextEditor editor, ITextSelection selection) {
boolean isNarrow = editor.showsHighlightRangeOnly();
// Use the text widget, as the IRewriteTarget has unpleasant scrolling side effects
Control text = getTextWidget(editor);
try {
text.setRedraw(false);
if (isNarrow) {
editor.showHighlightRangeOnly(false);
}
editor.getSelectionProvider().setSelection(selection);
} finally {
if (isNarrow) {
editor.showHighlightRangeOnly(isNarrow);
}
text.setRedraw(true);
}
return selection;
}
public boolean executeResult(ITextEditor editor, Object minibufferResult, ExecutingMinibuffer mini) {
boolean result = false;
AlignMinibuffer am = (AlignMinibuffer)mini;
String number = (String)minibufferResult;
if (number != null && number.length() > 0) {
try {
AlignControl ac = am.getAlignControl();
ac.group = EmacsPlusUtils.emacsParseInt(number);
// am.addToHistory(Integer.toString(ac.group)); // add to command history
am.addToHistory(ac.group); // add to command history
am.setExecuteState(sSpaces); // next state
} catch (NumberFormatException e) {
am.setResultMessage(String.format(BAD_NUMBER,number), true, true);
am.setAlignControl(null); // clear and
result = true; // flag for exit
}
}
return result;
}
@Test public void testCloseEditorAndDiscardWorkingCopy() throws InterruptedException {
waitForEvent(new Procedure0() {
@Override
public void apply() {
try {
compilationUnit.discardWorkingCopy();
((ITextEditor) editor).close(false);
} catch (JavaModelException e) {
throw new RuntimeException(e);
}
}
}, false);
assertNull(event);
}
@Test
public void testMultipleDocumentChanges() throws Exception {
ITextEditor editor = openInEditor(file0);
CompositeChange compositeChange = new CompositeChange("test");
compositeChange.add(createEditorDocumentChange(editor, 1, 1, "foo"));
compositeChange.add(createEditorDocumentChange(editor, 2, 1, "bar"));
CompositeChange compositeChange1 = new CompositeChange("test");
compositeChange.add(compositeChange1);
compositeChange1.add(createEditorDocumentChange(editor, 3, 1, "baz"));
compositeChange1.add(createEditorDocumentChange(editor, 2, 1, "bar"));
compositeChange1.add(createMultiEditorDocumentChange(editor, 1, 1, "foo", 4, 1, "foo"));
Change combined = combiner.combineChanges(compositeChange);
assertTrue(combined instanceof CompositeChange);
assertEquals(1, ((CompositeChange) combined).getChildren().length);
assertTrue(((CompositeChange)combined).getChildren()[0] instanceof EditorDocumentChange);
Change undo = combined.perform(new NullProgressMonitor());
IDocument document = getDocument(editor);
assertEquals(MODEL.replace("1234", "foobarbazfoo"), document.get());
undo.perform(new NullProgressMonitor());
assertEquals(MODEL, document.get());
}
public PartListenerGroup(ITextEditor editorPart) {
fPart= editorPart;
fCurrentJob= null;
fAstListeners= new ListenerList(ListenerList.IDENTITY);
fSelectionListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection= event.getSelection();
if (selection instanceof ITextSelection) {
fireSelectionChanged((ITextSelection) selection);
}
}
};
fPostSelectionListener= new ISelectionListener() {
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (part == fPart && selection instanceof ITextSelection)
firePostSelectionChanged((ITextSelection) selection);
}
};
}
/**
* Store text in history and invoke the executable command
*
* @see com.mulgasoft.emacsplus.minibuffer.ExecutingMinibuffer#executeResult(org.eclipse.ui.texteditor.ITextEditor, java.lang.Object)
*/
@Override
protected boolean executeResult(ITextEditor editor, Object commandResult) {
boolean result = true;
String text = (String)commandResult;
if (text != null) {
// skip history on erase replace
if (text.length() > 0) {
addToHistory(text); // add to command history
}
result = super.executeResult(editor, commandResult);
}
return result;
}
/**
* @param editor
* @param start
* - in model coords
* @param length
* - in model coords
*/
public static ITextSelection setSelection(ITextEditor editor, int start, int length) {
TextViewer tv = findTextViewer(editor);
ITextSelection selection = new TextSelection(null, start, length);
if (tv != null) {
tv.setSelection(selection, false);
} else {
setSelection(editor, selection);
}
return selection;
}
/**
* @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(org.eclipse.ui.texteditor.ITextEditor,
* org.eclipse.jface.text.IDocument, org.eclipse.jface.text.ITextSelection,
* org.eclipse.core.commands.ExecutionEvent)
*/
@Override
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection,
ExecutionEvent event) throws BadLocationException {
mbState = variableSetState();
mbState.run(editor);
return NO_OFFSET;
}
@Override
public void setActiveEditor(IEditorPart part)
{
super.setActiveEditor(part);
if (part instanceof ITextEditor)
{
ITextEditor editor = (ITextEditor) part;
fOpenDeclaration.setAction(getAction(editor, IJSActions.OPEN_DECLARATION));
}
}
/**
* @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(ITextEditor, IDocument,
* ITextSelection, ExecutionEvent)
*/
@Override
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection,
ExecutionEvent event) throws BadLocationException {
int uArg = getUniversalCount();
int offset = getCursorOffset(editor, currentSelection);
int offsetLine = document.getLineOfOffset(offset);
if (uArg == 1) {
try {
// gnu emacs: If the variable `kill-whole-line' is non-`nil', `C-k' at the very
// beginning of a line kills the entire line including the following newline.
boolean killWhole = isKillWholeLine() && (offset == document.getLineOffset(offsetLine));
executeCommand(killWhole ? CUT_LINE : CUT_LINE_TO_END, null, editor);
} catch (Exception e) {}
} else {
try {
// flag us as a kill command
KillRing.getInstance().setKill(IEmacsPlusCommandDefinitionIds.KILL_LINE, false);
int lastOffset = offset;
// note that line numbers start from 0
int maxLine = document.getNumberOfLines() - 1;
int endLine = uArg + document.getLineOfOffset(offset);
// if range includes eof
if (endLine >= maxLine) {
// delete through to last character
lastOffset = document.getLineOffset(maxLine) + document.getLineLength(maxLine);
} else {
// delete by whole lines
lastOffset = document.getLineOffset(Math.min(Math.max(endLine, 0), maxLine));
}
updateText(document, ((lastOffset >= offset ? offset : lastOffset)), Math.abs(lastOffset - offset),
EMPTY_STR);
} finally {
// clear kill command flag
KillRing.getInstance().setKill(null, false);
}
}
return NO_OFFSET;
}
/**
* Gets the source page editor.
*
* @return the source page editor
*/
public ITextEditor getSourcePageEditor() {
if (getCurrentPage() == sourceIndex) {
return sourceTextEditor;
} else
return null;
}
/************ For testing ****************/
public void handleActivate(IEditorPart epart) {
if (epart instanceof ITextEditor) {
handleNarrowActivate((ITextEditor)epart);
}
}
/**
* Create the Runnable for executing a command (which may be a named/bound kbd macro)
*
* @param event
* @param editor
* @param vkf
* @return the Runnable
*/
private Runnable getCmdRunner(KbdEvent event, final ITextEditor editor, final KbdLock vkf) {
final String cmdId = event.getCmd();
@SuppressWarnings("unchecked")
final Map<String,?> parameters = (Map<String,?>) event.getCmdParameters();
final KbdMacroExecuteHandler executeHandler = this;
return new Runnable() {
public void run() {
if (executeHandler.isInterrupted()) {
return;
}
try {
ITextEditor current = EmacsPlusUtils.getCurrentEditor();
if (parameters != null) {
KbdMacroExecuteHandler.this.executeCommand(cmdId, parameters, null,
(current != null ? current : editor));
} else {
KbdMacroExecuteHandler.this.executeCommand(cmdId, null,
(current != null ? current : editor));
}
} catch (Exception e) {
if (isMacro(cmdId)) {
notifyKbdListener(cmdId);
}
}
}
};
}
public OpenViewActionGroup(ITextEditor part) {
if (part instanceof ModulaEditor) {
openDeclarationAction = new OpenDeclarationsAction((ModulaEditor) part);
openDeclarationAction.setActionDefinitionId(IModulaEditorActionDefinitionIds.OPEN_DECL);
part.setAction(OpenDeclarationsAction.ID, openDeclarationAction); //$NON-NLS-1$
}
}
protected int getParagraphOffset(ITextEditor editor, IDocument document, ITextSelection selection) {
int result = NO_OFFSET;
// if we're not at buffer top (or top of narrowed region)
if (!isAtTop(editor,selection)) {
try {
result = getParagraphOffset(editor,false);
} catch (IndexOutOfBoundsException e) {
// work around bug in org.eclipse.jface.text.TextViewer.findAndSelect()
// where it doesn't check for 0 offset & 0 length
result = 0;
}
}
return result;
}
/**
* @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(ITextEditor, IDocument, ITextSelection, ExecutionEvent)
*/
@Override
protected int transform(final ITextEditor editor, IDocument document, ITextSelection currentSelection,
final ExecutionEvent event) throws BadLocationException {
return bufferTransform(new SearchReplaceMinibuffer(true,true), editor, event);
}
protected boolean validateEditorInputState(ITextEditor editor) {
if (editor instanceof ITextEditorExtension2)
return ((ITextEditorExtension2) editor).validateEditorInputState();
else if (editor instanceof ITextEditorExtension)
return !((ITextEditorExtension) editor).isEditorInputReadOnly();
else if (editor != null)
return editor.isEditable();
else
return false;
}
@Override
public void createContributionItems(IServiceLocator serviceLocator, IContributionRoot additions) {
ITextEditor editor = (ITextEditor)
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
additions.addContributionItem(new TextEditorContextMenuContribution(editor), null);
}
/**
* Verify that the editor in the location is still in use
*
* @param location
* @return true if editor is valid
*/
private boolean checkEditor(IBufferLocation location) {
boolean result = false;
if (location != null) {
ITextEditor editor = location.getEditor();
if (editor != null) {
IEditorInput input = editor.getEditorInput();
// check all the editor references that match the input for a match
IEditorReference[] refs = EmacsPlusUtils.getWorkbenchPage().findEditors(input,null, IWorkbenchPage.MATCH_INPUT);
for (int i=0; i< refs.length; i++) {
IEditorPart ed = refs[i].getEditor(false);
// multi page annoyance
if (ed instanceof MultiPageEditorPart) {
IEditorPart[] eds = ((MultiPageEditorPart)ed).findEditors(input);
for (int j=0; j < eds.length; j++) {
if (eds[i] == editor) {
result = true;
break;
}
}
if (result) {
break;
}
} else {
if (ed == editor) {
result = true;
break;
}
}
}
}
}
return result;
}
void executeUniversal(ITextEditor editor, String id, Event event, int count, boolean isNumeric)
throws NotDefinedException, ExecutionException, CommandException {
String did = null;
if ((did = getInternalCmd(id)) != null) {
// Emacs+ internal commands should support +- universal-argument
EmacsPlusUtils.executeCommand(did, count, event, editor);
} else if (count != 1 && (isUniversalCmd(id) || (alwaysUniversal && !id.startsWith(EmacsPlusUtils.MULGASOFT)))) {
// only non-Emacs+ commands should be invoked here
executeWithDispatch(editor, getUniversalCmd(id), count);
} else {
executeCommand(id, event, editor);
}
}
/**
* Returns the line base selection values for the given editor part.
*
* <p>The given editor part must not be <code>null</code>.
*
* @param editorPart the editorPart for which to get the text selection
* @return the line base selection values for the given editor part or {@link
* TextSelection#EMPTY_SELECTION} if the given editor part is is <code>null</code> or not a
* text editor, the editor does not have a valid selection provider or document provider, a
* valid IDocument could not be obtained form the document provider, or the correct line
* numbers or in-lin offsets could not be calculated
*/
public static TextSelection getSelection(IEditorPart editorPart) {
if (!(editorPart instanceof ITextEditor)) {
return TextSelection.EMPTY_SELECTION;
}
ITextEditor textEditor = (ITextEditor) editorPart;
ISelectionProvider selectionProvider = textEditor.getSelectionProvider();
if (selectionProvider == null) {
return TextSelection.EMPTY_SELECTION;
}
IDocumentProvider documentProvider = textEditor.getDocumentProvider();
if (documentProvider == null) {
return TextSelection.EMPTY_SELECTION;
}
IDocument document = documentProvider.getDocument(editorPart.getEditorInput());
if (document == null) {
return TextSelection.EMPTY_SELECTION;
}
ITextSelection textSelection = (ITextSelection) selectionProvider.getSelection();
int offset = textSelection.getOffset();
int length = textSelection.getLength();
return calculateSelection(document, offset, length);
}
/**
* Set up working set scope, if present, else workspace
*
* @see com.mulgasoft.emacsplus.commands.TagsSearchHandler#getInputObject(org.eclipse.ui.texteditor.ITextEditor)
*/
protected FileTextSearchScope getInputObject(ITextEditor editor) {
IWorkingSet set = (wset != null ? wset : getWorkingSet(editor));
if (set != null) {
return FileTextSearchScope.newSearchScope(new IWorkingSet[] { set }, new String[0], false);
} else {
return super.getInputObject(editor);
}
}