org.eclipse.jface.text.Position Java Examples

The following examples show how to use org.eclipse.jface.text.Position. 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: 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 #2
Source File: ContributionAnnotationManagerTest.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
@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)));
}
 
Example #3
Source File: JsonEditor.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 6 votes vote down vote up
@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;
}
 
Example #4
Source File: ExternalBreakpointWatcher.java    From goclipse with Eclipse Public License 1.0 6 votes vote down vote up
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;
			}
		}
	}
}
 
Example #5
Source File: CodeFoldingSetter.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @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;
}
 
Example #6
Source File: AnnotationWithQuickFixesHover.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@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;
}
 
Example #7
Source File: EditorUtils.java    From typescript.java with MIT License 6 votes vote down vote up
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;
}
 
Example #8
Source File: IndentForTabHandler.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #9
Source File: UnknownElementsIndexerTest.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@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)));
}
 
Example #10
Source File: TexOutlinePage.java    From texlipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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();
        }
    }        
}
 
Example #11
Source File: TexOutlinePage.java    From texlipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #12
Source File: TexOutlineDNDAdapter.java    From texlipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
    * 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;
}
 
Example #13
Source File: ModulaSpellingHover.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #14
Source File: CompilationUnitDocumentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
		}
 
Example #15
Source File: JavaDebugElementCodeMining.java    From jdt-codemining with Eclipse Public License 1.0 5 votes vote down vote up
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);
	}
}
 
Example #16
Source File: CopiedOverviewRuler.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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;
        }
    }
}
 
Example #17
Source File: PyFoldingAction.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @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;
}
 
Example #18
Source File: AbstractFoldingEditor.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
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);
		}
	}
}
 
Example #19
Source File: CppStyleMessageConsole.java    From CppStyle with MIT License 5 votes vote down vote up
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;
}
 
Example #20
Source File: PartitionCodeReader.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example #21
Source File: AnnotationIssueProcessor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@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;
}
 
Example #22
Source File: TemplateEngine.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #23
Source File: AnnotationIssueProcessor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
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);
		}
	}
}
 
Example #24
Source File: EmacsPlusUtils.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #25
Source File: CodeFoldingSetter.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #26
Source File: TLAFastPartitioner.java    From tlaplus with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #27
Source File: CommonReconcilingStrategy.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
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();
}
 
Example #28
Source File: DocumentPartitioner.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #29
Source File: JavaTemplatesPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #30
Source File: AnnotationWithQuickFixesHover.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@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;
}