Java Code Examples for org.eclipse.jface.text.source.IAnnotationModel#addAnnotation()

The following examples show how to use org.eclipse.jface.text.source.IAnnotationModel#addAnnotation() . 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: AnnotationModelHelper.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Removes annotations and replaces them in one step.
 *
 * @param model The {@link IAnnotationModel} that should be cleaned.
 * @param annotationsToRemove The annotations to remove.
 * @param annotationsToAdd The annotations to add.
 */
public void replaceAnnotationsInModel(
    IAnnotationModel model,
    Collection<? extends Annotation> annotationsToRemove,
    Map<? extends Annotation, Position> annotationsToAdd) {

  if (model instanceof IAnnotationModelExtension) {
    IAnnotationModelExtension extension = (IAnnotationModelExtension) model;
    extension.replaceAnnotations(
        annotationsToRemove.toArray(new Annotation[annotationsToRemove.size()]),
        annotationsToAdd);
  } else {
    if (log.isTraceEnabled())
      log.trace("AnnotationModel " + model + " does not support IAnnotationModelExtension");

    for (Annotation annotation : annotationsToRemove) {
      model.removeAnnotation(annotation);
    }

    for (Entry<? extends Annotation, Position> entry : annotationsToAdd.entrySet()) {
      model.addAnnotation(entry.getKey(), entry.getValue());
    }
  }
}
 
Example 2
Source File: TexlipseAnnotationUpdater.java    From texlipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new annotation
 * @param r The IRegion which should be highlighted
 * @param annString The name of the annotation (not important)
 * @param model The AnnotationModel
 */
private void createNewAnnotation(IRegion r, String annString, IAnnotationModel model) {
        Annotation annotation= new Annotation(ANNOTATION_TYPE, false, annString);
        Position position= new Position(r.getOffset(), r.getLength());
        model.addAnnotation(annotation, position);
        fOldAnnotations.add(annotation);
}
 
Example 3
Source File: DefineFoldingRegionAction.java    From tlaplus with MIT License 5 votes vote down vote up
public void run()
{
    ITextEditor editor = getTextEditor();
    ISelection selection = editor.getSelectionProvider().getSelection();
    if (selection instanceof ITextSelection)
    {
        ITextSelection textSelection = (ITextSelection) selection;
        if (textSelection.getLength() != 0)
        {
            IAnnotationModel model = getAnnotationModel(editor);
            if (model != null)
            {

                int start = textSelection.getStartLine();
                int end = textSelection.getEndLine();

                try
                {
                    IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());
                    int offset = document.getLineOffset(start);
                    int endOffset = document.getLineOffset(end + 1);
                    Position position = new Position(offset, endOffset - offset);
                    model.addAnnotation(new ProjectionAnnotation(), position);
                } catch (BadLocationException x)
                {
                    // ignore
                }
            }
        }
    }
}
 
Example 4
Source File: QuickAssistLightBulbUpdater.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void calculateLightBulb(IAnnotationModel model, IInvocationContext context) {
	boolean needsAnnotation= JavaCorrectionProcessor.hasAssists(context);
	if (fIsAnnotationShown) {
		model.removeAnnotation(fAnnotation);
	}
	if (needsAnnotation) {
		model.addAnnotation(fAnnotation, new Position(context.getSelectionOffset(), context.getSelectionLength()));
	}
	fIsAnnotationShown= needsAnnotation;
}
 
Example 5
Source File: TypeScriptEditor.java    From typescript.java with MIT License 4 votes vote down vote up
public IStatus run(IProgressMonitor progressMonitor) {
	fProgressMonitor = progressMonitor;

	if (isCanceled()) {
		if (LinkedModeModel.hasInstalledModel(fDocument)) {
			// Template completion applied, remove occurrences
			removeOccurrenceAnnotations();
		}
		return Status.CANCEL_STATUS;
	}
	ITextViewer textViewer = getViewer();
	if (textViewer == null)
		return Status.CANCEL_STATUS;

	IDocument document = textViewer.getDocument();
	if (document == null)
		return Status.CANCEL_STATUS;

	IAnnotationModel annotationModel = getAnnotationModel();
	if (annotationModel == null)
		return Status.CANCEL_STATUS;

	// Add occurrence annotations
	int length = fPositions.length;
	Map annotationMap = new HashMap(length);
	for (int i = 0; i < length; i++) {

		if (isCanceled())
			return Status.CANCEL_STATUS;

		String message;
		Position position = fPositions[i];

		// Create & add annotation
		try {
			message = document.get(position.offset, position.length);
		} catch (BadLocationException ex) {
			// Skip this match
			continue;
		}
		annotationMap.put(new Annotation("org.eclipse.wst.jsdt.ui.occurrences", false, message), //$NON-NLS-1$
				position);
	}

	if (isCanceled())
		return Status.CANCEL_STATUS;

	synchronized (getLockObject(annotationModel)) {
		if (annotationModel instanceof IAnnotationModelExtension) {
			((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations,
					annotationMap);
		} else {
			removeOccurrenceAnnotations();
			Iterator iter = annotationMap.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry mapEntry = (Map.Entry) iter.next();
				annotationModel.addAnnotation((Annotation) mapEntry.getKey(), (Position) mapEntry.getValue());
			}
		}
		fOccurrenceAnnotations = (Annotation[]) annotationMap.keySet()
				.toArray(new Annotation[annotationMap.keySet().size()]);
	}

	return Status.OK_STATUS;
}
 
