下面列出了怎么用org.eclipse.jface.text.FindReplaceDocumentAdapter的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testHoverThrowable() throws Exception {
String uriString = ClassFileUtil.getURI(project, "java.lang.Exception");
IClassFile classFile = JDTUtils.resolveClassFile(uriString);
String contents = JavaLanguageServerPlugin.getContentProviderManager().getSource(classFile, monitor);
IDocument document = new Document(contents);
IRegion region = new FindReplaceDocumentAdapter(document).find(0, "Throwable", true, false, false, false);
int offset = region.getOffset();
int line = document.getLineOfOffset(offset);
int character = offset - document.getLineOffset(line);
TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uriString);
Position position = new Position(line, character);
TextDocumentPositionParams params = new TextDocumentPositionParams(textDocument, position);
Hover hover = handler.hover(params, monitor);
assertNotNull(hover);
assertTrue("Unexpected hover ", !hover.getContents().getLeft().isEmpty());
}
public boolean hasPlusCal() {
try {
// Search the document for the string "--algorithm" or "--fair".
final IDocument doc = this.getDocumentProvider().getDocument(this.getEditorInput());
final FindReplaceDocumentAdapter search = new FindReplaceDocumentAdapter(doc);
IRegion find = search.find(0, IPCalReservedWords.ALGORITHM, true, true, false, false);
if (find != null) {
return true;
}
find = search.find(0, "--" + IPCalReservedWords.FAIR, true, true, false, false);
if (find != null) {
return true;
}
} catch (BadLocationException e) {
}
return false;
}
/**
* For an given id that is used in the document retrieves the four coordinates of it's first occurrence.
* @param document
* @param searchAdapter
* @param idRegion
* @return location coordinates in the sense of {@link Location} class (bl, bc, el, ec).
* @throws CoreException on errors
*/
public static int[] calculateCoordinates(IDocument document, FindReplaceDocumentAdapter searchAdapter, String id)
throws CoreException
{
try
{
IRegion foundId = searchAdapter.find(0, id, true, true, false, false);
if (foundId == null)
{
return EMPTY_LOCATION;
} else
{
// return the coordinates
return regionToLocation(document, foundId, true);
}
} catch (BadLocationException e)
{
throw new CoreException(new Status(IStatus.ERROR, TLCActivator.PLUGIN_ID,
"Error during detection of the id position in MC.tla.", e));
}
}
public List<IRegion> searchOccurrences(String searchFor) {
ArrayList<IRegion> lst = new ArrayList<IRegion>();
FindReplaceDocumentAdapter adapter = new FindReplaceDocumentAdapter(this.doc);
boolean regExSearch = false;
boolean wholeWord = true;
boolean caseSensitive = true;
boolean forwardSearch = true;
int startOffset = 0;
try {
while (true) {
IRegion found = adapter.find(startOffset, searchFor, forwardSearch, caseSensitive, wholeWord,
regExSearch);
if (found == null) {
break;
}
lst.add(found);
startOffset = found.getOffset() + found.getLength();
}
} catch (BadLocationException e) {
Log.log(e);
}
return lst;
}
private boolean initializePatternControl() {
ISelection selection = getSelection();
if (selection instanceof ITextSelection && !selection.isEmpty()
&& ((ITextSelection) selection).getLength() > 0) {
String text = ((ITextSelection) selection).getText();
if (text != null) {
if (fIsRegExSearch) {
fPattern.setText(FindReplaceDocumentAdapter.escapeForRegExPattern(text));
} else {
fPattern.setText(insertEscapeChars(text));
}
return true;
}
}
return false;
}
private Map<Annotation,Position> createWarningAnnotations(final String variable) {
final FindReplaceDocumentAdapter finder = new FindReplaceDocumentAdapter(document);
final String expression = document.get();
final Map<Annotation,Position> annotations= new HashMap<Annotation,Position>();
try {
IRegion region = finder.find(0, variable, true, true, true, false);
while (region != null) {
final Position position = new Position(region.getOffset(), region.getLength());
if (!isInAStringExpression(variable, region, expression)) {
annotations.put(new Annotation(JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE, false, createDescription(variable)), position);
}
region = finder.find(position.getOffset() + position.getLength(), variable, true, true, true, false);
}
} catch (final BadLocationException e) {
}
return annotations ;
}
private String performTextReplacement(final String elementNameToUpdate, final String newElementName, final String script) {
final Document document = new Document(script);
final FindReplaceDocumentAdapter finder = new FindReplaceDocumentAdapter(document);
IRegion region;
try {
int i = 0;
region = finder.find(0, elementNameToUpdate, true, true, false, false);
while (region != null) {
i = i + region.getLength();
finder.replace(newElementName, false);
region = finder.find(i, elementNameToUpdate, true, true, false, false);
}
} catch (final BadLocationException e1) {
// Just ignore them
}
return document.get();
}
public static IRegion getDelimRegion( IDocument doc, int offset) throws BadLocationException{
IRegion regLine = doc.getLineInformationOfOffset(offset);
FindReplaceDocumentAdapter finder = new FindReplaceDocumentAdapter(doc);
int lineOff = regLine.getOffset();
IRegion regDelim = null;
try {
regDelim = finder.find(lineOff, AssistConstants.S_EQUAL, true, true, false, false);
} catch (Exception ignore) {}
return regDelim;
}
/**
* @see com.mulgasoft.emacsplus.commands.MinibufferExecHandler#doExecuteResult(org.eclipse.ui.texteditor.ITextEditor, java.lang.Object)
*/
@Override
protected boolean doExecuteResult(ITextEditor editor, Object minibufferResult) {
String msg = null;
boolean isError = false;
if (minibufferResult == null) {
msg = String.format(msg, 0);
} else {
try {
int count = 1; // cursor is already at the end of the first find
int begin = getCursorOffset(editor);
String searchStr = getSearchStr(minibufferResult);
FindReplaceDocumentAdapter fda = new FindReplaceDocumentAdapter(getThisDocument(editor));
IRegion found = null;
while ((found = getNextMatch(fda,begin,searchStr)) != null) {
++count;
int tmp = found.getOffset() + found.getLength();
if (tmp != begin) {
begin = tmp;
} else {
// offset should always move after match, but just in case
msg = "Infinite loop on = " + searchStr; //$NON-NLS-1$
isError = true;
break;
}
}
if (msg == null) {
msg = ((count == 1) ? OCCURRENCE : String.format(OCCURRENCES, count));
}
} catch (BadLocationException e) {
// shouldn't happen, but alert user if it does
msg = BAD_LOCATION_ERROR;
isError = true;
}
}
asyncShowMessage(editor, msg, isError);
return true;
}
private void doBuild(IDocument document, List<ITypedRegion> groovyPartitions) {
final Set<String> parsedExpressions = Sets.newHashSet();
expression.getReferencedElements().clear();
for (final ITypedRegion region : groovyPartitions) {
try {
final String expressionContent = strip(document.get(region.getOffset(), region.getLength()));
if (expressionContent != null && !parsedExpressions.contains(expressionContent)) {
final Expression groovyScriptExpression = ExpressionHelper
.createGroovyScriptExpression(expressionContent, String.class.getName());
groovyScriptExpression.setName(expressionContent);
final Document expDoc = new Document();
expDoc.set(expressionContent);
final FindReplaceDocumentAdapter expDocFinder = new FindReplaceDocumentAdapter(expDoc);
for (final Expression exp : scope) {
if (expDocFinder.find(0, exp.getName(), true, true, true, false) != null) {
groovyScriptExpression.getReferencedElements()
.add(ExpressionHelper.createDependencyFromEObject(exp));
}
}
expression.getReferencedElements().add(groovyScriptExpression);
parsedExpressions.add(expressionContent);
}
} catch (final BadLocationException e) {
}
}
}
protected Map<TLAMarkerInformationHolder, Hashtable<String, Object>> sany2ToolboxErrors(final IProgressMonitor monitor, final IFile rootModule,
final Vector<TLAMarkerInformationHolder> detectedErrors) throws CoreException {
FileEditorInput fileEditorInput = new FileEditorInput(rootModule);
FileDocumentProvider fileDocumentProvider = new FileDocumentProvider();
final Map<TLAMarkerInformationHolder, Hashtable<String, Object>> result = new HashMap<>();
try
{
fileDocumentProvider.connect(fileEditorInput);
// The document for manipulation of the MC.tla file
IDocument document = fileDocumentProvider.getDocument(fileEditorInput);
// the find/replace adapter to find texts in the document
FindReplaceDocumentAdapter searchAdapter = new FindReplaceDocumentAdapter(document);
for (int i = 0; i < detectedErrors.size(); i++)
{
// the holder has the information about the error in the MC file
TLAMarkerInformationHolder markerHolder = (TLAMarkerInformationHolder) detectedErrors.get(i);
String message = markerHolder.getMessage();
if (markerHolder.getModuleName() != null)
{
// the root module is MC.tla
if (markerHolder.getModuleName().equals(rootModule.getName()))
{
int severity = markerHolder.getSeverityError();
int[] coordinates = markerHolder.getCoordinates();
// find the error cause and install the error marker on the corresponding
// field
result.put(markerHolder, ModelHelper.createMarkerDescription(rootModule, document, searchAdapter,
message, severity, coordinates));
} else
{
// see getLaunch(...) above
DebugPlugin.getDefault().getLaunchManager().removeLaunch(this.launch);
// the reported error is not pointing to the MC file.
throw new CoreException(new Status(IStatus.ERROR, TLCActivator.PLUGIN_ID,
"Fatal error during validation of the model. "
+ "SANY discovered an error somewhere else than the MC file. "
+ "This is a bug. The error message was " + message + " in the module "
+ markerHolder.getModuleName()));
}
} else
{
// see getLaunch(...) above
DebugPlugin.getDefault().getLaunchManager().removeLaunch(this.launch);
throw new CoreException(new Status(IStatus.ERROR, TLCActivator.PLUGIN_ID,
"Fatal error during validation of the model. "
+ "SANY discovered an error somewhere else than the MC file. "
+ "This is a bug. The error message was " + message + "."));
}
}
} finally
{
/*
* The document provider is not needed. Always disconnect it to avoid a memory leak.
*
* Keeping it connected only seems to provide synchronization of
* the document with file changes. That is not necessary in this context.
*/
fileDocumentProvider.disconnect(fileEditorInput);
monitor.done();
}
return result;
}
/** burke 修改find/replace界面修改 不需要fuzzySearch*/
//private boolean fuzzySearch;
public IRegion executeSearch(String findValue, String dataValue) {
// 如果查找的字符和单元格中的数据长度为 0,,则直接返回没有找到。
if (findValue == null || findValue.length() == 0 || dataValue == null || dataValue.length() == 0) {
return null;
}
Document doc = new Document(dataValue);
FindReplaceDocumentAdapter adapter = new FindReplaceDocumentAdapter(doc);
IRegion region;
try {
if (startOffset == -1) {
if (searchForward) {
startOffset = 0;
} else {
startOffset = adapter.length() - 1;
}
}
region = adapter.find(startOffset, findValue, searchForward, caseSensitive, wholeWord, regExSearch);
while (region != null) {
boolean inTag = false;
for (int i = region.getOffset(); i < region.getOffset() + region.getLength(); i++) {
Position tagRange = InnerTagUtil.getStyledTagRange(dataValue, i);
if (tagRange != null) {
if (searchForward) {
if (tagRange.getOffset() + tagRange.getLength() == dataValue.length()) {
return null; // 如果句首是一个标记,则直接返回 null,会继续查找上一个文本段。
}
startOffset = tagRange.getOffset() + tagRange.getLength();
} else {
if (tagRange.offset == 0) {
return null; // 如果句首是一个标记,则直接返回 null,会继续查找上一个文本段。
}
startOffset = tagRange.getOffset() - 1;
}
inTag = true;
break;
}
}
if (inTag) {
region = adapter.find(startOffset, findValue, searchForward, caseSensitive, wholeWord, regExSearch);
} else {
break;
}
}
return region;
} catch (BadLocationException e) {
return null;
}
}
/** burke 修改find/replace界面修改 不需要fuzzySearch*/
//private boolean fuzzySearch;
public IRegion executeSearch(String findValue, String dataValue) {
// 如果查找的字符和单元格中的数据长度为 0,,则直接返回没有找到。
if (findValue == null || findValue.length() == 0 || dataValue == null || dataValue.length() == 0) {
return null;
}
Document doc = new Document(dataValue);
FindReplaceDocumentAdapter adapter = new FindReplaceDocumentAdapter(doc);
IRegion region;
try {
if (startOffset == -1) {
if (searchForward) {
startOffset = 0;
} else {
startOffset = adapter.length() - 1;
}
}
region = adapter.find(startOffset, findValue, searchForward, caseSensitive, wholeWord, regExSearch);
while (region != null) {
boolean inTag = false;
for (int i = region.getOffset(); i < region.getOffset() + region.getLength(); i++) {
Position tagRange = InnerTagUtil.getStyledTagRange(dataValue, i);
if (tagRange != null) {
if (searchForward) {
if (tagRange.getOffset() + tagRange.getLength() == dataValue.length()) {
return null; // 如果句首是一个标记,则直接返回 null,会继续查找上一个文本段。
}
startOffset = tagRange.getOffset() + tagRange.getLength();
} else {
if (tagRange.offset == 0) {
return null; // 如果句首是一个标记,则直接返回 null,会继续查找上一个文本段。
}
startOffset = tagRange.getOffset() - 1;
}
inTag = true;
break;
}
}
if (inTag) {
region = adapter.find(startOffset, findValue, searchForward, caseSensitive, wholeWord, regExSearch);
} else {
break;
}
}
return region;
} catch (BadLocationException e) {
return null;
}
}
/**
* Mostly based on code from {@link org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedNamesAssistProposal}
*/
private void startEditing(ISourceViewer viewer) throws ExecutionException {
Point selOffsetAndLen = viewer.getSelectedRange();
int selStart = CoordinatesUtil.fromOffsetAndLengthToStartAndEnd(selOffsetAndLen).x;
IDocument document = viewer.getDocument();
try {
String selectedText;
if (selOffsetAndLen.y == 0) { // no characters selected
String documentText = document.get();
Point wordOffsetAndLen = TextUtil.findWordSurrounding(documentText, selStart);
if (wordOffsetAndLen != null) {
selectedText = document.get(wordOffsetAndLen.x, wordOffsetAndLen.y);
} else {
IRegion selectedLine = document.getLineInformationOfOffset(selStart);
selectedText = document.get(selectedLine.getOffset(), selectedLine.getLength());
}
} else {
selectedText = document.get(selOffsetAndLen.x, selOffsetAndLen.y);
}
LinkedPositionGroup linkedPositionGroup = new LinkedPositionGroup();
FindReplaceDocumentAdapter findReplaceAdaptor = new FindReplaceDocumentAdapter(document);
IRegion matchingRegion = findReplaceAdaptor.find(0, selectedText, true, true, false, false);
while (matchingRegion != null) {
linkedPositionGroup.addPosition(new LinkedPosition(document, matchingRegion.getOffset(), matchingRegion
.getLength()));
matchingRegion = findReplaceAdaptor.find(matchingRegion.getOffset() + matchingRegion.getLength(),
selectedText, true, true, false, false);
}
LinkedModeModel model = new LinkedModeModel();
model.addGroup(linkedPositionGroup);
model.forceInstall();
LinkedModeUI ui = new EditorLinkedModeUI(model, viewer);
ui.setExitPolicy(new DeleteBlockingExitPolicy(document));
ui.enter();
// by default the text being edited is selected so restore original selection
viewer.setSelectedRange(selOffsetAndLen.x, selOffsetAndLen.y);
} catch (BadLocationException e) {
throw new ExecutionException("Editing failed", e);
}
}
private void startEditing(ISourceViewer viewer) throws ExecutionException {
final Point selOffsetAndLen = viewer.getSelectedRange();
final IDocument document = viewer.getDocument();
try {
final String searchText;
final int candidateSearchOffset;
final int selStart = CoordinatesUtil.fromOffsetAndLengthToStartAndEnd(selOffsetAndLen).x;
if (selOffsetAndLen.y == 0) { // no characters selected
final String documentText = document.get();
final Point wordOffsetAndLen = TextUtil.findWordSurrounding(documentText, selStart);
if (wordOffsetAndLen != null) {
searchText = document.get(wordOffsetAndLen.x, wordOffsetAndLen.y);
candidateSearchOffset = wordOffsetAndLen.x;
} else {
final IRegion selectedLine = document.getLineInformationOfOffset(selStart);
searchText = document.get(selectedLine.getOffset(), selectedLine.getLength());
candidateSearchOffset = selectedLine.getOffset();
}
} else {
searchText = document.get(selOffsetAndLen.x, selOffsetAndLen.y);
candidateSearchOffset = selOffsetAndLen.x;
}
final int searchOffset;
final List<IRegion> selections;
final Point startingSelection;
final SelectInProgress currentState = getCurrentState();
if (LinkedModeModel.getModel(document, 0) != null &&
currentState != null
&& selOffsetAndLen.equals(currentState.startingSelection)
&& searchText.equals(currentState.searchText)) {
startingSelection = currentState.startingSelection;
selections = new ArrayList<IRegion>(currentState.existingSelections);
searchOffset = currentState.nextOffset;
} else {
startingSelection = selOffsetAndLen;
selections = new ArrayList<IRegion>();
searchOffset = candidateSearchOffset;
}
final IRegion matchingRegion = new FindReplaceDocumentAdapter(document).find(searchOffset,
searchText, true, true, false, false);
if (matchingRegion != null) {
selections.add(matchingRegion);
if (selections.size() == 1) {
// select the next occurrence too; only selecting the current cursor pos isn't useful
final IRegion secondMatchingRegion = new FindReplaceDocumentAdapter(document).find(
matchingRegion.getOffset() + matchingRegion.getLength(), searchText, true, true, false, false);
if (secondMatchingRegion != null) {
selections.add(secondMatchingRegion);
}
}
if (selections.size() > 1) {
final IRegion lastSelection = selections.get(selections.size() - 1);
saveCurrentState(new SelectInProgress(startingSelection, searchText, selections,
lastSelection.getOffset() + lastSelection.getLength()));
startLinkedEdit(selections, viewer, selOffsetAndLen);
}
}
} catch (BadLocationException e) {
throw new ExecutionException("Editing failed", e);
}
}
/**
* Find the next match in the document and return its region
*
* @param documentAdapter
* @param begin the search here
* @param regExp
* @return the found region or null
* @throws BadLocationException
*/
private IRegion getNextMatch(FindReplaceDocumentAdapter fda, int begin, String regExp) throws BadLocationException {
return fda.find(begin, regExp, true, false, false, true);
}