Jim Orcheson Jim Orcheson - 1 month ago 7
C# Question

How do I retrieve text from the Visual Studio editor for use with Roslyn SyntaxTree?

I am attempting to write a Visual Studio extension that will analyze the C# code displayed in the editor and possibly update the code based on what I find. This would be on demand (via a menu item), and not using an analyzer and code fix.

There are a number of examples and samples on the Internet, but they all start either with the source code hard-coded in the samples, or create a new document, or look at each file in the VS solution that is open. How do I access the source code from the active editor window?

Answer Source

In a comment to my original question, @SJP gave a link to @Frank Bakker's answer to the question at Calling Roslyn from VSIX Command. This does work as outlined.

@JoshVarty provided a hint of the direction to go in his answer above. I combined that with code provided by @user1912383 for how to get an IWpfTextView answering the question Find an IVsTextView or IWpfTextView for a given ProjectItem, in 2010 RC extension. Here is the code I came up with:

var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));
var textManager = (IVsTextManager)Package.GetGlobalService(typeof(SVsTextManager));
IVsTextView activeView = null;
ErrorHandler.ThrowOnFailure(textManager.GetActiveView(1, null, out activeView));
var editorAdapter = componentModel.GetService<IVsEditorAdaptersFactoryService>();
var textView = editorAdapter.GetWpfTextView(activeView);
var document  = Extensions.GetRelatedDocuments(textView.TextBuffer).FirstOrDefault();

In a comment after @user1912383's code mentioned above, @kman mentioned that this does not work for document types such as .sql files. It does, however, work for .cs files which is what I will be using it with.