In general, the infrastructure around analyzers was created to allow them to run outside of Visual Studio (eg. from commandline or as part of a CI build system). This is why there aren't many easy ways to interop between Roslyn and Visual Studio. However there are a few different extension methods that can help you bridge the gap between Visual Studio and Roslyn.
I believe you need to:
- Add the NugetPackage with
Install-Package Microsoft.CodeAnalysis.EditorFeatures.Text
- Add the using
using Microsoft.CodeAnalysis.Text;
to your analyzer
If you have access to a Document
you can use .TryGetText(out SourceText)
to retrieve the SourceText
for a document.
Then you can use the extension method FindCorrespondingEditorTextSnapshot
to get an ITextSnapshot
.
My knowledge here is a little shakey but I'm not sure if you can get an ITextBuffer
because your analyzer will often be running when no editor is opened for a given file so no ITextBuffer
has been created for it.