下面列出了怎么用org.eclipse.jface.text.ITypedRegion的API类实例代码及写法,或者点击链接到github查看源代码。
public static String[] getJsniMethods(IDocument document) {
try {
List<String> jsniMethods = new LinkedList<String>();
ITypedRegion[] regions = TextUtilities.computePartitioning(document,
GWTPartitions.GWT_PARTITIONING, 0, document.getLength(), false);
// Format all JSNI blocks in the document
for (ITypedRegion region : regions) {
if (region.getType().equals(GWTPartitions.JSNI_METHOD)) {
String jsni = document.get(region.getOffset(), region.getLength());
jsniMethods.add(jsni);
}
}
return jsniMethods.toArray(new String[0]);
} catch (BadLocationException e) {
GWTPluginLog.logError(e);
return null;
}
}
/**
* Handle the partition under the start offset of the selection.
*
* @param partition the partition under the start of the selection
* @param edits the list of edits to later execute
* @param factory the factory for edits
* @param offset the start of the selection, which must lie inside
* <code>partition</code>
*/
private void handleFirstPartition(ITypedRegion partition, List<Edit> edits, Edit.EditFactory factory, int offset) throws BadLocationException {
int partOffset= partition.getOffset();
String partType= partition.getType();
Assert.isTrue(partOffset <= offset, "illegal partition"); //$NON-NLS-1$
// first partition: mark start of comment
if (partType == IDocument.DEFAULT_CONTENT_TYPE) {
// Java code: right where selection starts
edits.add(factory.createEdit(offset, 0, getCommentStart()));
} else if (isSpecialPartition(partType)) {
// special types: include the entire partition
edits.add(factory.createEdit(partOffset, 0, getCommentStart()));
} // javadoc: no mark, will only start after comment
}
/**
* searches backwards for the given string within the same partition type
* @return the region of the match or <code>null</code> if no match were found
* @since 2.4
*/
public IRegion searchBackwardsInSamePartition(String toFind, String documentText, IDocument document, int endOffset) throws BadLocationException {
if (endOffset < 0) {
return null;
}
int length = toFind.length();
String text = preProcessSearchString(documentText);
ITypedRegion partition = document.getPartition(endOffset);
int indexOf = text.lastIndexOf(toFind, endOffset - length);
while (indexOf >= 0) {
ITypedRegion partition2 = document.getPartition(indexOf);
if (partition2.getType().equals(partition.getType())) {
return new Region(indexOf, length);
}
indexOf = text.lastIndexOf(toFind, partition2.getOffset() - length);
}
String trimmed = toFind.trim();
if (trimmed.length() > 0 && trimmed.length() != length) {
return searchBackwardsInSamePartition(trimmed, documentText, document, endOffset);
}
return null;
}
public static ITypedRegion getEnclosingJsniRegion(ITextSelection selection,
IDocument document) {
try {
ITypedRegion region = TextUtilities.getPartition(document,
GWTPartitions.GWT_PARTITIONING, selection.getOffset(), false);
if (region.getType().equals(GWTPartitions.JSNI_METHOD)) {
int regionEnd = region.getOffset() + region.getLength();
int selectionEnd = selection.getOffset() + selection.getLength();
// JSNI region should entirely contain the selection
if (region.getOffset() <= selection.getOffset()
&& regionEnd >= selectionEnd) {
return region;
}
}
} catch (BadLocationException e) {
GWTPluginLog.logError(e);
}
return null;
}
/**
* {@inheritDoc}
* <p>
* May be replaced or extended by subclasses.
* </p>
*
* @since 2.2
*/
@Override
public synchronized ITypedRegion getPartition(int offset, boolean preferOpenPartitions) {
ITypedRegion region = getPartition(offset);
if (preferOpenPartitions) {
if (region.getOffset() == offset && !region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE)) {
if (offset > 0) {
region = getPartition(offset - 1);
if (region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE))
return region;
}
return new TypedRegion(offset, 0, IDocument.DEFAULT_CONTENT_TYPE);
}
}
return region;
}
protected String getDocumentContent(IDocument document, DocumentCommand command) throws BadLocationException {
final ITypedRegion partition = document.getPartition(command.offset);
ITypedRegion[] partitions = document.getDocumentPartitioner().computePartitioning(0, document.getLength());
Iterable<ITypedRegion> partitionsOfCurrentType = Iterables.filter(Arrays.asList(partitions),
new Predicate<ITypedRegion>() {
@Override
public boolean apply(ITypedRegion input) {
return input.getType().equals(partition.getType());
}
});
StringBuilder builder = new StringBuilder();
for (ITypedRegion position : partitionsOfCurrentType) {
builder.append(document.get(position.getOffset(), position.getLength()));
}
return builder.toString();
}
protected final int readPreviousCharacter() {
if(pos <= posLimit) {
return token = TOKEN_EOF;
} else {
ITypedRegion partition;
try {
partition = getPartition(pos-1);
} catch(BadLocationException e) {
return token = TOKEN_OUTSIDE;
}
pos--;
if (contentType.equals(partition.getType())) {
return token = source.charAt(pos);
} else {
pos = partition.getOffset();
return token = TOKEN_OUTSIDE;
}
}
}
@Override
public int nextPosition(int position, boolean forward) {
ITypedRegion partition= getPartition(position);
if (fPartition.equals(partition.getType()))
return super.nextPosition(position, forward);
if (forward) {
int end= partition.getOffset() + partition.getLength();
if (position < end)
return end;
} else {
int offset= partition.getOffset();
if (position > offset)
return offset - 1;
}
return super.nextPosition(position, forward);
}
@Override
protected IRegion findExtendedDoubleClickSelection(IDocument document, int offset) {
IRegion match= super.findExtendedDoubleClickSelection(document, offset);
if (match != null)
return match;
try {
ITypedRegion region= TextUtilities.getPartition(document, fPartitioning, offset, true);
if (offset == region.getOffset() + fHitDelta || offset == region.getOffset() + region.getLength() - fHitDelta) {
if (fLeftBorder == 0 && fRightBorder == 0)
return region;
if (fRightBorder == -1) {
String delimiter= document.getLineDelimiter(document.getLineOfOffset(region.getOffset() + region.getLength() - 1));
if (delimiter == null)
fRightBorder= 0;
else
fRightBorder= delimiter.length();
}
return new Region(region.getOffset() + fLeftBorder, region.getLength() - fLeftBorder - fRightBorder);
}
} catch (BadLocationException e) {
return null;
}
return null;
}
private ITypedRegion searchCommentStart(IDocument doc, int pos, int addLines) throws BadLocationException {
int lnum = doc.getLineOfOffset(pos);
lnum += addLines;
if (lnum < doc.getNumberOfLines()) {
IRegion reg = doc.getLineInformation(lnum);
String line = doc.get(reg.getOffset(), reg.getLength());
for (int i = addLines > 0 ? 0 : pos - reg.getOffset(); i < line.length(); ++i) {
if (line.charAt(i) == '(' &&
i+1 < line.length() &&
line.charAt(i+1) == '*')
{
ITypedRegion partition = TextUtilities.getPartition(doc, IModulaPartitions.M2_PARTITIONING,
reg.getOffset() + i, false);
if (partition.getType().equals(IModulaPartitions.M2_CONTENT_TYPE_BLOCK_COMMENT)) {
return partition;
}
}
}
}
return null;
}
@Override
protected boolean isInterestingProblem(SpellingProblem problem) {
IStructuredDocument doc = (IStructuredDocument) getDocument();
try {
ITypedRegion[] partitions = doc.computePartitioning(
problem.getOffset(), problem.getLength());
for (ITypedRegion partition : partitions) {
if (partition.getType().equals(ICSSPartitions.STYLE)) {
return false;
}
}
} catch (BadLocationException e) {
// Ignore
}
return super.isInterestingProblem(problem);
}
public void createPresentation(TextPresentation presentation, ITypedRegion region) {
int start= region.getOffset();
int length= 0;
boolean firstToken= true;
TextAttribute attribute = getTokenTextAttribute(Token.UNDEFINED);
scanner.setRange(document,start,region.getLength());
while (true) {
IToken resultToken = scanner.nextToken();
if (resultToken.isEOF()) {
break;
}
if(resultToken.equals(Token.UNDEFINED)) {
continue;
}
if (!firstToken) {
addRange(presentation,start,length,attribute,true);
}
firstToken = false;
attribute = getTokenTextAttribute(resultToken);
start = scanner.getTokenOffset();
length = scanner.getTokenLength();
}
addRange(presentation,start,length,attribute,true);
}
@Test public void testJavaDoc_ML_COMMENTPartitions() throws BadLocationException {
String input = "/* some comment */class Foo {}";
document.set(input);
ITypedRegion[] partitions = document.getDocumentPartitioner().computePartitioning(0, input.length());
assertEquals(2, partitions.length);
assertEquals("__comment", partitions[0].getType());
document.replace(input.indexOf("/* some comment */"), "/* some comment */".length(), "/** some comment */");
partitions = document.getDocumentPartitioner().computePartitioning(0, input.length() + 1/* * */);
assertEquals(2, partitions.length);
assertEquals("__java_javadoc", partitions[0].getType());
document.replace(input.indexOf("/* some comment */"), "/** some comment */".length(), "/*** some comment */");
partitions = document.getDocumentPartitioner().computePartitioning(0, input.length() + 2/* ** */);
assertEquals(2, partitions.length);
assertEquals("__comment", partitions[0].getType());
}
/**
* Returns the partition type of the document displayed in <code>viewer</code> at <code>startLine</code>.
* @param viewer the viewer
* @param startLine the line in the viewer
* @return the partition type at the start of <code>startLine</code>, or <code>IDocument.DEFAULT_CONTENT_TYPE</code> if none can be detected
*/
private String getPartition(ISourceViewer viewer, int startLine) {
if (viewer == null)
return null;
IDocument doc= viewer.getDocument();
if (doc == null)
return null;
if (startLine <= 0)
return IDocument.DEFAULT_CONTENT_TYPE;
try {
ITypedRegion region= TextUtilities.getPartition(doc, fPartitioning, doc.getLineOffset(startLine) - 1, true);
return region.getType();
} catch (BadLocationException e) {
}
return IDocument.DEFAULT_CONTENT_TYPE;
}
private void replaceSlavePartitionsWithDummyText() {
try {
ITypedRegion[] partitions = TextUtilities.computePartitioning(
tempDocument, partitioning, 0, tempDocument.getLength(), false);
for (int i = 0; i < partitions.length; i++) {
if (!isSlaveContentType(partitions[i].getType())) {
continue;
}
// Ideally, we'd like to use whitespace as the dummy text, but it may
// cause the partition to be lost by the master formatter. Instead this
// uses periods.
tempDocument.replace(partitions[i].getOffset(),
partitions[i].getLength(), StringUtilities.repeatCharacter('.',
partitions[i].getLength()));
}
} catch (BadLocationException e) {
// This should not happen according to super class
}
}
/**
* Add start of coverage
* @param start
*/
public void addTagStart(ITypedRegion start)
{
// Assert.isTrue(inTag() && !inTag() == !hasUserPartitions(),
// "Found user partitions which have not been removed. This is a bug.");
ITypedRegion userRegion = getUserRegion();
if (userRegion != null)
{
stack.push(userRegion);
}
TLCRegion startRegion = new TLCRegion(start.getOffset(), start.getLength(), start.getType());
startRegion.setMessageCode(getMessageCode(start, START));
startRegion.setSeverity(getSeverity(start));
// add start to stack
stack.push(startRegion);
}
/**
* Returns array of elements from top of the stack with start as the last element (call pop until the start is found)
* @param code
* @return
*/
private ITypedRegion[] getFindStart(int code)
{
Assert.isTrue(!stack.isEmpty(), "Bug. Empty stack, start tag expected");
Vector<ITypedRegion> elements = new Vector<ITypedRegion>();
while (!stack.isEmpty())
{
ITypedRegion region = (ITypedRegion) stack.pop();
elements.add(region);
if (TagBasedTLCOutputTokenScanner.TAG_OPEN.equals(region.getType()))
{
TLCRegion startRegion = (TLCRegion) region;
Assert.isTrue(startRegion.getMessageCode() == code, "Found a non-matching start. This is a bug.");
// found a match
break;
} else
{
// not a start tag
// but something else, e.G. user partition
}
}
return (ITypedRegion[]) elements.toArray(new ITypedRegion[elements.size()]);
}
public void onOutput(ITypedRegion region, String text) {
// a) just store the region
this.regions.add(region);
// b) convert to TLCState if TLCRegion
if (region instanceof TLCRegion) {
TLCRegion tlcRegion = (TLCRegion) region;
int severity = tlcRegion.getSeverity();
switch (severity) {
case MP.STATE:
TLCState state = TLCState.parseState(text, "bogusModelName");
this.states.add(state);
return;
}
}
// c) unexpected content
this.garbage = true;
}
@Override
public boolean isInsertClosingBracket(IDocument doc, int offset) throws BadLocationException {
if (offset >= 2) {
ITypedRegion prevPartition = doc.getPartition(offset - 1);
String prevPartitionType = prevPartition.getType();
if (TerminalsTokenTypeToPartitionMapper.SL_COMMENT_PARTITION.equals(prevPartitionType)) {
return false;
}
if (TokenTypeToPartitionMapper.REG_EX_PARTITION.equals(prevPartitionType)) {
return prevPartition.getLength() == 1;
}
}
return SingleLineTerminalsStrategy.DEFAULT.isInsertClosingBracket(doc, offset);
}
/**
* Returns partition information about the region containing the
* specified position.
*
* @param pos a position within this document.
* @return positioning information about the region containing the
* position
*/
private ITypedRegion getPartition(int pos) {
if (fCachedPartition == null || !contains(fCachedPartition, pos)) {
Assert.isTrue(pos >= 0 && pos <= fDocument.getLength());
try {
fCachedPartition= TextUtilities.getPartition(fDocument, fPartitioning, pos, false);
} catch (BadLocationException e) {
fCachedPartition= null;
}
}
return fCachedPartition;
}
private boolean shouldCollapse(ITypedRegion beginRegion, int lines) {
String autofoldOption = prefs.getPreferenceStore().getString(ISolidityPreferencesConstants.FOLDING_COMMENT_AUTOFOLD);
if (ISolidityPreferencesConstants.FOLDING_COMMENT_AUTOFOLD_NONE.equals(autofoldOption))
return false;
if (ISolidityPreferencesConstants.FOLDING_COMMENT_AUTOFOLD_ALL.equals(autofoldOption))
return true;
if (ISolidityPreferencesConstants.FOLDING_COMMENT_AUTOFOLD_HEADER.equals(autofoldOption))
return beginRegion.getOffset() == 0;
return false;
}
public void testGetEnclosingJsniRegionSelectionInsideJsni() {
IRegion selRegion = RegionConverter.convertWindowsRegion(169, 3, testClass.getContents());
ITextSelection sel = new TextSelection(selRegion.getOffset(), selRegion.getLength());
ITypedRegion jsniRegion = JsniParser.getEnclosingJsniRegion(sel, getTestClassDocument());
assertNotNull(jsniRegion);
assertEquals(GWTPartitions.JSNI_METHOD, jsniRegion.getType());
IRegion expectedJsniRegion = RegionConverter.convertWindowsRegion(121, 234, testClass.getContents());
assertEquals(expectedJsniRegion.getOffset(), jsniRegion.getOffset());
assertEquals(expectedJsniRegion.getLength(), jsniRegion.getLength());
}
@Override
public void createPresentation (TextPresentation presentation, ITypedRegion region) {
this.parseJob.setPresentation(presentation);
this.parseJob.setRegion(region);
this.parseJob.cancel();
// if job is not running, effectively reset scheduled time
this.parseJob.schedule(this.delay);
}
/**
* Checks whether <code>position</code> resides in a default (Java) partition of <code>document</code>.
*
* @param document the document being modified
* @param position the position to be checked
* @param partitioning the document partitioning
* @return <code>true</code> if <code>position</code> is in the default partition of <code>document</code>, <code>false</code> otherwise
*/
private static boolean isDefaultPartition(IDocument document, int position, String partitioning) {
Assert.isTrue(position >= 0);
Assert.isTrue(position <= document.getLength());
try {
ITypedRegion region= TextUtilities.getPartition(document, partitioning, position, false);
return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE);
} catch (BadLocationException e) {
}
return false;
}
/**
* Guesses if the command operates within a newly created Javadoc comment or not.
* If in doubt, it will assume that the Javadoc is new.
*
* @param document the document
* @param commandOffset the command offset
* @return <code>true</code> if the comment should be closed, <code>false</code> if not
*/
private boolean isNewComment(IDocument document, int commandOffset) {
try {
int lineIndex= document.getLineOfOffset(commandOffset) + 1;
if (lineIndex >= document.getNumberOfLines())
return true;
IRegion line= document.getLineInformation(lineIndex);
ITypedRegion partition= TextUtilities.getPartition(document, fPartitioning, commandOffset, false);
int partitionEnd= partition.getOffset() + partition.getLength();
if (line.getOffset() >= partitionEnd)
return false;
if (document.getLength() == partitionEnd)
return true; // partition goes to end of document - probably a new comment
String comment= document.get(partition.getOffset(), partition.getLength());
if (comment.indexOf("/*", 2) != -1) //$NON-NLS-1$
return true; // enclosed another comment -> probably a new comment
return false;
} catch (BadLocationException e) {
return false;
}
}
/**
* @see IPresentationRepairer#createPresentation(TextPresentation,
* ITypedRegion)
*/
public void createPresentation( TextPresentation presentation,
ITypedRegion region )
{
addRange( presentation,
region.getOffset( ),
region.getLength( ),
fDefaultTextAttribute );
}
/**
* {@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;
}
public QualifiedContentType getContentType(IDocument document, int offset) throws BadLocationException
{
QualifiedContentType result = new QualifiedContentType(defaultContentType);
try
{
// If we're at the end of the document, back up one char to grab partition when we have bogus zero length
// partition at EOF.
if (offset == document.getLength())
{
ITypedRegion region = document.getPartition(offset);
if (region.getLength() == 0 && offset > 0)
{
offset = offset - 1;
}
}
// get partition at offset
String contentType = document.getContentType(offset);
// grab the top level document type that this partition is a subtype of
String subdocContentType = contentTypesAssociation.get(contentType);
if (subdocContentType != null && !subdocContentType.equals(result.getLastPart()))
{
// if our content type/scope doesn't have this language level scope at the end, add it to the end
result = result.subtype(subdocContentType);
}
// add partition to end
return result.subtype(contentType);
}
catch (Exception e)
{
return result;
}
}
/**
* determines the offset of the next ITypedRegion of type {@link IDocument#DEFAULT_CONTENT_TYPE} starting from the given offset
* Fix for bug 403812.
*/
private int findOffsetOfNextDftlContentPartition(IDocument document, int startOffset) throws BadLocationException{
if (startOffset >= document.getLength()) {
return startOffset;
}
ITypedRegion partition = document.getPartition(startOffset);
if(IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())){
return startOffset;
}else{
return findOffsetOfNextDftlContentPartition(document,partition.getOffset()+partition.getLength());
}
}
@Override
public void reconcile(IRegion region) {
if (!isSpellingEnabled()) {
return;
}
ITypedRegion[] regions = computePartitioning(0, getDocument().getLength(), DEFAULT_PARTITIONING);
spellingService.check(getDocument(), regions, spellingContext, spellingProblemCollector, progressMonitor);
}