下面列出了怎么用org.eclipse.jface.text.IRegion的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* {@inheritDoc}
*/
@Override
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
// Check through the contributed hover providers.
for (ITextHover hoverContributer : hoverContributors) {
@SuppressWarnings("deprecation")
String hoverText = hoverContributer.getHoverInfo(textViewer,
hoverRegion);
if (hoverText != null) {
lastReturnedHover = hoverContributer;
return hoverText;
}
}
return String.valueOf(getHoverInfo2(textViewer, hoverRegion));
}
public void deselect(BaseEditor editor) {
FastStack<IRegion> stack = ScopeSelectionAction.getCache(editor);
ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
Region region = new Region(selection.getOffset(), selection.getLength());
Iterator<IRegion> it = stack.topDownIterator();
while (it.hasNext()) {
IRegion iRegion = it.next();
stack.pop(); //After getting the latest, pop it.
if (iRegion.equals(region)) {
if (stack.size() > 0) {
IRegion peek = stack.peek();
editor.setSelection(peek.getOffset(), peek.getLength());
}
break;
}
}
}
/**
* Finds for a \begin{env} the matching \end{env}.
* @param input
* @param envName Name of the environment, e.g. "itemize"
* @param beginIndex Must be at the start or inside of \begin{env}
* @return The region of the \end{env} command or null if the end was not found
*/
public static IRegion findMatchingEndEnvironment(String input, String envName, int beginIndex) {
int pos = beginIndex + 1;
IRegion nextEnd, nextBegin;
int level = 0;
do {
nextEnd = findEndEnvironment(input, envName, pos);
nextBegin = findBeginEnvironment(input, envName, pos);
if (nextEnd == null) return null;
if (nextBegin == null) {
level--;
pos = nextEnd.getOffset() + envName.length() + 6;
} else {
if (nextBegin.getOffset() > nextEnd.getOffset()) level--;
else level++;
pos = nextBegin.getOffset() + envName.length() + 8;
}
} while (level >= 0);
return nextEnd;
}
/**
* Finds the EL expressions's contents in the given text.
*
* @param in the text containing EL expressions.
* @return a non-null list of regions of the contents of EL expressions
*/
public static List<IRegion> getElExpressionRegions(String in) {
final Pattern braces = Pattern.compile("[{]([^}]*)[}]");
final Pattern legalFirstChar = Pattern.compile("^[$_a-zA-Z].*");
final List<IRegion> list = new ArrayList<IRegion>();
int nextFindStart = 0;
Matcher m = braces.matcher(in);
while (m.find(nextFindStart)) {
String fieldReference = m.group(1);
if (!legalFirstChar.matcher(fieldReference).matches()) {
nextFindStart = m.start() + 2;
continue;
}
list.add(new Region(m.start(1), m.end(1) - m.start(1)));
nextFindStart = m.end();
}
return list;
}
/**
* {@inheritDoc}
*/
@Override
protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo,
final int markerStartOffset) {
return new ASTVisitor() {
@SuppressWarnings("unchecked")
@Override
public boolean visit(SwitchStatement node) {
if (containsPosition(lineInfo, node.getStartPosition())) {
SwitchCase defNode = node.getAST().newSwitchCase();
defNode.setExpression(null);
node.statements().add(defNode);
node.statements().add(node.getAST().newBreakStatement());
}
return true; // also visit children
}
};
}
/**
* {@inheritDoc}
*/
@Override
protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo,
final int markerStartOffset) {
return new ASTVisitor() {
@SuppressWarnings("unchecked")
@Override
public boolean visit(SingleVariableDeclaration node) {
if (containsPosition(node, markerStartOffset) && !Modifier.isFinal(node.getModifiers())) {
if (!Modifier.isFinal(node.getModifiers())) {
Modifier finalModifier = node.getAST().newModifier(ModifierKeyword.FINAL_KEYWORD);
node.modifiers().add(finalModifier);
}
}
return true;
}
};
}
protected boolean isSelectionCommented(IDocument document, ITextSelection selection, String commentPrefix)
{
try {
for (int lineNum = selection.getStartLine(); lineNum <= selection.getEndLine(); ++lineNum) {
IRegion r = document.getLineInformation(lineNum);
String str = document.get(r.getOffset(), r.getLength()).trim();
if (!str.startsWith(commentPrefix)) {
return false;
}
}
return true;
} catch (Exception x) {
}
return false;
}
/**
* Returns this link's text
*
* @return the complete text of the link, never <code>null</code>
* @exception CoreException
* if unable to retrieve the text
*/
protected String getLinkText() throws CoreException {
try {
IDocument document = getConsole().getDocument();
IRegion region = getConsole().getRegion(this);
int regionOffset = region.getOffset();
int lineNumber = document.getLineOfOffset(regionOffset);
IRegion lineInformation = document.getLineInformation(lineNumber);
int lineOffset = lineInformation.getOffset();
String line = document.get(lineOffset, lineInformation.getLength());
int regionOffsetInLine = regionOffset - lineOffset;
int linkEnd = line.indexOf(')', regionOffsetInLine);
int linkStart = line.lastIndexOf(' ', regionOffsetInLine);
return line.substring(linkStart == -1 ? 0 : linkStart + 1, linkEnd + 1);
} catch (BadLocationException e) {
IStatus status = new Status(IStatus.ERROR, N4JSActivator.PLUGIN_ID, 0,
ConsoleMessages.msgUnableToParseLinkText(), e);
throw new CoreException(status);
}
}
private static boolean existsInNewOccurrences(SearchMatch searchResult, SearchResultGroup[] newOccurrences, TextChangeManager manager) {
SearchResultGroup newGroup= findOccurrenceGroup(searchResult.getResource(), newOccurrences);
if (newGroup == null) {
return false;
}
IRegion oldEditRange= getCorrespondingEditChangeRange(searchResult, manager);
if (oldEditRange == null) {
return false;
}
SearchMatch[] newSearchResults= newGroup.getSearchResults();
int oldRangeOffset = oldEditRange.getOffset();
for (int i= 0; i < newSearchResults.length; i++) {
if (newSearchResults[i].getOffset() == oldRangeOffset) {
return true;
}
}
return false;
}
/**
* Delete the whitespace at the end of each line from the bottom up
*
* @param lastLine last line in the region
* @param firstLine first line in the region
* @param maxOffset when narrowed, this is the last offset on the last line
* @param document the model
* @throws BadLocationException
*/
private void deleteWhitepace(int lastLine, int firstLine, int maxOffset, IDocument document) throws BadLocationException {
// bottoms up
for (int i= lastLine; i >= firstLine; i--) {
IRegion line= document.getLineInformation(i);
if (line.getLength() == 0)
continue;
int lineStart= line.getOffset();
int lineLen = line.getLength();
int lineEnd = lineStart + lineLen;
if (lineEnd > maxOffset) {
lineLen -= (lineEnd - maxOffset) - 1;
lineEnd = maxOffset;
} else {
lineEnd--;
}
int j= lineEnd;
// String t = document.get(lineStart,line.getLength());
while (j >= lineStart && Character.isWhitespace(document.getChar(j))) --j;
if (j < lineEnd) {
String newText = document.get(lineStart,(j - lineStart)+1);
updateText(document,lineStart,lineLen ,newText);
}
}
}
private void startLinkedEdit(List<IRegion> selections, ITextViewer viewer, Point originalSelection)
throws BadLocationException {
final LinkedPositionGroup linkedPositionGroup = new LinkedPositionGroup();
for (IRegion selection : selections) {
linkedPositionGroup.addPosition(new LinkedPosition(viewer.getDocument(), selection.getOffset(), selection
.getLength()));
}
LinkedModeModel model = new LinkedModeModel();
model.addGroup(linkedPositionGroup);
model.forceInstall();
//FIXME can add a listener here to listen for the end of linked mode
//model.addLinkingListener(null);
LinkedModeUI ui = new EditorLinkedModeUI(model, viewer);
ui.setExitPolicy(new DeleteBlockingExitPolicy(viewer.getDocument()));
ui.enter();
// by default the text being edited is selected so restore original selection
viewer.setSelectedRange(originalSelection.x, originalSelection.y);
}
@Override
public ASTVisitor getCorrectingASTVisitor(IRegion lineInfo, int markerStartOffset) {
return new ASTVisitor() {
@Override
public boolean visit(NumberLiteral node) {
if (containsPosition(node, markerStartOffset)) {
String token = node.getToken();
if (token.endsWith("l")) { //$NON-NLS-1$
token = token.replace('l', 'L');
node.setToken(token);
}
}
return true;
}
};
}
private IMarker createMarker(IResource resource, IDocument document, IRegion position,
String msg, int severity) throws CoreException {
if (isDuplicate(resource, position, msg)) {
return null;
}
IMarker marker = MarkerUtilities.createMarker(markerId, resource, msg,
severity);
marker.setAttribute(IMarker.CHAR_START, position.getOffset());
marker.setAttribute(IMarker.CHAR_END, position.getOffset()
+ position.getLength());
try {
// +1 since the attribute is 1-relative but document.getLineOfOffset is
// 0-relative
marker.setAttribute(IMarker.LINE_NUMBER,
document.getLineOfOffset(position.getOffset()) + 1);
} catch (BadLocationException e) {
GWTPluginLog.logWarning(e,
"Unexpected bad location when getting line number for marker.");
}
return marker;
}
private void colorize(ModelTokensChangedEvent event) {
IDocument document = viewer.getDocument();
if (document == null) {
return;
}
ITMModel model = event.model;
if (! (model instanceof TMDocumentModel)) {
return;
}
TMDocumentModel docModel = (TMDocumentModel) model;
for (Range range : event.ranges) {
try {
int length = document.getLineOffset(range.toLineNumber - 1) + document.getLineLength(range.toLineNumber - 1) - document.getLineOffset(range.fromLineNumber - 1);
IRegion region = new Region(document.getLineOffset(range.fromLineNumber -1), length);
TMPresentationReconciler.this.colorize(region, docModel);
} catch (BadLocationException ex) {
TMUIPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, TMUIPlugin.PLUGIN_ID, ex.getMessage(), ex));
}
}
}
@SuppressWarnings("deprecation")
@Override
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
if (ensureHoverCreated() && fHover.isContentTypeSupported(this.contentType)) {
return fHover.getHoverInfo(textViewer, hoverRegion);
}
return null;
}
protected IRegion check(String before, int start, int replaceLength, String text) throws Exception {
Document doc = createDocument(before);
damager.setDocument(doc);
doc.addDocumentListener(this);
doc.replace(start, replaceLength, text);
return lastRegion;
}
/**
* 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;
}
/**
* Change the indent of a, possible multiple line, code string. The given number of indent units is removed,
* and a new indent string is added.
* <p>The first line of the code will not be changed (It is considered to have no indent as it might start in
* the middle of a line).</p>
*
* @param code the code to change the indent of
* @param indentUnitsToRemove the number of indent units to remove from each line (except the first) of the given code
* @param tabWidth the size of one tab in space equivalents
* @param indentWidth the width of one indentation unit in space equivalents
* @param newIndentString the new indent string to be added to all lines (except the first)
* @param lineDelim the new line delimiter to be used. The returned code will contain only this line delimiter.
* @return the newly indent code, containing only the given line delimiters.
* @exception IllegalArgumentException if:
* <ul>
* <li>the given <code>indentWidth</code> is lower than zero</li>
* <li>the given <code>tabWidth</code> is lower than zero</li>
* <li>the given <code>code</code> is null</li>
* <li>the given <code>indentUnitsToRemove</code> is lower than zero</li>
* <li>the given <code>newIndentString</code> is null</li>
* <li>the given <code>lineDelim</code> is null</li>
* </ul>
*/
public static String changeIndent(String code, int indentUnitsToRemove, int tabWidth, int indentWidth, String newIndentString, String lineDelim) {
if (tabWidth < 0 || indentWidth < 0 || code == null || indentUnitsToRemove < 0 || newIndentString == null || lineDelim == null) {
throw new IllegalArgumentException();
}
try {
ILineTracker tracker= new DefaultLineTracker();
tracker.set(code);
int nLines= tracker.getNumberOfLines();
if (nLines == 1) {
return code;
}
StringBuffer buf= new StringBuffer();
for (int i= 0; i < nLines; i++) {
IRegion region= tracker.getLineInformation(i);
int start= region.getOffset();
int end= start + region.getLength();
String line= code.substring(start, end);
if (i == 0) { // no indent for first line (contained in the formatted string)
buf.append(line);
} else { // no new line after last line
buf.append(lineDelim);
buf.append(newIndentString);
if(indentWidth != 0) {
buf.append(trimIndent(line, indentUnitsToRemove, tabWidth, indentWidth));
} else {
buf.append(line);
}
}
}
return buf.toString();
} catch (BadLocationException e) {
// can not happen
return code;
}
}
@Override
public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) {
int lineNumber;
try {
lineNumber = getLineNumber(textViewer, hoverRegion);
return getHoverInfoInternal(textViewer, lineNumber, hoverRegion.getOffset());
} catch (final BadLocationException e) {
return null;
}
}
@Override
public void createHyperlinksByOffset(XtextResource resource, int offset, IHyperlinkAcceptor acceptor) {
super.createHyperlinksByOffset(resource, offset, acceptor);
EObject eObject = getEObjectAtOffsetHelper().resolveElementAt(resource, offset);
if (eObject instanceof Entity) {
List<INode> nodes = NodeModelUtils.findNodesForFeature(eObject, DomainmodelPackage.Literals.ABSTRACT_ELEMENT__NAME);
if (!nodes.isEmpty()) {
INode node = nodes.get(0);
if (node.getOffset() <= offset && node.getOffset() + node.getLength() > offset) {
String qualifiedJavaName = qualifiedNameConverter.toString(qualifiedNameProvider.getFullyQualifiedName(eObject));
if (resource.getResourceSet() instanceof XtextResourceSet) {
XtextResourceSet resourceSet = (XtextResourceSet) resource.getResourceSet();
Object uriContext = resourceSet.getClasspathURIContext();
if (uriContext instanceof IJavaProject) {
IJavaProject javaProject = (IJavaProject) uriContext;
try {
IType type = javaProject.findType(qualifiedJavaName);
if (type != null) {
JdtHyperlink hyperlink = jdtHyperlinkProvider.get();
hyperlink.setJavaElement(type);
hyperlink.setTypeLabel("Navigate to generated source code.");
hyperlink.setHyperlinkText("Go to type " + qualifiedJavaName);
hyperlink.setHyperlinkRegion((IRegion) new Region(node.getOffset(), node.getLength()));
acceptor.accept(hyperlink);
}
} catch(JavaModelException e) {
logger.error(e.getMessage(), e);
}
}
}
}
}
}
}
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
ITextEditor textEditor= (ITextEditor)getAdapter(ITextEditor.class);
if (region == null || textEditor == null)
return null;
IEditorSite site= textEditor.getEditorSite();
if (site == null)
return null;
ITypeRoot javaElement= getInputJavaElement(textEditor);
if (javaElement == null)
return null;
CompilationUnit ast= SharedASTProvider.getAST(javaElement, SharedASTProvider.WAIT_NO, null);
if (ast == null)
return null;
ASTNode node= NodeFinder.perform(ast, region.getOffset(), 1);
if (!(node instanceof StringLiteral) && !(node instanceof SimpleName))
return null;
if (node.getLocationInParent() == QualifiedName.QUALIFIER_PROPERTY)
return null;
IRegion nlsKeyRegion= new Region(node.getStartPosition(), node.getLength());
AccessorClassReference ref= NLSHintHelper.getAccessorClassReference(ast, nlsKeyRegion);
if (ref == null)
return null;
String keyName= null;
if (node instanceof StringLiteral) {
keyName= ((StringLiteral)node).getLiteralValue();
} else {
keyName= ((SimpleName)node).getIdentifier();
}
if (keyName != null)
return new IHyperlink[] {new NLSKeyHyperlink(nlsKeyRegion, keyName, ref, textEditor)};
return null;
}
/**
* This returns the region in <code>document</code> represented by the
* <code>location</code>. Note that a <code>Location</code> is a region
* represented by the <row, column> coordinates of its first and last
* characters.
* @param document
* @param location
* @return
* @throws BadLocationException
*/
public static IRegion getRegionOf(IDocument document, Location location)
throws BadLocationException {
int offset;
int length;
offset = document.getLineInformation(location.beginLine()-1).getOffset()
+ location.beginColumn() -1;
length = document.getLineInformation(location.endLine()-1).getOffset()
+ location.endColumn() - offset;
return new Region(offset, length) ;
}
/**
* {@inheritDoc}
* <p>
* This implementation damages entire lines unless clipped by the given partition.
* </p>
*
* @return the full lines containing the document changes described by the document event,
* clipped by the given partition. If there was a partitioning change then the whole
* partition is returned.
*/
@Override
public IRegion getDamageRegion(ITypedRegion partition, DocumentEvent e, boolean documentPartitioningChanged) {
if (!documentPartitioningChanged) {
try {
IRegion info = fDocument.getLineInformationOfOffset(e.getOffset());
int start = Math.max(partition.getOffset(), info.getOffset());
int end = e.getOffset() + (e.getText() == null ? e.getLength() : e.getText().length());
if (info.getOffset() <= end && end <= info.getOffset() + info.getLength()) {
// optimize the case of the same line
end = info.getOffset() + info.getLength();
} else {
end = endOfLineOf(end);
}
end = Math.min(partition.getOffset() + partition.getLength(), end);
return new Region(start, end - start);
} catch (BadLocationException x) {
}
}
return partition;
}
/**
* Clear initial whitespace in the rectangle
* Emacs ignores the end column on each line and removes all initial whitespace on the line
*
* @param document
* @param reg
* @throws BadLocationException
*/
private void clearInitialWhitespace(IDocument document, IRegion reg) throws BadLocationException {
int j=0;
IRegion lineInfo = document.getLineInformationOfOffset(reg.getOffset());
for ( ; j < lineInfo.getLength() - (reg.getOffset() - lineInfo.getOffset()); j++) {
if (document.get(reg.getOffset()+j,1).charAt(0) > ' ') {
break;
}
}
if (j > 0) {
document.replace(reg.getOffset(), j, EMPTY_STR);
}
}
/**
* Determines whether each line is prefixed by one of the prefixes.
*
* @param startLine Start line in document
* @param endLine End line in document
* @param prefixes Possible comment prefixes
* @param document The document
* @return <code>true</code> iff each line from <code>startLine</code>
* to and including <code>endLine</code> is prepended by one
* of the <code>prefixes</code>, ignoring whitespace at the
* begin of line
* @since 2.1
*/
protected boolean isBlockCommented(int startLine, int endLine, String[] prefixes, IDocument document) {
try {
// check for occurrences of prefixes in the given lines
for (int i= startLine; i <= endLine; i++) {
IRegion line= document.getLineInformation(i);
String text= document.get(line.getOffset(), line.getLength());
int[] found= TextUtilities.indexOf(prefixes, text, 0);
if (found[0] == -1)
// found a line which is not commented
return false;
String s= document.get(line.getOffset(), found[0]);
s= s.trim();
if (s.length() != 0)
// found a line which is not commented
return false;
}
return true;
} catch (BadLocationException x) {
// should not happen
log.error(x.getMessage(), x);
}
return false;
}
public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion)
{
try
{
IParseNode activeNode = getActiveNode(textViewer, hoverRegion.getOffset());
if (!(activeNode instanceof CSSSimpleSelectorNode))
{
return null;
}
CSSSimpleSelectorNode node = (CSSSimpleSelectorNode) activeNode;
ElementElement element = new HTMLIndexQueryHelper().getElement(node.getTypeSelector().toLowerCase());
// To avoid duplicating work, we generate the header and documentation together here
// and then getHeader and getDocumentation just return the values.
if (element != null)
{
fHeader = HTMLModelFormatter.TEXT_HOVER.getHeader(element);
fDocs = HTMLModelFormatter.TEXT_HOVER.getDocumentation(element);
return getHoverInfo(element, isBrowserControlAvailable(textViewer), null, getEditor(textViewer),
hoverRegion);
}
return null;
}
finally
{
fHeader = null;
fDocs = null;
}
}
protected IRegion modelRange2WidgetRange(IRegion region) {
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer;
return extension.modelRange2WidgetRange(region);
}
IRegion visibleRegion = sourceViewer.getVisibleRegion();
int start = region.getOffset() - visibleRegion.getOffset();
int end = start + region.getLength();
if (end > visibleRegion.getLength())
end = visibleRegion.getLength();
return new Region(start, end - start);
}
/**
* @return <code>true</code> only if the lastDamage is encloses the affected text of the given DocumentEvent.
*/
protected boolean isEventMatchingLastDamage(DocumentEvent e, IRegion lastDamage) {
int eventStart = e.getOffset();
int eventEnd = eventStart+e.getText().length();
int damageStart = lastDamage.getOffset();
int damageEnd = damageStart+lastDamage.getLength();
boolean result = damageStart<=eventStart && damageEnd>=eventEnd;
return result;
}
@Override
public void check(IDocument document, IRegion[] regions,
SpellingContext context, ISpellingProblemCollector collector,
IProgressMonitor monitor) {
ISpellingEngine engine = getEngine(context.getContentType());
if (engine == null){
engine = getEngine(TEXT_CONTENT_TYPE);
}
if (engine != null){
engine.check(document, regions, context, collector, monitor);
}
}
public IRegion getSubject(ITextViewer textViewer, int offset) {
createHover(textViewer);
if (hover != null) {
return hover.getHoverRegion(textViewer, offset);
}
return null;
}