I am writing an extension to Visual Studio intellisense and would like to get the type of the item just before the cursor in a C# editor.
I currently have a ITextBuffer
which I can use to get the current source file.
I can also get the current position in the editor as below:
var dte = Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider.GetService(typeof(EnvDTE._DTE)) as EnvDTE.DTE;
TextSelection sel = (TextSelection)dte.ActiveDocument.Selection;
However I'm not too sure how to detect the type of the item currently behind the cursor in the editor. I've tried using Roslyn but it seems like this should be a much simpler thing to do than this. Is Roslyn the best tool to do this (via compiling the document and navigating to the correct position in the document) or is there a better way.
Below is my attempt at finding the type of the item using Roslyn:
ITextSnapshot snapshot = m_textBuffer.CurrentSnapshot;
SnapshotPoint? triggerPoint = session.GetTriggerPoint(snapshot);
var tree = SyntaxTree.ParseCompilationUnit(m_textBuffer.CurrentSnapshot.GetText());
var nodes = tree.GetRoot().DescendantNodes();
var element = nodes.Where(n => n.Span.End <= triggerPoint.Value.Position).Last();
var comp = Compilation.Create("test", syntaxTrees: new[] { tree });
var semModel = comp.GetSemanticModel(tree);
//I cant work out what to do here to get the type as the element doesnt seem to be of the required type
var s = semModel.GetTypeInfo((AttributeSyntax)element);
ITextView.Caret.Position
? – SeasonseasonableICompletionSourceProvider
(which doesnt seem to have a ref) but im assuming you get this somehow via a static ref to the editor via WPF? – Branensession.GetTriggerPoint(snapshot);
instead. See here for an example: github.com/leppie/IronScheme.VisualStudio2/blob/master/… – Seasonseasonable