下面列出了org.eclipse.jface.text.ITypedRegion#getOffset ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* {@inheritDoc}
* <p>
* May be replaced or extended by subclasses.
* </p>
*/
@Override
public 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;
}
/**
* Returns the next position to query in the search. The position
* is not guaranteed to be in this document's partition.
*
* @param pos an offset within the document
* @param searchForward the direction of the search
* @return the next position to query
*/
public int getNextPosition(int pos, boolean searchForward) {
final ITypedRegion partition= getPartition(pos);
if (partition == null) return simpleIncrement(pos, searchForward);
if (fPartition.equals(partition.getType()))
return simpleIncrement(pos, searchForward);
if (searchForward) {
int end= partition.getOffset() + partition.getLength();
if (pos < end)
return end;
} else {
int offset= partition.getOffset();
if (pos > offset)
return offset - 1;
}
return simpleIncrement(pos, searchForward);
}
@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;
}
/**
* {@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;
}
@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);
}
/**
* Finds the partition containing the given offset.
*
* @param document the document to search
* @param offset the offset used to find a matching partition
* @return the partition, or null
*/
public static ITypedRegion getPartition(IStructuredDocument document, int offset) {
ITypedRegion[] partitions;
try {
partitions = TextUtilities.computePartitioning(document,
IStructuredPartitioning.DEFAULT_STRUCTURED_PARTITIONING, 0,
document.getLength(), true);
} catch (BadLocationException e) {
CorePluginLog.logError(e, "Unexpected bad location exception.");
return null;
}
for (ITypedRegion partition : partitions) {
if (partition.getOffset() <= offset
&& offset < partition.getOffset() + partition.getLength()) {
return partition;
}
}
return null;
}
@Override
protected void runInternal(ITextSelection selection, IDocumentExtension3 docExtension, Edit.EditFactory factory) throws BadLocationException, BadPartitioningException {
int selectionOffset= selection.getOffset();
int selectionEndOffset= selectionOffset + selection.getLength();
List<Edit> edits= new LinkedList<Edit>();
ITypedRegion partition= docExtension.getPartition(IJavaPartitions.JAVA_PARTITIONING, selectionOffset, false);
handleFirstPartition(partition, edits, factory, selectionOffset);
while (partition.getOffset() + partition.getLength() < selectionEndOffset) {
partition= handleInteriorPartition(partition, edits, factory, docExtension);
}
handleLastPartition(partition, edits, factory, selectionEndOffset);
executeEdits(edits);
}
/**
* Returns a position in the first java partition after the last non-empty and non-comment partition.
* There is no non-whitespace from the returned position to the end of the partition it is contained in.
*
* @param document the document being modified
* @param line the line under investigation
* @param offset the caret offset into <code>line</code>
* @param partitioning the document partitioning
* @return the position of the next Java partition, or the end of <code>line</code>
*/
private static int nextPartitionOrLineEnd(IDocument document, ITextSelection line, int offset, String partitioning) {
// run relative to document
final int docOffset= offset + line.getOffset();
final int eol= line.getOffset() + line.getLength();
int nextPartitionPos= eol; // init with line end
int validPosition= docOffset;
try {
ITypedRegion partition= TextUtilities.getPartition(document, partitioning, nextPartitionPos, true);
validPosition= getValidPositionForPartition(document, partition, eol);
while (validPosition == -1) {
nextPartitionPos= partition.getOffset() - 1;
if (nextPartitionPos < docOffset) {
validPosition= docOffset;
break;
}
partition= TextUtilities.getPartition(document, partitioning, nextPartitionPos, false);
validPosition= getValidPositionForPartition(document, partition, eol);
}
} catch (BadLocationException e) {
}
validPosition= Math.max(validPosition, docOffset);
// make relative to line
validPosition -= line.getOffset();
return validPosition;
}
/**
* @since 2.8
*/
protected void computeCommentFolding(IXtextDocument xtextDocument, IFoldingRegionAcceptor<ITextRegion> foldingRegionAcceptor, ITypedRegion typedRegion, boolean initiallyFolded)
throws BadLocationException {
int offset = typedRegion.getOffset();
int length = typedRegion.getLength();
Matcher matcher = getTextPatternInComment().matcher(xtextDocument.get(offset, length));
if (matcher.find()) {
TextRegion significant = new TextRegion(offset + matcher.start(), 0);
((IFoldingRegionAcceptorExtension<ITextRegion>)foldingRegionAcceptor).accept(offset, length, initiallyFolded, significant);
} else {
((IFoldingRegionAcceptorExtension<ITextRegion>)foldingRegionAcceptor).accept(offset, length, initiallyFolded);
}
}
public void createPresentation(TextPresentation presentation, ITypedRegion region) {
if (fScanner == null) {
// will be removed if deprecated constructor will be removed
addRange(presentation, region.getOffset(), region.getLength(), fDefaultTextStyle);
return;
}
int lastStart = region.getOffset();
int length = 0;
boolean firstToken = true;
IToken lastToken = Token.UNDEFINED;
TextStyle lastTextStyle = getTokenTextStyle(lastToken);
fScanner.setRange(fDocument, lastStart, region.getLength());
while (true) {
IToken token = fScanner.nextToken();
if (token.isEOF())
break;
TextStyle textStyle = getTokenTextStyle(token);
if (lastTextStyle != null && lastTextStyle.equals(textStyle)) {
length += fScanner.getTokenLength();
firstToken = false;
} else {
if (!firstToken)
addRange(presentation, lastStart, length, lastTextStyle);
firstToken = false;
lastToken = token;
lastTextStyle = textStyle;
lastStart = fScanner.getTokenOffset();
length = fScanner.getTokenLength();
}
}
addRange(presentation, lastStart, length, lastTextStyle);
}
public ITypedRegion[] merge(ITypedRegion[] original) {
if (original == null || original.length == 0)
return original;
ITypedRegion[] result = new ITypedRegion[original.length];
String contentType = original[0].getType();
result[0] = original[0];
for(int i = 1; i < original.length; i++) {
ITypedRegion copyMe = original[i];
result[i] = new TypedRegion(copyMe.getOffset(), copyMe.getLength(), contentType);
}
return result;
}
/**
* {@inheritDoc}
* <p>
* May be replaced or extended by subclasses.
* </p>
*/
public 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;
}
public void createPresentation(TextPresentation presentation, ITypedRegion region) {
if (fScanner == null) {
// will be removed if deprecated constructor will be removed
addRange(presentation, region.getOffset(), region.getLength(), fDefaultTextStyle);
return;
}
int lastStart = region.getOffset();
int length = 0;
boolean firstToken = true;
IToken lastToken = Token.UNDEFINED;
TextStyle lastTextStyle = getTokenTextStyle(lastToken);
fScanner.setRange(fDocument, lastStart, region.getLength());
while (true) {
IToken token = fScanner.nextToken();
if (token.isEOF())
break;
TextStyle textStyle = getTokenTextStyle(token);
if (lastTextStyle != null && lastTextStyle.equals(textStyle)) {
length += fScanner.getTokenLength();
firstToken = false;
} else {
if (!firstToken)
addRange(presentation, lastStart, length, lastTextStyle);
firstToken = false;
lastToken = token;
lastTextStyle = textStyle;
lastStart = fScanner.getTokenOffset();
length = fScanner.getTokenLength();
}
}
addRange(presentation, lastStart, length, lastTextStyle);
}
protected ExtendedJavaContentAssistInvocationContext createContext(ITextViewer viewer, int offset) {
final RepositoryAccessor repositoryAccessor = new RepositoryAccessor();
repositoryAccessor.init();
final GroovyCompilationUnitFactory gcuf = new GroovyCompilationUnitFactory(repositoryAccessor);
ICompilationUnit newCompilationUnit;
try {
final IDocument document = viewer.getDocument();
GroovyExpressionPartitioner groovyExpressionPartitioner = new GroovyExpressionPartitioner();
groovyExpressionPartitioner.connect(document);
ITypedRegion partition = groovyExpressionPartitioner.getPartition(offset);
String script = document.get(partition.getOffset() + 2, partition.getLength() - 2);
groovyExpressionPartitioner.disconnect();
if (script.endsWith("}")) {
script = script.substring(0, script.length() - 1);
}
newCompilationUnit = gcuf.newCompilationUnit(script, new NullProgressMonitor());
Map<String, ScriptVariable> context = new HashMap<String, ScriptVariable>();
variableScope.stream().forEach(exp -> context.put(exp.getName(), new ScriptVariable(exp.getName(), exp.getReturnType())));
((BonitaScriptGroovyCompilationUnit) newCompilationUnit).setContext(context);
final Document tmpDocument = new Document(script);
editorPart.init(null, new FileEditorInput((IFile) newCompilationUnit.getResource()));
return new ExtendedJavaContentAssistInvocationContext(editorPart, viewer, offset, tmpDocument,
offset - partition.getOffset() - 2,
context);
} catch (final JavaModelException | BadLocationException | PartInitException e) {
BonitaStudioLog.error(e);
}
return null;
}
/**
* 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;
}
}
public void createPresentation(TextPresentation presentation, ITypedRegion region) {
if (fScanner == null) {
// will be removed if deprecated constructor will be removed
addRange(presentation, region.getOffset(), region.getLength(), fDefaultTextStyle);
return;
}
int lastStart = region.getOffset();
int length = 0;
boolean firstToken = true;
IToken lastToken = Token.UNDEFINED;
TextStyle lastTextStyle = getTokenTextStyle(lastToken);
fScanner.setRange(fDocument, lastStart, region.getLength());
while (true) {
IToken token = fScanner.nextToken();
if (token.isEOF())
break;
TextStyle textStyle = getTokenTextStyle(token);
if (lastTextStyle != null && lastTextStyle.equals(textStyle)) {
length += fScanner.getTokenLength();
firstToken = false;
} else {
if (!firstToken)
addRange(presentation, lastStart, length, lastTextStyle);
firstToken = false;
lastToken = token;
lastTextStyle = textStyle;
lastStart = fScanner.getTokenOffset();
length = fScanner.getTokenLength();
}
}
addRange(presentation, lastStart, length, lastTextStyle);
}
/**
* Detects the indentation level.
*/
public int detectIndentationLevel(IDocument document, int offset, boolean isSelection,
IFormattingContext formattingContext)
{
int indent = 0;
try
{
// detect the indentation offset with the parser, only if the given offset is not the first one in the
// current partition.
ITypedRegion partition = document.getPartition(offset);
if (partition != null && partition.getOffset() == offset)
{
return super.detectIndentationLevel(document, offset);
}
String source = document.get();
IParseRootNode parseResult = ParserPoolFactory.parse(getMainContentType(), source).getRootNode();
if (parseResult != null)
{
final XMLFormatterNodeBuilder builder = new XMLFormatterNodeBuilder();
final FormatterDocument formatterDocument = createFormatterDocument(source, offset);
IFormatterContainerNode root = builder.build(parseResult, formatterDocument);
new XMLFormatterNodeRewriter().rewrite(root);
IFormatterContext context = new XMLFormatterContext(0);
FormatterIndentDetector detector = new FormatterIndentDetector(offset);
try
{
root.accept(context, detector);
return detector.getLevel();
}
catch (Exception e)
{
// ignore
}
}
}
catch (Throwable t)
{
return super.detectIndentationLevel(document, offset);
}
return indent;
}
/**
* Returns a segmentation of the line of the given document appropriate for
* Bidi rendering.
*
* @param document the document
* @param baseLevel the base level of the line
* @param lineStart the offset of the line
* @param lineText Text of the line to retrieve Bidi segments for
* @return the line's Bidi segmentation
* @throws BadLocationException in case lineOffset is not valid in document
*/
protected static int[] getBidiLineSegments(IDocument document, int baseLevel, int lineStart, String lineText) throws BadLocationException {
if (lineText == null || document == null)
return null;
int lineLength= lineText.length();
if (lineLength <= 2)
return null;
// Have ICU compute embedding levels. Consume these levels to reduce
// the Bidi impact, by creating selective segments (preceding
// character runs with a level mismatching the base level).
// XXX: Alternatively, we could apply TextLayout. Pros would be full
// synchronization with the underlying StyledText's (i.e. native) Bidi
// implementation. Cons are performance penalty because of
// unavailability of such methods as isLeftToRight and getLevels.
Bidi bidi= new Bidi(lineText, baseLevel);
if (bidi.isLeftToRight())
// Bail out if this is not Bidi text.
return null;
IRegion line= document.getLineInformationOfOffset(lineStart);
ITypedRegion[] linePartitioning= TextUtilities.computePartitioning(document, IJavaPartitions.JAVA_PARTITIONING, lineStart, line.getLength(), false);
if (linePartitioning == null || linePartitioning.length < 1)
return null;
int segmentIndex= 1;
int[] segments= new int[lineLength + 1];
byte[] levels= bidi.getLevels();
int nPartitions= linePartitioning.length;
for (int partitionIndex= 0; partitionIndex < nPartitions; partitionIndex++) {
ITypedRegion partition = linePartitioning[partitionIndex];
int lineOffset= partition.getOffset() - lineStart;
//Assert.isTrue(lineOffset >= 0 && lineOffset < lineLength);
if (lineOffset > 0
&& isMismatchingLevel(levels[lineOffset], baseLevel)
&& isMismatchingLevel(levels[lineOffset - 1], baseLevel)) {
// Indicate a Bidi segment at the partition start - provided
// levels of both character at the current offset and its
// preceding character mismatch the base paragraph level.
// Partition end will be covered either by the start of the next
// partition, a delimiter inside a next partition, or end of line.
segments[segmentIndex++]= lineOffset;
}
if (IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())) {
int partitionEnd= Math.min(lineLength, lineOffset + partition.getLength());
while (++lineOffset < partitionEnd) {
if (isMismatchingLevel(levels[lineOffset], baseLevel)
&& String.valueOf(lineText.charAt(lineOffset)).matches(BIDI_DELIMITERS)) {
// For default content types, indicate a segment before
// a delimiting character with a mismatching embedding
// level.
segments[segmentIndex++]= lineOffset;
}
}
}
}
if (segmentIndex <= 1)
return null;
segments[0]= 0;
if (segments[segmentIndex - 1] != lineLength)
segments[segmentIndex++]= lineLength;
if (segmentIndex == segments.length)
return segments;
int[] newSegments= new int[segmentIndex];
System.arraycopy(segments, 0, newSegments, 0, segmentIndex);
return newSegments;
}
private boolean isContained(ITypedRegion region, int position, int length) {
return region.getOffset() <= position
&& position + length <= region.getOffset() + region.getLength();
}
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
int offsetInDoc) {
IDocument doc = viewer.getDocument();
IStructuredDocument structuredDoc = (IStructuredDocument) doc;
ITypedRegion partition = SseUtilities.getPartition(structuredDoc,
offsetInDoc);
if (partition == null) {
GWTPluginLog.logWarning("Could not generate CSS proposals due to problem getting partition of offset.");
return null;
}
int offsetInExtractedDoc = offsetInDoc - partition.getOffset();
CssExtractor extractor = CssExtractor.extract(doc, partition.getOffset(),
partition.getLength(), new CssResourceAwareModelLoader());
if (extractor == null) {
GWTPluginLog.logWarning("Could not extract CSS document to generate CSS proposals.");
return null;
}
IndexedRegion indexedNode = extractor.getCssModel().getIndexedRegion(
offsetInExtractedDoc);
if (indexedNode == null) {
indexedNode = (IndexedRegion) extractor.getCssDocument();
}
ICompletionProposal[] proposals;
try {
proposals = CssProposalArrangerCaller.getProposals(offsetInExtractedDoc,
(ICSSNode) indexedNode, partition.getOffset(), (char) 0);
List<ICompletionProposal> newProposals = new ArrayList<ICompletionProposal>();
for (ICompletionProposal proposal : proposals) {
newProposals.add(new IndentationFixingCompletionProposal(proposal));
}
return newProposals.toArray(new ICompletionProposal[newProposals.size()]);
} catch (Throwable e) {
GWTPluginLog.logWarning(e,
"Could not generate CSS proposals due to failed call to CSS proposal arranger.");
return null;
}
}