下面列出了怎么用org.eclipse.jface.text.IFindReplaceTarget的API类实例代码及写法,或者点击链接到github查看源代码。
public static void findPrevious(IEditorPart editorPart) {
IFindReplaceTarget target = (IFindReplaceTarget) editorPart.getAdapter(IFindReplaceTarget.class);
if (target == null)
return;
StatusLine statusLine = new StatusLine(editorPart.getEditorSite());
statusLine.cleanStatusLine();
SearchRegion region = getSearchRegion(target, editorPart);
if (region == null)
return;
int offset = Math.max(region.offset - 1, 0);
offset = findAndSelect(target, offset, region.text, false);
if (offset < 0) {
String message = String.format(Messages.QuickFind_Status_FirstOccurence, region.text);
statusLine.showMessage(message, ImageUtils.getImage(ImageUtils.FIND_STATUS));
}
}
public static void findNext(IEditorPart editorPart) {
IFindReplaceTarget target = (IFindReplaceTarget) editorPart.getAdapter(IFindReplaceTarget.class);
if (target == null)
return;
StatusLine statusLine = new StatusLine(editorPart.getEditorSite());
statusLine.cleanStatusLine();
SearchRegion region = getSearchRegion(target, editorPart);
if (region == null)
return;
int offset = region.offset + region.length;
offset = findAndSelect(target, offset, region.text, true);
if (offset < 0) {
String message = String.format(Messages.QuickFind_Status_LastOccurence, region.text);
statusLine.showMessage(message, ImageUtils.getImage(ImageUtils.FIND_STATUS));
}
}
/**
* Searches for a string starting at the given offset and using the specified search
* directives. If a string has been found it is selected and its start offset is
* returned.
*
* @param target the target for finding string
* @param offset the offset at which searching starts
* @param findString the string which should be found
* @param forwardSearch the direction of the search
* @return the position of the specified string, or -1 if the string has not been found
*/
private static int findAndSelect( IFindReplaceTarget target
, int offset, String findString
, boolean forwardSearch )
{
boolean caseSensitive = true;
boolean wholeWord = XFindUtils.isWord(findString);
boolean regExSearch = false;
try {
if (target instanceof IFindReplaceTargetExtension3) {
return ((IFindReplaceTargetExtension3)target).findAndSelect(
offset, findString, forwardSearch, caseSensitive, wholeWord, regExSearch
);
}
return target.findAndSelect(
offset, findString, forwardSearch, caseSensitive, wholeWord
);
} catch (Exception e){
return -1;
}
}
public void open()
{
try
{
final IFileStore store = EFS.getStore(document);
// Now open an editor to this file (and highlight the occurrence if possible)
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IEditorPart part = IDE.openEditorOnFileStore(page, store);
// Now select the occurrence if we can
IFindReplaceTarget target = (IFindReplaceTarget) part.getAdapter(IFindReplaceTarget.class);
if (target != null && target.canPerformFind())
{
target.findAndSelect(0, searchString, true, caseSensitive, wholeWord);
}
}
catch (Exception e)
{
IdeLog.logError(CommonEditorPlugin.getDefault(), e);
}
}
/**
* Find the next occurrence of empty line(s)
* Will match all valid lines except single ^$
*
* @param editor
* @param forward true if moving forward
* @return -1 if not found, else offset of match in widget coords
*/
protected int findNext(ITextEditor editor, boolean forward) {
IFindReplaceTarget frt = getTarget(editor);
Point selection = frt.getSelection();
// don't move past eob
int offset = Math.min(MarkUtils.getCharCount(editor), Math.max(0,MarkUtils.getCaretOffset(editor) + (forward ? 1 : -2)));
int result = ((IFindReplaceTargetExtension3)frt).findAndSelect(offset, PARAGRAPH_START, forward, false, false, true);
if (result != -1) {
if ((forward && offset > result) || (!forward && offset < result)) {
// reset if we've wrapped around in the search
MarkUtils.setWidgetSelection(editor, selection.x, selection.x + selection.y);
result = -1;
}
}
return result;
}
/**
* Refine target search to not proceed beyond a region limit, if present
*
* @see com.mulgasoft.emacsplus.minibuffer.SearchMinibuffer#findTarget(org.eclipse.jface.text.IFindReplaceTarget, java.lang.String, int, boolean)
*/
protected int findTarget(IFindReplaceTarget target, String searchStr, int searchIndex, boolean forward) {
int result = WRAP_INDEX;
StyledText text = getTextWidget();
try {
text.setRedraw(false);
result = super.findTarget(target,searchStr,searchIndex,forward);
// if present, check if we've gone past the end of the region
if (getLimit() != WRAP_INDEX && result != WRAP_INDEX) {
int pos = MarkUtils.widget2ModelOffset(getViewer(), result);
// include length of search result in check
if (pos + target.getSelection().y > getLimit()) {
result = WRAP_INDEX;
// restore last position the region
setSelection(searchIndex);
}
}
} finally {
text.setRedraw(true);
}
return result;
}
private static SearchRegion getSearchRegion(IFindReplaceTarget target, IEditorPart editorPart)
{
SearchRegion searchRegion = null;
String text = target.getSelectionText();
Point range = target.getSelection();
if (range.y > 0) {
searchRegion = new SearchRegion(text, range.x, range.y);
}
else if (editorPart instanceof ITextEditor) {
ISelection selection = ((ITextEditor) editorPart).getSelectionProvider().getSelection();
if (selection instanceof ITextSelection) {
int offset = ((ITextSelection)selection).getOffset();
IDocumentProvider provider = ((ITextEditor) editorPart).getDocumentProvider();
IEditorInput input = editorPart.getEditorInput();
if ((provider != null) && (input != null)) {
IDocument document = provider.getDocument(input);
if (document != null) {
searchRegion = getSearchRegion(document, offset);
if (searchRegion != null) {
// ITextSelection textSelection = new TextSelection(
// document, searchRegion.offset, searchRegion.length
// );
// ((ITextEditor) editorPart).getSelectionProvider().setSelection(textSelection);
searchRegion = new SearchRegion(
searchRegion.text,
searchRegion.offset + (range.x - offset),
searchRegion.length
);
}
}
}
}
}
return searchRegion;
}
/**
* makes shure that the correct find/replace target is returned.
* the actual viewer is returned if an adapter of type
* FindReplaceTarget is searched
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object getAdapter(Class adapter) {
Object object = super.getAdapter(adapter);
if(object != null) {
return object;
}
if(adapter.equals(IFindReplaceTarget.class)) {
return viewer.getActualViewer().getFindReplaceTarget();
}
return null;
}
void resetScope()
{
scope = null;
IFindReplaceTarget findReplaceTarget = (IFindReplaceTarget) textEditor.getAdapter(IFindReplaceTarget.class);
if (findReplaceTarget instanceof IFindReplaceTargetExtension)
{
((IFindReplaceTargetExtension) findReplaceTarget).endSession();
}
}
/**
* Case-based replacement - after the initial find has already happened
*
* @param replacer - the replacement string (may be regexp)
* @param index - offset of find
* @param all - all if true, else initial
* @return - the replacement region
*
* @throws BadLocationException
*/
private IRegion caseReplace(String replacer, int index, boolean all) throws BadLocationException {
IRegion result = null;
IDocumentUndoManager undoer = DocumentUndoManagerRegistry.getDocumentUndoManager(getDocument());
try {
if (!isReplaceAll() && undoer != null) {
undoer.beginCompoundChange();
}
IFindReplaceTarget target = getTarget();
// first replace with (possible regexp) string
((IFindReplaceTargetExtension3)target).replaceSelection(replacer, isRegexp());
// adjust case of actual replacement string
replacer = target.getSelectionText();
String caseReplacer = replacer;
if (all) {
caseReplacer = caseReplacer.toUpperCase();
} else {
caseReplacer = caseReplacer.trim();
caseReplacer = Character.toUpperCase(caseReplacer.charAt(0)) +
caseReplacer.substring(1,caseReplacer.length()).toString();
// now update the replacement string with the re-cased part
caseReplacer = replacer.replaceFirst(replacer.trim(), caseReplacer);
}
int ind = target.findAndSelect(index, replacer, true, false, false);
if (ind > -1) {
target.replaceSelection(caseReplacer);
}
} finally {
if (!isReplaceAll() && undoer != null) {
undoer.endCompoundChange();
}
}
return result;
}
protected String getSelectionText() {
String result = null;
IFindReplaceTarget target = getTarget();
if (target != null) {
result = target.getSelectionText();
}
return result;
}
protected Point getSelection() {
Point result = null;
IFindReplaceTarget target = getTarget();
if (target != null) {
result = target.getSelection();
}
return result;
}
@Override
public IFindReplaceTarget getFindReplaceTarget() {
throw new UnsupportedOperationException();
}
@Override
public IFindReplaceTarget getFindReplaceTarget() {
throw new UnsupportedOperationException();
}
@Override
public IFindReplaceTarget getFindReplaceTarget() {
throw new UnsupportedOperationException();
}
public XFindPanel(final Composite parent, IEditorPart editorPart) {
super(parent, SWT.NONE);
statusLine = new StatusLine(editorPart.getEditorSite());
setVisible(false);
if (editorPart != null) {
target = (IFindReplaceTarget) editorPart.getAdapter(IFindReplaceTarget.class);
isRegExSupported = (target instanceof IFindReplaceTargetExtension3);
}
final IPreferenceStore store = XFindPlugin.getDefault().getPreferenceStore();
if (!store.contains(XFIND_PANEL_PLACEMENT)) {
store.setDefault(XFIND_PANEL_PLACEMENT, XFIND_PANEL_PLACEMENT_TOP);
}
if (store.getInt(XFIND_PANEL_PLACEMENT) == XFIND_PANEL_PLACEMENT_BOTTOM) {
moveBelow(null);
} else {
moveAbove(null);
}
createContents();
loadHistory(store);
store.addPropertyChangeListener(new IPropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent event) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (XFIND_PANEL_PLACEMENT.equals(event.getProperty())) {
if (store.getInt(XFIND_PANEL_PLACEMENT) == XFIND_PANEL_PLACEMENT_BOTTOM) {
moveBelow(null);
} else {
moveAbove(null);
}
parent.layout();
}
}
});
}
});
parent.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
saveHistory(store);
}
});
}
@Override
public IFindReplaceTarget getFindReplaceTarget() {
throw new UnsupportedOperationException();
}
public IFindReplaceTarget getFindReplaceTarget() {
return originalTextViewer.getFindReplaceTarget();
}
public void open()
{
AbstractThemeableEditor editor = getEditor();
if (editor != null)
{
// grab AST, making sure the file has been parsed
IParseNode ast = editor.getAST();
// assume no target identifier
JSIdentifierNode targetIdentifier = null;
// try to locate the target identifier in the AST
if (ast instanceof JSParseRootNode)
{
// collect all identifiers that match the search string
JSIdentifierCollector collector = new JSIdentifierCollector(searchString);
((JSParseRootNode) ast).accept(collector);
List<JSIdentifierNode> identifiers = collector.getIdentifiers();
// try to refine the selection based on link type
if (INVOCATION_TYPE.equals(getTypeLabel()))
{
for (JSIdentifierNode identifier : identifiers)
{
if (identifier.getParent().getNodeType() == IJSNodeTypes.FUNCTION)
{
targetIdentifier = identifier;
break;
}
}
}
// assume first item in list, as a fallback. This is only slightly better than performing a plain-text
// search
if (targetIdentifier == null && !CollectionsUtil.isEmpty(identifiers))
{
targetIdentifier = identifiers.get(0);
}
}
if (targetIdentifier != null)
{
// show the identifier we ended up with
editor.selectAndReveal(targetIdentifier.getStart(), targetIdentifier.getLength());
}
else
{
IFindReplaceTarget target = (IFindReplaceTarget) editor.getAdapter(IFindReplaceTarget.class);
if (target != null && target.canPerformFind())
{
// do a standard search (forward from 0 offset, case sensitive, whole word)
target.findAndSelect(0, searchString, true, true, true);
}
else
{
// as a last resort, show the editor. Not sure this will ever happen, but here just in case
editor.selectAndReveal(0, 0);
}
}
}
}
public CopiedFromFindReplaceDialog(IFindReplaceTarget target, IEditorStatusLine statusLineManager)
{
this.fTarget = target;
this.fStatusLineManager = statusLineManager;
}
protected IFindReplaceTarget getTarget(ITextEditor editor) {
return (IFindReplaceTarget)editor.getAdapter(IFindReplaceTarget.class);
}
/**
* Find the next occurrence of empty line consisting of ^$
* Since findNext will find multiple sequential ^$'s, we only need find one
*
* @param editor
* @param forward
* @return offset of match in widget coords
*/
protected int findNextEmpty(ITextEditor editor, boolean forward) {
IFindReplaceTarget frt = getTarget(editor);
Point selection = frt.getSelection();
int count = MarkUtils.getCharCount(editor);
int coffset = MarkUtils.getCaretOffset(editor);
// don't move past EOB
int offset = Math.min(count,coffset + (forward ? 1 : -1)); //(forward ? selection.x + selection.y+1 : selection.x-2);
int next = 0;
int prev = -1;
do {
next = ((IFindReplaceTargetExtension3)frt).findAndSelect(offset, REGEX_BOL_HACK, forward, false, false, true);
if (next == -1 || prev == next){
// we've run out of buffer
offset = (forward ? count : 0);
MarkUtils.setWidgetSelection(editor, offset, offset);
return offset;
} else if (forward && offset > next) {
// protect against overrun
MarkUtils.setWidgetSelection(editor, count, count);
return count;
} else if (!forward && offset < next) {
// protect against overrun
MarkUtils.setWidgetSelection(editor, 0, 0);
return 0;
} else {
selection = frt.getSelection();
// Eclipse internals (frda) return different regions depending on whether the file has a
// single or double line delimiter e.g. \r\n or \n. In the former it returns a 0 length
// region, and in the latter a length of 1
if (selection.y == 0 || (!forward && selection.x == 0)) {
// found it, or reached the top
return selection.x;
} if (selection.y == 1) {
// check for single line delimiter
char c = frt.getSelectionText().charAt(0);
if (c == '\n' || c == '\r'){
return selection.x;
}
}
// the widget count could change if a folded region expands automatically
count = MarkUtils.getCharCount(editor);
// don't move past EOB
offset = Math.min(count,(forward ? selection.x + selection.y+1 : selection.x-1));
prev = next;
}
} while (next != -1);
return next;
}
protected IFindReplaceTarget getTarget() {
return (IFindReplaceTarget)getEditor().getAdapter(IFindReplaceTarget.class);
}
/**
* Perform one replacement
*
* @return the replacement index
*/
private boolean replaceIt() {
boolean result = false;
boolean forward = true;
if (!checkPaused()) {
findCount++;
try {
result = true;
int index = getSearchOffset();
IFindReplaceTarget target = getTarget();
int fpos = findTarget(target,getSearchStr(), index, forward);
if (fpos > -1) {
boolean initial = false;
boolean all = false;
String replacer = replaceStr;
if (!isCaseSensitive() && replacer.length() > 0) {
// Preserve case using the emacs definition
// - Preserving case means that if the string matched is all caps, or capitalized,
// then its replacement is upper cased or capitalized.)
String replacee = target.getSelectionText().trim();
if (replacee != null && replacee.length() > 0) {
initial = Character.isUpperCase(replacee.charAt(0));
all = initial;
if (initial) {
for (int i = 1; i < replacee.length(); i++) {
if (!Character.isUpperCase(replacee.charAt(i))) {
all = false;
break;
}
}
}
}
}
int adjust = 0;
if (all || initial) {
caseReplace(replacer,index,all);
} else {
if (isRegexLD()) {
adjust = replacer.length(); // prevents repetitious find of same EOL
// now we need the offset in model coords
ITextSelection sel = (ITextSelection)getEditor().getSelectionProvider().getSelection();
// use document 'insert' instead of broken target replace
getDocument().replace(sel.getOffset(),0,replacer);
// search uses cursor position - s/r is always forward
MarkUtils.setCursorOffset(getEditor(), sel.getOffset()+adjust);
} else {
((IFindReplaceTargetExtension3)target).replaceSelection(replacer, isRegexp());
}
}
Point p = target.getSelection();
int rIndex = p.x + p.y + adjust;
setSearchOffset(rIndex);
}
} catch (Exception e) {
setResultString(e.getLocalizedMessage(), true);
finish();
beep();
}
}
return result;
}
/**
* Find the next instance of the search string in the buffer
*
* @param searchStr
* @param addit - true when just added text to search string
* @return true if we found a match
*/
protected boolean findNext(String searchStr,boolean addit) {
if (isSearchEnabled()) {
setRegexLD(false);
StyledText text = getTextWidget();
IFindReplaceTarget target = getTarget();
if (text != null && target != null) {
int searchIndex = getSearchOffset();
if (searchIndex != WRAP_INDEX) {
Point p = getSelection();
// if not building the string (or wrapping) search from caret position
if (!addit) {
if (isFound() && p != null) {
searchIndex = p.x;
if (isForward()) {
// increment index by (actual or implicit) selection width
searchIndex += (p.y == 0 ? getEol().length() : p.y);
}
} else {
// Cannot use target.getSelection since that does not return which side of the
// selection the caret is on.
searchIndex = text.getCaretOffset();
}
}
if (!forward && p != null) {
// if at beginning of line, back up by full eol, else just 1
searchIndex -= ((p.x == text.getOffsetAtLine(text.getLineAtOffset(p.x))) ? getEol().length() : 1);
}
}
int index = findTarget(target,searchStr,searchIndex, forward);
boolean justFound = (index != WRAP_INDEX);
if (isFound() && !justFound && (addit && !isRegexp())) {
beep();
} else if (!addit) {
setSearchOffset(index);
}
setFound(justFound);
}
}
return isFound();
}
@Override
public IFindReplaceTarget getFindReplaceTarget() {
return viewer.getFindReplaceTarget();
}
/**
* Instantiates a new find annotate dialog.
*
* @param parentShell the parent shell
* @param document the document
* @param findReplaceTarget the find replace target
* @param modeType the mode type
*/
FindAnnotateDialog(Shell parentShell, ICasDocument document, IFindReplaceTarget findReplaceTarget, Type modeType) {
super(parentShell);
this.document = document;
this.findReplaceTarget = findReplaceTarget;
this.modeType = modeType;
}
/**
* Instantiates a new find annotate action.
*
* @param editor the editor
* @param target the target
*/
FindAnnotateAction(AnnotationEditor editor, IFindReplaceTarget target) {
this.editor = editor;
this.target = target;
}