org.eclipse.jface.text.FindReplaceDocumentAdapter Java Examples

The following examples show how to use org.eclipse.jface.text.FindReplaceDocumentAdapter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HoverHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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());
}
 
Example #2
Source File: TLAEditor.java    From tlaplus with MIT License 6 votes vote down vote up
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;
}
 
Example #3
Source File: ModelHelper.java    From tlaplus with MIT License 6 votes vote down vote up
/**
 * 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));
    }
}
 
Example #4
Source File: TextSelectionUtils.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: GoSearchPage.java    From goclipse with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: UpdateUnknownReferencesListener.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
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 ;
}
 
Example #7
Source File: TextExpressionScriptContainer.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #8
Source File: DocumentUtils.java    From http4e with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #9
Source File: CountMatchesHandler.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @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;
}
 
Example #10
Source File: PatternExpressionModelBuilder.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
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) {

        }
    }
}
 
Example #11
Source File: TLCModelLaunchDelegate.java    From tlaplus with MIT License 4 votes vote down vote up
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;
}
 
Example #12
Source File: DefaultCellSearchStrategy.java    From translationstudio8 with GNU General Public License v2.0 4 votes vote down vote up
/** 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;
	}
}
 
Example #13
Source File: DefaultCellSearchStrategy.java    From tmxeditor8 with GNU General Public License v2.0 4 votes vote down vote up
/** 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;
	}
}
 
Example #14
Source File: SelectAllOccurrencesHandler.java    From eclipse-multicursor with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * 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);
	}
}
 
Example #15
Source File: SelectNextOccurrenceHandler.java    From eclipse-multicursor with Eclipse Public License 1.0 4 votes vote down vote up
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);
	}
}
 
Example #16
Source File: CountMatchesHandler.java    From e4macs with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * 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);
}