What event will be raised, if the current shown texteditor is changed

228 views Asked by At

I am coding a Visual Studio extension in Visual Studio 2019, that should show lightbulbs with code suggestions out of a .xml file.

My current problem is, I can't find an event that gets raised if the currently shown text-editors (.cs) files are changing. I would be glad if someone knows a tutorial or could tell me how and where I need to call the event and how does it trigger.

2

There are 2 answers

0
Monie On BEST ANSWER

Solved it with the ITagger.

internal class TodoTagger : ITagger<TodoTag>
{
    private IClassifier m_classifier;
    private const string m_searchText = "todo";

    internal TodoTagger(IClassifier classifier)
    {
        m_classifier = classifier;
    }

    IEnumerable<ITagSpan<TodoTag>> ITagger<TodoTag>.GetTags(NormalizedSnapshotSpanCollection spans)
    {
        foreach (SnapshotSpan span in spans)
        {
            //look at each classification span \
            foreach (ClassificationSpan classification in m_classifier.GetClassificationSpans(span))
            {
                //if the classification is a comment
                if (classification.ClassificationType.Classification.ToLower().Contains("comment"))
                {
                    //if the word "todo" is in the comment,
                    //create a new TodoTag TagSpan
                    int index = classification.Span.GetText().ToLower().IndexOf(m_searchText);
                    if (index != -1)
                    {
                        yield return new TagSpan<TodoTag>(new SnapshotSpan(classification.Span.Start + index, m_searchText.Length), new TodoTag());
                    }
                }
            }
        }
    }

    public event EventHandler<SnapshotSpanEventArgs> TagsChanged;
}


[Export(typeof(ITaggerProvider))]
[ContentType("code")]
[TagType(typeof(TodoTag))]
class TodoTaggerProvider : ITaggerProvider
{
    [Import]
    internal IClassifierAggregatorService AggregatorService;

    public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag
    {
        if (buffer == null)
        {
            throw new ArgumentNullException("buffer");
        }

        return new TodoTagger(AggregatorService.GetClassifier(buffer)) as ITagger<T>;
    }
}
1
Matze On

You´re probably looking for examples of the analyzer and code-fix functionality. You can find a lightbulb example on GitHub; of course, it targets Visual Studio 2017, but should also work for a newer version. For instance, see https://github.com/microsoft/VSSDK-Extensibility-Samples/tree/master/LightBulb

As you can see in the example project is that you would need an ISuggestedActionsSourceProvider, an ISuggestedActionsSource, and at least one ISuggestedAction implementation that will perform the suggested fix.