Example 6
Source File: XMLEditor.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Given the offset, tries to determine if we're on an HTML close/start tag, and if so it will find the matching
 * open/close and highlight the pair.
 * 
 * @param offset
 */
private void highlightTagPair(int offset)
{
	IDocumentProvider documentProvider = getDocumentProvider();
	if (documentProvider == null)
	{
		return;
	}
	IAnnotationModel annotationModel = documentProvider.getAnnotationModel(getEditorInput());
	if (annotationModel == null)
	{
		return;
	}

	if (fTagPairOccurrences != null)
	{
		// if the offset is included by one of these two positions, we don't need to wipe and re-calculate!
		for (Position pos : fTagPairOccurrences.values())
		{
			if (pos.includes(offset))
			{
				return;
			}
		}
		// New position, wipe the existing annotations in preparation for re-calculating...
		for (Annotation a : fTagPairOccurrences.keySet())
		{
			annotationModel.removeAnnotation(a);
		}
		fTagPairOccurrences = null;
	}

	// Calculate current pair
	Map<Annotation, Position> occurrences = new HashMap<Annotation, Position>();
	IDocument document = getSourceViewer().getDocument();

	IParseNode node = getASTNodeAt(offset, getAST());
	if (node instanceof XMLElementNode)
	{
		XMLElementNode en = (XMLElementNode) node;
		if (!en.isSelfClosing())
		{
			IRegion match = TagUtil.findMatchingTag(document, offset, tagPartitions);
			if (match != null)
			{
				// TODO Compare versus last positions, if they're the same don't wipe out the old ones and add new
				// ones!
				occurrences.put(new Annotation(IXMLEditorConstants.TAG_PAIR_OCCURRENCE_ID, false, null),
						new Position(match.getOffset(), match.getLength()));

				try
				{
					// The current tag we're in!
					ITypedRegion partition = document.getPartition(offset);
					occurrences.put(new Annotation(IXMLEditorConstants.TAG_PAIR_OCCURRENCE_ID, false, null),
							new Position(partition.getOffset(), partition.getLength()));
				}
				catch (BadLocationException e)
				{
					IdeLog.logError(XMLPlugin.getDefault(), e);
				}
				for (Map.Entry<Annotation, Position> entry : occurrences.entrySet())
				{
					annotationModel.addAnnotation(entry.getKey(), entry.getValue());
				}
				fTagPairOccurrences = occurrences;
				return;
			}
		}
	}
	// no new pair, so don't highlight anything
	fTagPairOccurrences = null;
}
 
Example 7
Source File: HTMLEditor.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Given the offset, tries to determine if we're on an HTML close/start tag, and if so it will find the matching
 * open/close and highlight the pair.
 * 
 * @param offset
 */
private void highlightTagPair(int offset)
{
	IDocumentProvider documentProvider = getDocumentProvider();
	if (documentProvider == null)
	{
		return;
	}
	IAnnotationModel annotationModel = documentProvider.getAnnotationModel(getEditorInput());
	if (annotationModel == null)
	{
		return;
	}

	if (fTagPairOccurrences != null)
	{
		// if the offset is included by one of these two positions, we don't need to wipe and re-calculate!
		for (Position pos : fTagPairOccurrences.values())
		{
			if (pos.includes(offset))
			{
				return;
			}
		}
		// New position, wipe the existing annotations in preparation for re-calculating...
		for (Annotation a : fTagPairOccurrences.keySet())
		{
			annotationModel.removeAnnotation(a);
		}
		fTagPairOccurrences = null;
	}

	// Calculate current pair
	Map<Annotation, Position> occurrences = new HashMap<Annotation, Position>();
	IDocument document = getSourceViewer().getDocument();
	IRegion match = TagUtil.findMatchingTag(document, offset, tagPartitions);
	if (match != null)
	{
		// TODO Compare versus last positions, if they're the same don't wipe out the old ones and add new ones!
		occurrences.put(new Annotation(IHTMLConstants.TAG_PAIR_OCCURRENCE_ID, false, null),
				new Position(match.getOffset(), match.getLength()));

		try
		{
			// The current tag we're in!
			ITypedRegion partition = document.getPartition(offset);
			occurrences.put(new Annotation(IHTMLConstants.TAG_PAIR_OCCURRENCE_ID, false, null), new Position(
					partition.getOffset(), partition.getLength()));
		}
		catch (BadLocationException e)
		{
			IdeLog.logError(HTMLPlugin.getDefault(), e);
		}
		for (Map.Entry<Annotation, Position> entry : occurrences.entrySet())
		{
			annotationModel.addAnnotation(entry.getKey(), entry.getValue());
		}
		fTagPairOccurrences = occurrences;
	}
	else
	{
		// no new pair, so don't highlight anything
		fTagPairOccurrences = null;
	}
}
 
