下面列出了怎么用org.eclipse.jface.text.Position的API类实例代码及写法,或者点击链接到github查看源代码。
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 ;
}
@Test
public void testInsertAnnotationWithLengthGreaterOne() {
final int annotationLength = 3;
manager.insertAnnotation(model, 5, annotationLength, ALICE_TEST_USER);
final List<Position> annotationPositions = getAnnotationPositions(model);
assertEquals(
"Annotation was not split into multiple annotation of length 1",
annotationLength,
annotationPositions.size());
assertTrue(annotationPositions.contains(new Position(5, 1)));
assertTrue(annotationPositions.contains(new Position(6, 1)));
assertTrue(annotationPositions.contains(new Position(7, 1)));
}
@Override
public boolean show(ShowInContext context) {
ISelection selection = context.getSelection();
if (selection instanceof IStructuredSelection) {
Object selected = ((IStructuredSelection) selection).getFirstElement();
if (selected instanceof AbstractNode) {
Position position = ((AbstractNode) selected).getPosition(getSourceViewer().getDocument());
selectAndReveal(position.getOffset(), position.getLength());
return true;
}
}
return false;
}
protected void updateMarkerAnnotation(IMarker marker) {
Iterator<Annotation> iter = annotationModel.getAnnotationIterator();
for (Annotation ann : (Iterable<Annotation>) () -> iter) {
if(ann instanceof MarkerAnnotation) {
MarkerAnnotation markerAnnotation = (MarkerAnnotation) ann;
if(markerAnnotation.getMarker().equals(marker)) {
Position position = annotationModel.getPosition(markerAnnotation);
// Trigger a model update.
annotationModelExt.modifyAnnotationPosition(markerAnnotation, position);
return;
}
}
}
}
/**
* @return an annotation that should be added (or null if that entry already has an annotation
* added for it).
*/
private Tuple<ProjectionAnnotation, Position> getAnnotationToAdd(FoldingEntry node, int start, int end,
ProjectionAnnotationModel model, List<Annotation> existing) throws BadLocationException {
try {
IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());
int offset = document.getLineOffset(start);
int endOffset = offset;
try {
endOffset = document.getLineOffset(end);
} catch (Exception e) {
//sometimes when we are at the last line, the command above will not work very well
IRegion lineInformation = document.getLineInformation(end);
endOffset = lineInformation.getOffset() + lineInformation.getLength();
}
Position position = new Position(offset, endOffset - offset);
return getAnnotationToAdd(position, node, model, existing);
} catch (BadLocationException x) {
//this could happen
}
return null;
}
@Override
protected Object getHoverInfoInternal(ITextViewer textViewer, final int lineNumber, final int offset) {
AnnotationInfo result = recentAnnotationInfo;
if (result != null)
return result;
List<Annotation> annotations = getAnnotations(lineNumber, offset);
for (Annotation annotation : sortBySeverity(annotations)) {
Position position = getAnnotationModel().getPosition(annotation);
if (annotation.getText() != null && position != null) {
final QuickAssistInvocationContext invocationContext = new QuickAssistInvocationContext(sourceViewer, position.getOffset(), position.getLength(), true);
CompletionProposalRunnable runnable = new CompletionProposalRunnable(invocationContext);
// Note: the resolutions have to be retrieved from the UI thread, otherwise
// workbench.getActiveWorkbenchWindow() will return null in LanguageSpecificURIEditorOpener and
// cause an exception
Display.getDefault().syncExec(runnable);
if (invocationContext.isMarkedCancelled()) {
return null;
}
result = new AnnotationInfo(annotation, position, sourceViewer, runnable.proposals);
recentAnnotationInfo = result;
return result;
}
}
return null;
}
public static Position getPosition(IFile file, TextSpan textSpan) throws BadLocationException {
ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
ITextFileBuffer buffer = bufferManager.getTextFileBuffer(file.getLocation(), LocationKind.IFILE);
if (buffer != null) {
return getPosition(buffer.getDocument(), textSpan);
}
IDocumentProvider provider = new TextFileDocumentProvider();
try {
provider.connect(file);
IDocument document = provider.getDocument(file);
if (document != null) {
return getPosition(document, textSpan);
}
} catch (CoreException e) {
} finally {
provider.disconnect(file);
}
return null;
}
/**
* Insert tab/spaces at selection offset and each subsequent line origin
*
* @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(ITextEditor, IDocument, ITextSelection, ExecutionEvent)
*/
@Override
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection, ExecutionEvent event)
throws BadLocationException {
// if we're here, either ^U or no relevant ^I
ColumnSupport cs = new ColumnSupport(document,editor);
String tab = cs.getSpaces(0,cs.getTabWidth());
int off = currentSelection.getOffset();
Position coff = new Position(getCursorOffset(editor,currentSelection),0);
try {
document.addPosition(coff);
int begin = document.getLineOfOffset(off);
int end = document.getLineOfOffset(off+ currentSelection.getLength());
if (begin != end) {
while (++begin <= end) {
document.replace(document.getLineOffset(begin), 0, tab);
}
}
document.replace(off, 0, tab);
} finally {
document.removePosition(coff);
}
return coff.offset;
}
@Test
public void should_add_to_overriden_variables_a_variable_declared_and_already_in_the_process_scope() throws Exception {
final BonitaScriptGroovyCompilationUnit groovyCompilationUnit = mock(BonitaScriptGroovyCompilationUnit.class, RETURNS_DEEP_STUBS);
Map<String, ScriptVariable> context = new HashMap<String, ScriptVariable>();
context.put("declaredVar", null);
when(groovyCompilationUnit.getContext()).thenReturn(context);
final List<Statement> statements = new ArrayList<Statement>();
statements.add(new ExpressionStatement(
new DeclarationExpression(new VariableExpression("declaredVar"), Token.NULL, new VariableExpression("something"))));
statements.add(new ReturnStatement(new VariableExpression("declaredVar")));
final VariableScope variableScope = new VariableScope();
variableScope.putDeclaredVariable(new VariableExpression("declaredVar"));
final BlockStatement blockStatement = new BlockStatement(statements, variableScope);
when(groovyCompilationUnit.getModuleNode().getStatementBlock()).thenReturn(blockStatement);
final UnknownElementsIndexer unknownElementsIndexer = new UnknownElementsIndexer(groovyCompilationUnit);
unknownElementsIndexer.run(new NullProgressMonitor());
assertThat(unknownElementsIndexer.getOverridenVariables()).containsExactly(entry("declaredVar", new Position(0)));
}
/**
* Focuses the editor to the text of the selected item.
*
* @param event the selection event
*/
public void selectionChanged(SelectionChangedEvent event) {
super.selectionChanged(event);
ISelection selection = event.getSelection();
if (selection.isEmpty()) {
editor.resetHighlightRange();
}
else {
OutlineNode node = (OutlineNode) ((IStructuredSelection) selection).getFirstElement();
Position position = node.getPosition();
if (position != null) {
try {
editor.setHighlightRange(position.getOffset(), position.getLength(), true);
editor.getViewer().revealRange(position.getOffset(), position.getLength());
} catch (IllegalArgumentException x) {
editor.resetHighlightRange();
}
} else {
editor.resetHighlightRange();
}
}
}
/**
* Pastes given text after the selected item. Used by the paste
* action.
*
* Triggers model update afterwards.
*
* @param text the text to be pasted
* @return true if pasting was succesful, otherwise false
*/
public boolean paste(String text) {
// get selection
IStructuredSelection selection = (IStructuredSelection)getTreeViewer().getSelection();
if (selection == null) {
return false;
}
OutlineNode node = (OutlineNode)selection.getFirstElement();
Position pos = node.getPosition();
// paste the text
try {
this.editor.getDocumentProvider().getDocument(this.editor.getEditorInput()).replace(pos.getOffset() + pos.getLength(), 0, text);
} catch (BadLocationException e) {
return false;
}
// trigger parsing
this.editor.updateModelNow();
return true;
}
/**
* Set the text data into TextTransfer.
*
* @see org.eclipse.swt.dnd.DragSourceListener#dragSetData(org.eclipse.swt.dnd.DragSourceEvent)
*/
public void dragSetData(DragSourceEvent event) {
// check that requested data type is supported
if (!TextTransfer.getInstance().isSupportedType(event.dataType)) {
return;
}
// get the source text
int sourceOffset = this.dragSource.getPosition().getOffset();
int sourceLength = this.dragSource.getPosition().getLength();
Position sourcePosition = dragSource.getPosition();
String sourceText = "";
try {
sourceText = getDocument().get(sourcePosition.getOffset(), sourcePosition.getLength());
} catch (BadLocationException e) {
TexlipsePlugin.log("Could not set drag data.", e);
return;
}
// set the data
event.data = sourceText;
}
private HoverInfoWithSpellingAnnotation getSpellingHover(ITextViewer textViewer, IRegion hoverRegion) {
IAnnotationModel model= null;
if (textViewer instanceof ISourceViewerExtension2) {
model = ((ISourceViewerExtension2)textViewer).getVisualAnnotationModel();
} else if (textViewer instanceof SourceViewer) {
model= ((SourceViewer)textViewer).getAnnotationModel();
}
if (model != null) {
@SuppressWarnings("rawtypes")
Iterator e= model.getAnnotationIterator();
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if (a instanceof SpellingAnnotation) {
Position p= model.getPosition(a);
if (p != null && p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) {
return new HoverInfoWithSpellingAnnotation((SpellingAnnotation)a, textViewer, p.getOffset());
}
}
}
}
return null;
}
public Object get(Position position) {
Entry entry;
// behind anchor
int length= fList.size();
for (int i= fAnchor; i < length; i++) {
entry= fList.get(i);
if (entry.fPosition.equals(position)) {
fAnchor= i;
return entry.fValue;
}
}
// before anchor
for (int i= 0; i < fAnchor; i++) {
entry= fList.get(i);
if (entry.fPosition.equals(position)) {
fAnchor= i;
return entry.fValue;
}
}
return null;
}
private static Position getPosition(ASTNode node, IDocument document) {
int offset = node.getStartPosition();
try {
IRegion region = document.getLineInformationOfOffset(offset);
return new Position(region.getOffset() + region.getLength(), 1);
} catch (BadLocationException e) {
return new Position(offset, 1);
}
}
/**
* Handles mouse moves.
*
* @param event the mouse move event
*/
protected void handleMouseMove(MouseEvent event) {
if (fTextViewer != null) {
int[] lines = toLineNumbers(event.y);
Position p = getAnnotationPosition(lines);
Cursor cursor = (p != null ? fHitDetectionCursor : null);
if (cursor != fLastCursor) {
fCanvas.setCursor(cursor);
fLastCursor = cursor;
}
}
}
/**
* @param position
* @param elements
* @return
*/
protected boolean isInside(Position position, List elements) {
for (Iterator iter = elements.iterator(); iter.hasNext();) {
Position element = (Position) iter.next();
if (position.getOffset() > element.getOffset()
&& position.getOffset() < element.getOffset() + element.getLength()) {
return true;
}
}
return false;
}
public void updateFoldingStructure(Map<ProjectionAnnotation, Position> annotations)
{
synchronized (lockUpdateFoldingStructure)
{
List<Annotation> deletions = new ArrayList<Annotation>();
Collection<Position> additions = annotations.values();
ProjectionAnnotationModel currentModel = getAnnotationModel();
if (currentModel == null)
{
return;
}
for (@SuppressWarnings("rawtypes")
Iterator iter = currentModel.getAnnotationIterator(); iter.hasNext();)
{
Object annotation = iter.next();
if (annotation instanceof ProjectionAnnotation)
{
Position position = currentModel.getPosition((Annotation) annotation);
if (additions.contains(position))
{
additions.remove(position);
}
else
{
deletions.add((Annotation) annotation);
}
}
}
if (annotations.size() != 0 || deletions.size() != 0)
{
currentModel.modifyAnnotations(deletions.toArray(new Annotation[deletions.size()]), annotations, null);
}
}
}
public FileLink getFileLink(int offset) {
try {
IDocument document = getDocument();
if (document != null) {
Position[] positions = document.getPositions(ERROR_MARKER_CATEGORY);
Position position = findPosition(offset, positions);
if (position instanceof MarkerPosition) {
return ((MarkerPosition) position).getFileLink();
}
}
} catch (BadPositionCategoryException e) {
}
return null;
}
private boolean isPositionValid(Position position, String contentType) {
if (fSupportKeepPositions || (fForward && position.getOffset() + position.getLength() >= fOffset || !fForward
&& position.getOffset() <= fOffset)) {
if (position instanceof TypedPosition) {
TypedPosition typedPosition = (TypedPosition) position;
if (contentType != null && !contentType.equals(ALL_CONTENT_TYPES_AVAILABLE)) {
if (!contentType.equals(typedPosition.getType())) {
return false;
}
}
}
return true;
}
return false;
}
@Override
public void processIssues(List<Issue> issues, IProgressMonitor monitor) {
updateMarkersOnModelChange = false;
List<Annotation> toBeRemoved = getAnnotationsToRemove(monitor);
Multimap<Position, Annotation> positionToAnnotations = ArrayListMultimap.create();
Map<Annotation, Position> annotationToPosition = getAnnotationsToAdd(positionToAnnotations, issues, monitor);
updateMarkerAnnotations(monitor);
updateAnnotations(monitor, toBeRemoved, annotationToPosition);
updateMarkersOnModelChange = true;
}
/**
* Empties the collector.
*/
public void reset() {
fProposals.clear();
for (Iterator<Entry<IDocument, Position>> it= fPositions.entrySet().iterator(); it.hasNext();) {
Entry<IDocument, Position> entry= it.next();
IDocument doc= entry.getKey();
Position position= entry.getValue();
doc.removePosition(position);
}
fPositions.clear();
}
protected void announceAnnotationChanged(Annotation annotation) {
if (annotationModel instanceof XtextResourceMarkerAnnotationModel)
((XtextResourceMarkerAnnotationModel) annotationModel).fireAnnotationChangedEvent(annotation);
else {
Position position = annotationModel.getPosition(annotation);
if (annotationModel instanceof IAnnotationModelExtension)
((IAnnotationModelExtension) annotationModel).modifyAnnotationPosition(annotation, position);
else {
annotationModel.removeAnnotation(annotation);
annotationModel.addAnnotation(annotation, position);
}
}
}
/**
* Determine if the offset is in one of the Positions in the Position list
*
* @param doc
* @param positions
* @param offset
* @return true if in a Position
*/
public static Position inPosition(IDocument doc, List<Position> positions, int offset) {
for (Position p : positions) {
if (p.includes(offset)){
return p;
}
}
return null;
}
/**
* We have to be careful not to remove existing annotations because if this happens, previous code folding is not correct.
*/
private Tuple<ProjectionAnnotation, Position> getAnnotationToAdd(Position position, FoldingEntry node,
ProjectionAnnotationModel model, List<Annotation> existing) {
for (Iterator<Annotation> iter = existing.iterator(); iter.hasNext();) {
Annotation element = iter.next();
Position existingPosition = model.getPosition(element);
if (existingPosition.equals(position)) {
//ok, do nothing to this annotation (neither remove nor add, as it already exists in the correct place).
existing.remove(element);
return null;
}
}
return new Tuple<ProjectionAnnotation, Position>(new PyProjectionAnnotation(node.getAstEntry(),
node.isCollapsed), position);
}
/**
* Returns the index of the first position which ends after the given offset.
*
* @param positions the positions in linear order
* @param offset the offset
* @return the index of the first position which ends after the offset
*/
private int getFirstIndexEndingAfterOffset(Position[] positions, int offset) {
int i= -1, j= positions.length;
while (j - i > 1) {
int k= (i + j) >> 1;
Position p= positions[k];
if (p.getOffset() + p.getLength() > offset)
j= k;
else
i= k;
}
return j;
}
protected void calculatePositions(boolean initialReconcile, IProgressMonitor monitor, IParseRootNode ast)
{
if (monitor != null && monitor.isCanceled())
{
return;
}
// Folding...
try
{
Map<ProjectionAnnotation, Position> positions = folder.emitFoldingRegions(initialReconcile, monitor, ast);
synchronized (fPositionsLock)
{
fPositions = positions;
}
}
catch (BadLocationException e)
{
IdeLog.logError(CommonEditorPlugin.getDefault(), e);
}
// If we had all positions we shouldn't probably listen to cancel, but we may have exited emitFoldingRegions
// early because of cancel...
if (monitor != null && monitor.isCanceled() || !shouldUpdatePositions(folder))
{
return;
}
updatePositions();
}
/**
* Returns the index of the first position which ends after the given offset.
*
* @param positions
* the positions in linear order
* @param offset
* the offset
* @return the index of the first position which ends after the offset
*/
private int getFirstIndexEndingAfterOffset(Position[] positions, int offset) {
int i = -1, j = positions.length;
while (j - i > 1) {
int k = (i + j) >> 1;
Position p = positions[k];
if (p.getOffset() + p.getLength() > offset)
j = k;
else
i = k;
}
return j;
}
/**
* Get context
*
* @param document the document
* @param template the template
* @param offset the offset
* @param length the length
* @return the context
*/
private DocumentTemplateContext getContext(IDocument document, Template template, final int offset, int length) {
DocumentTemplateContext context;
if (template.getContextTypeId().equals(JavaDocContextType.ID)) {
context= new JavaDocContext(getContextTypeRegistry().getContextType(template.getContextTypeId()), document, new Position(offset, length), (ICompilationUnit) EditorUtility
.getEditorInputJavaElement(fJavaEditor, true));
} else {
context= new JavaContext(getContextTypeRegistry().getContextType(template.getContextTypeId()), document, new Position(offset, length), (ICompilationUnit) EditorUtility.getEditorInputJavaElement(
fJavaEditor, true));
}
return context;
}
@Override
protected Region getHoverRegionInternal(final int lineNumber, final int offset) {
recentAnnotationInfo = null;
List<Annotation> annotations = getAnnotations(lineNumber, offset);
for (Annotation annotation : sortBySeverity(annotations)) {
Position position = sourceViewer.getAnnotationModel().getPosition(annotation);
if (position != null) {
final int start = position.getOffset();
return new Region(start, position.getLength());
}
}
return null;
}