下面列出了怎么用org.eclipse.jface.text.ITextSelection的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void run(ITextSelection selection) {
try {
if (!ActionUtil.isEditable(fEditor))
return;
if (fMoveStaticMembersAction.isEnabled() && tryMoveStaticMembers(selection))
return;
if (fMoveInstanceMethodAction.isEnabled() && tryMoveInstanceMethod(selection))
return;
if (tryReorgMove())
return;
MessageDialog.openInformation(getShell(), RefactoringMessages.MoveAction_Move, RefactoringMessages.MoveAction_select);
} catch (JavaModelException e) {
ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
}
}
/**
* Creates a region describing the text block (something that starts at
* the beginning of a line) completely containing the current selection.
*
* @param selection The selection to use
* @param document The document
* @return the region describing the text block comprising the given selection
*/
protected static IRegion getTextBlockFromSelection(ITextSelection selection, IDocument document) {
try {
IRegion line= document.getLineInformationOfOffset(selection.getOffset());
int length= selection.getLength() == 0 ?
line.getLength() :
selection.getLength() + (selection.getOffset() - line.getOffset());
return new Region(line.getOffset(), length);
} catch (BadLocationException x) {
// should not happen
LangCore.logError("Unexpected error.", x);
}
return null;
}
/**
* @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 {
Control text = getTextWidget(editor);
String cmd = ((getDirection() == FORWARD) ? IEmacsPlusCommandDefinitionIds.NEXT_LINE : IEmacsPlusCommandDefinitionIds.PREVIOUS_LINE);
try {
// use widget to avoid unpleasant scrolling side effects of IRewriteTarget
text.setRedraw(false);
for (int i=0; i < blockMovementSize; i++) {
try {
EmacsPlusUtils.executeCommand(cmd, null, editor);
} catch (Exception e) {}
}
} finally {
text.setRedraw(true);
}
return NO_OFFSET;
}
/**
* The initial search string will be the closest full word forward, if it is on the same line
*
* @param document
* @param selection
* @return the initial search string
*
* @throws BadLocationException
*/
protected ITextSelection initText(ITextEditor editor, IDocument document, ITextSelection selection) throws BadLocationException {
ITextSelection result = null;
if (selection != null) {
if (selection.getLength() == 0) {
int line = document.getLineOfOffset(selection.getOffset());
// get the proximate word
try {
ITextSelection tmp = new SexpForwardHandler().getTransSexp(document, selection.getOffset(), true);
// make sure we're still on the same line
if (tmp != null && line == document.getLineOfOffset(tmp.getOffset())) {
selection = tmp;
}
// ignore
} catch (BadLocationException e) {}
}
if (selection != null && selection.getLength() > 0 && selection.getText() != null) {
result = selection;
}
}
return result;
}
@Override
protected void runInternal(ITextSelection selection, IDocumentExtension3 docExtension, Edit.EditFactory factory) throws BadLocationException, BadPartitioningException {
int selectionOffset= selection.getOffset();
int selectionEndOffset= selectionOffset + selection.getLength();
List<Edit> edits= new LinkedList<Edit>();
ITypedRegion partition= docExtension.getPartition(IJavaPartitions.JAVA_PARTITIONING, selectionOffset, false);
handleFirstPartition(partition, edits, factory, selectionOffset);
while (partition.getOffset() + partition.getLength() < selectionEndOffset) {
partition= handleInteriorPartition(partition, edits, factory, docExtension);
}
handleLastPartition(partition, edits, factory, selectionEndOffset);
executeEdits(edits);
}
private void removeLineComments(IDocument document, ITextSelection selection, String comment, ITextEditor editor)
throws BadLocationException {
int lineNumber = selection.getStartLine();
int endLineNumber = selection.getEndLine();
String oldText = document.get();
int deletedChars = 0;
Boolean isStartBeforeComment = false;
while (lineNumber <= endLineNumber) {
int commentOffset = oldText.indexOf(comment, document.getLineOffset(lineNumber) + deletedChars);
document.replace(commentOffset - deletedChars, comment.length(), "");
if (deletedChars == 0) {
isStartBeforeComment = commentOffset > selection.getOffset();
}
if (lineNumber != endLineNumber) {
deletedChars += comment.length();
}
lineNumber++;
}
ITextSelection newSelection = new TextSelection(
selection.getOffset() - (isStartBeforeComment ? 0 : comment.length()),
selection.getLength() - deletedChars);
editor.selectAndReveal(newSelection.getOffset(), newSelection.getLength());
}
private void addLineComments(IDocument document, ITextSelection selection, String comment, ITextEditor editor)
throws BadLocationException {
int lineNumber = selection.getStartLine();
int endLineNumber = selection.getEndLine();
int insertedChars = 0;
while (lineNumber <= endLineNumber) {
document.replace(document.getLineOffset(lineNumber), 0, comment);
if (lineNumber != endLineNumber) {
insertedChars += comment.length();
}
lineNumber++;
}
ITextSelection newSelection = new TextSelection(selection.getOffset() + comment.length(),
selection.getLength() + insertedChars);
editor.selectAndReveal(newSelection.getOffset(), newSelection.getLength());
}
protected void doSelectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
NavigationBarItem item = null;
Iterator iter = ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object o = iter.next();
if (o instanceof NavigationBarItem) {
item = (NavigationBarItem) o;
break;
}
}
setSelection(item, !isActivePart());
ISelectionProvider selectionProvider = getSelectionProvider();
if (selectionProvider == null)
return;
ISelection textSelection = selectionProvider.getSelection();
if (!(textSelection instanceof ITextSelection))
return;
fForcedMarkOccurrencesSelection = textSelection;
updateOccurrenceAnnotations((ITextSelection) textSelection);
}
/**
* Given a selection on a document, computes the lines fully or partially covered by
* <code>selection</code>. A line in the document is considered covered if
* <code>selection</code> comprises any characters on it, including the terminating delimiter.
* <p>Note that the last line in a selection is not considered covered if the selection only
* comprises the line delimiter at its beginning (that is considered part of the second last
* line).
* As a special case, if the selection is empty, a line is considered covered if the caret is
* at any position in the line, including between the delimiter and the start of the line. The
* line containing the delimiter is not considered covered in that case.
* </p>
*
* @param document the document <code>selection</code> refers to
* @param selection a selection on <code>document</code>
* @param viewer the <code>ISourceViewer</code> displaying <code>document</code>
* @return a selection describing the range of lines (partially) covered by
* <code>selection</code>, without any terminating line delimiters
* @throws BadLocationException if the selection is out of bounds (when the underlying document has changed during the call)
*/
private ITextSelection getMovingSelection(IDocument document, ITextSelection selection, ITextViewer viewer) throws BadLocationException {
int low= document.getLineOffset(selection.getStartLine());
int endLine= selection.getEndLine();
int high= document.getLineOffset(endLine) + document.getLineLength(endLine);
// get everything up to last line without its delimiter
String delim= document.getLineDelimiter(endLine);
if (delim != null)
high -= delim.length();
// the new selection will cover the entire lines being moved, except for the last line's
// delimiter. The exception to this rule is an empty last line, which will stay covered
// including its delimiter
if (delim != null && document.getLineLength(endLine) == delim.length())
fAddDelimiter= true;
else
fAddDelimiter= false;
return new TextSelection(document, low, high - low);
}
@Override
public IRenameElementContext createLocalRenameElementContext(EObject targetElement, XtextEditor editor,
ITextSelection selection, XtextResource resource) {
EObject declarationTarget = getDeclarationTarget(targetElement);
if (declarationTarget instanceof XtendFunction && ((XtendFunction) declarationTarget).isDispatch()) {
IProject project = projectUtil.getProject(declarationTarget.eResource().getURI());
ResourceSet resourceSet = resourceSetProvider.get(project);
XtendFunction relaodedDispatchFunction = (XtendFunction) resourceSet.getEObject(
EcoreUtil2.getPlatformResourceOrNormalizedURI(declarationTarget), true);
Iterable<JvmOperation> allDispatchOperations = dispatchRenameSupport
.getAllDispatchOperations(relaodedDispatchFunction);
Map<URI, IJavaElement> jvm2javaElement = newLinkedHashMap();
for (JvmOperation jvmOperation : allDispatchOperations) {
IJavaElement javaElement = getJavaElementFinder().findExactElementFor(jvmOperation);
if (javaElement != null) {
URI jvmOperationURI = EcoreUtil.getURI(jvmOperation);
jvm2javaElement.put(jvmOperationURI, javaElement);
}
}
if (!jvm2javaElement.isEmpty()) {
return new DispatchMethodRenameContext(relaodedDispatchFunction, jvm2javaElement, editor, selection,
resource);
}
}
return super.createLocalRenameElementContext(targetElement, editor, selection, resource);
}
/**
* @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 {
IRegion reg = document.getLineInformationOfOffset(currentSelection.getOffset());
String lineTxt = document.get(reg.getOffset(),reg.getLength());
// Check if the line already contains a eol comment
int pos = lineTxt.lastIndexOf(COMMENT_MARKER);
if (pos < 0) {
pos = reg.getOffset() + reg.getLength();
document.replace(pos, 0, LINE_COMMENT);
return pos + LINE_COMMENT.length();
} else {
// If it already exists, position cursor at the comment
return pos
+ COMMENT_MARKER.length()
+ reg.getOffset()
+ (lineTxt.substring(pos).matches(COMMENT_REGEX) ? 1 : 0);
}
}
@Override
public void run(ITextSelection selection) {
if (!ActionUtil.isEditable(fEditor))
return;
IJavaElement element= SelectionConverter.getInput(fEditor);
IJavaElement[] array= new IJavaElement[] {element};
try {
if (element != null && RefactoringAvailabilityTester.isInferTypeArgumentsAvailable(array)){
RefactoringExecutionStarter.startInferTypeArgumentsRefactoring(array, getShell());
} else {
MessageDialog.openInformation(getShell(), RefactoringMessages.OpenRefactoringWizardAction_unavailable, RefactoringMessages.InferTypeArgumentsAction_unavailable);
}
} catch (JavaModelException e) {
ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
}
}
/**
* Prime the minibuffer with the supplied text (which must be guaranteed to be present and selected in the buffer)
*
* @param selection
*/
public void initMinibufferSelection(ITextSelection selection){
if (selection != null && selection.getLength() > 0) {
String text = selection.getText();
saveState();
try {
// temporarily disable selection changed
setSearching(true);
MarkUtils.setSelection(getEditor(),selection);
} finally {
setSearching(false);
}
initMinibuffer(text);
checkCasePos(text);
addToHistory();
// force start (for history searches) to beginning of text rather than cursor
setStartOffset(getTextWidget().getSelectionRange().x);
setFound(true);
}
}
/**
* @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 {
fileCompletions = null;
if (!KbdMacroSupport.getInstance().isDefining() && !KbdMacroSupport.getInstance().isExecuting()) {
String macroName = event.getParameter(NAME_ARG);
boolean forceIt = (event.getParameter(FORCE_ARG) != null ? Boolean.valueOf(event.getParameter(FORCE_ARG)) : false);
if (macroName != null && macroName.length() > 0) {
File file = macroFile(macroName);
if (file.exists()) {
loadMacro(editor,macroName,file,forceIt);
} else {
asyncShowMessage(editor, String.format(MACRO_MISSING, macroName), true);
}
} else {
mbState = this.nameState();
return mbState.run(editor);
}
} else {
asyncShowMessage(editor, BAD_MACRO_STATE, true);
}
return NO_OFFSET;
}
/**
* @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 doTransform(ITextEditor editor, IDocument document,
ITextSelection currentSelection)
throws BadLocationException {
int result = NO_OFFSET;
result = updateRectangle(editor, document, getImpliedSelection(editor,currentSelection), null, false);
return result;
}
/**
* @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 {
return NO_OFFSET;
}
/**
* Synchronizes outline view selection with editor selection, using the given editor selection
*/
private void synchronizeOutlineWithEditor(ISelection selection) {
if (selection.isEmpty()) {
return;
}
if (selection instanceof ITextSelection) {
ITextSelection textSelection = (ITextSelection) selection;
selectInTheOutlineTree(textSelection.getOffset());
editor.setFocus();
}
}
/**
* @see com.mulgasoft.emacsplus.commands.SexpBaseForwardHandler#consoleDispatch(TextConsoleViewer, IConsoleView, ExecutionEvent)
*/
public Object consoleDispatch(final TextConsoleViewer viewer, final IConsoleView activePart, ExecutionEvent event) {
IDocument doc = viewer.getDocument();
ITextSelection currentSelection = (ITextSelection) viewer.getSelectionProvider().getSelection();
ITextSelection selection = downList(doc, currentSelection);
if (selection == null) {
unbalanced(activePart,false);
} else {
endTransform(viewer,selection.getOffset() + selection.getLength(), currentSelection, selection);
}
return null;
}
/**
* Run to the first char (other than whitespaces) or to the real first char.
*/
@Override
public void run(IAction action) {
try {
ITextEditor textEditor = getTextEditor();
IDocument doc = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
ITextSelection selection = (ITextSelection) textEditor.getSelectionProvider().getSelection();
perform(doc, selection);
} catch (Exception e) {
beep(e);
}
}
/**
* @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 {
boolean named = isUniversalPresent();
if (KbdMacroSupport.getInstance().hasKbdMacro(named) && !KbdMacroSupport.getInstance().isBusy()) {
mbState = (named ? nameState() : bindState(null));
return mbState.run(editor);
} else {
asyncShowMessage(editor, NO_MACRO_ERROR, true);
}
return NO_OFFSET;
}
public boolean canToggleLineBreakpoints( IWorkbenchPart part,
ISelection selection )
{
DecoratedScriptEditor textEditor = getEditor( part );
if ( textEditor != null )
{
String script = textEditor.getScript( );
if ( script == null || script.trim( ).length( ) == 0 )
{
return false;
}
ITextSelection textSelection = (ITextSelection) selection;
IReportScriptLocation location = (IReportScriptLocation) textEditor.getAdapter( IReportScriptLocation.class );
if ( location != null )
{
int lineNumber = textSelection.getStartLine( );
if ( location.getLineNumber( ) > 0 )
{
lineNumber = location.getLineNumber( );
}
return JsUtil.checkBreakable( script, lineNumber );
}
}
return false;
}
@Override
public void run(ITextSelection selection) {
ICompilationUnit input= SelectionConverter.getInputAsCompilationUnit(fEditor);
if (!ActionUtil.isEditable(fEditor))
return;
RefactoringExecutionStarter.startInlineTempRefactoring(input, null, selection, getShell());
}
private void copyToClipboard(ITextSelection selection, int repeatCount) {
try{
fClipboard.setContents(new String[] { selection.getText() }, new Transfer[] { TextTransfer.getInstance() });
} catch (SWTError e) {
if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD || repeatCount >= MAX_REPEAT_COUNT)
throw e;
if (MessageDialog.openQuestion(getShell(), InfoViewMessages.CopyToClipboard_error_title, InfoViewMessages.CopyToClipboard_error_message))
copyToClipboard(selection, repeatCount + 1);
}
}
/**
* This method is used to update the enablement state. This has the
* effect of graying out any menu items for the
* command if the handler is disabled. Through experimentation, this method seems to be
* called just before such menu items are rendered in the UI and
* just before the handler is executed.
*/
public void setEnabled(Object context)
{
TLAEditor editor = EditorUtil.getTLAEditorWithFocus();
if (editor != null)
{
if (editor.getProofStructureProvider() != null)
{
setBaseEnabled(editor.getProofStructureProvider().canRunFoldOperation(
IProofFoldCommandIds.FOCUS_ON_STEP,
(ITextSelection) editor.getSelectionProvider().getSelection()));
}
}
}
/**
* Computes the region of the skipped line given the text block to be moved. If
* <code>fUpwards</code> is <code>true</code>, the line above <code>selection</code>
* is selected, otherwise the line below.
*
* @param document the document <code>selection</code> refers to
* @param selection the selection on <code>document</code> that will be moved.
* @return the region comprising the line that <code>selection</code> will be moved over, without its terminating delimiter.
*/
private ITextSelection getSkippedLine(IDocument document, ITextSelection selection) {
int skippedLineN= (fUpwards ? selection.getStartLine() - 1 : selection.getEndLine() + 1);
if (skippedLineN > document.getNumberOfLines() || (!fCopy && (skippedLineN < 0 || skippedLineN == document.getNumberOfLines())))
return null;
try {
if (fCopy && skippedLineN == -1)
skippedLineN= 0;
IRegion line= document.getLineInformation(skippedLineN);
return new TextSelection(document, line.getOffset(), line.getLength());
} catch (BadLocationException e) {
// only happens on concurrent modifications
return null;
}
}
public void textSelectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (selection instanceof ITextSelection && !selection.isEmpty()) {
ITextSelection textSelection = (ITextSelection) selection;
int offset = textSelection.getOffset();
IFigure figureToBeSelected = findFigureForTextOffset(view.getContents(), offset, null);
if (figureToBeSelected != null) {
selectFigure(figureToBeSelected);
view.reveal(figureToBeSelected);
}
}
}
/**
* Fetches the text selection from the active text editor.
*
* @return the text selection or <code>null</code>, when there is no active
* editor or it is not a text editor
*/
public static ITextSelection getActiveTextSelection() {
IEditorPart editor = getActiveEditor(true);
if (editor instanceof ITextEditor) {
ISelection selection = ((ITextEditor) editor)
.getSelectionProvider().getSelection();
if (selection instanceof ITextSelection) {
return (ITextSelection) selection;
}
}
return null;
}
protected boolean isValidSelection(IWorkbenchPartSelection workbenchPartSelection) {
return !this.equals(workbenchPartSelection.getWorkbenchPart())
&& workbenchPartSelection.getWorkbenchPart() instanceof XtextEditor
&& workbenchPartSelection.getSelection() instanceof ITextSelection
&& ((XtextEditor) workbenchPartSelection.getWorkbenchPart()).getLanguageName().equalsIgnoreCase(
languageName);
}
/**
* @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;
}
/**
* Returns the editor's selection, or <code>null</code> if no selection can be obtained or the
* editor is <code>null</code>.
*
* @return the selection of the action's editor, or <code>null</code>
*/
protected ITextSelection getCurrentSelection() {
ITextEditor editor= getTextEditor();
if (editor != null) {
ISelectionProvider provider= editor.getSelectionProvider();
if (provider != null) {
ISelection selection= provider.getSelection();
if (selection instanceof ITextSelection)
return (ITextSelection) selection;
}
}
return null;
}