Example 8
Source File: JavaEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public IStatus run(IProgressMonitor progressMonitor) {
	if (isCanceled(progressMonitor))
		return Status.CANCEL_STATUS;

	ITextViewer textViewer= getViewer();
	if (textViewer == null)
		return Status.CANCEL_STATUS;

	IDocument document= textViewer.getDocument();
	if (document == null)
		return Status.CANCEL_STATUS;

	IDocumentProvider documentProvider= getDocumentProvider();
	if (documentProvider == null)
		return Status.CANCEL_STATUS;

	IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
	if (annotationModel == null)
		return Status.CANCEL_STATUS;

	// Add occurrence annotations
	int length= fLocations.length;
	Map<Annotation, Position> annotationMap= new HashMap<Annotation, Position>(length);
	for (int i= 0; i < length; i++) {

		if (isCanceled(progressMonitor))
			return Status.CANCEL_STATUS;

		OccurrenceLocation location= fLocations[i];
		Position position= new Position(location.getOffset(), location.getLength());

		String description= location.getDescription();
		String annotationType= (location.getFlags() == IOccurrencesFinder.F_WRITE_OCCURRENCE) ? "org.eclipse.jdt.ui.occurrences.write" : "org.eclipse.jdt.ui.occurrences"; //$NON-NLS-1$ //$NON-NLS-2$

		annotationMap.put(new Annotation(annotationType, false, description), position);
	}

	if (isCanceled(progressMonitor))
		return Status.CANCEL_STATUS;

	synchronized (getLockObject(annotationModel)) {
		if (annotationModel instanceof IAnnotationModelExtension) {
			((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
		} else {
			removeOccurrenceAnnotations();
			Iterator<Entry<Annotation, Position>> iter= annotationMap.entrySet().iterator();
			while (iter.hasNext()) {
				Entry<Annotation, Position> mapEntry= iter.next();
				annotationModel.addAnnotation(mapEntry.getKey(), mapEntry.getValue());
			}
		}
		fOccurrenceAnnotations= annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
	}

	return Status.OK_STATUS;
}
 
Example 9
Source File: ScriptValidator.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Validates the current script, and selects the error if the specified falg
 * is <code>true</code>.
 * 
 * @param isFunctionBody
 *            <code>true</code> if a function body is validated,
 *            <code>false</code> otherwise.
 * @param isErrorSelected
 *            <code>true</code> if error will be selected after
 *            validating, <code>false</code> otherwise.
 * @throws ParseException
 *             if an syntax error is found.
 */
public void validate( boolean isFunctionBody, boolean isErrorSelected )
		throws ParseException
{
	if ( scriptViewer == null )
	{
		return;
	}

	clearAnnotations( );

	StyledText textField = scriptViewer.getTextWidget( );

	if ( textField == null || !textField.isEnabled( ) )
	{
		return;
	}

	String functionTag = "function(){"; //$NON-NLS-1$
	IDocument document = scriptViewer.getDocument( );
	String text = document == null ? null : scriptViewer.getDocument( )
			.get( );

	String script = text;

	if ( isFunctionBody )
	{
		script = functionTag + script + "\n}"; //$NON-NLS-1$
	}

	try
	{
		validateScript( script );
	}
	catch ( ParseException e )
	{
		int offset = e.getErrorOffset( );

		if ( isFunctionBody )
		{
			offset -= functionTag.length( );
			while ( offset >= text.length( ) )
			{
				offset--;
			}
		}

		String errorMessage = e.getLocalizedMessage( );
		Position position = getErrorPosition( text, offset );

		if ( position != null )
		{
			IAnnotationModel annotationModel = scriptViewer.getAnnotationModel( );

			if ( annotationModel != null )
			{
				annotationModel.addAnnotation( new Annotation( IReportGraphicConstants.ANNOTATION_ERROR,
						true,
						errorMessage ),
						position );
			}
			if ( isErrorSelected )
			{
				if ( scriptViewer instanceof SourceViewer )
				{
					( (SourceViewer) scriptViewer ).setSelection( new TextSelection( position.getOffset( ),
							position.getLength( ) ) );
				}
				scriptViewer.revealRange( position.getOffset( ),
						position.getLength( ) );
			}
		}
		throw new ParseException( e.getLocalizedMessage( ), position.offset );
	}
}