Get Roslyn SyntaxToken from Visual Studio Text Selection (caret position)

前端 未结 1 828
栀梦
栀梦 2020-12-18 08:20

I am attempting to bridge between the VSSDK and Roslyn SDK in a Visual Studio extension package and have been having a hard time with this. The ActivePoint.AbsoluteCharOffse

相关标签:
1条回答
  • 2020-12-18 08:28

    I'd highly recommend using Microsoft.VisualStudio.Text.SnapshotPoint from a Microsoft.VisualStudio.Text.Editor.IWpfTextView buffer instead of EnvDTE interfaces to interact with Roslyn.

    Main code may look like this:

    Microsoft.VisualStudio.Text.Editor.IWpfTextView textView =
        GetTextView();
    
    Microsoft.VisualStudio.Text.SnapshotPoint caretPosition =
        textView.Caret.Position.BufferPosition;
    
    Microsoft.CodeAnalysis.Document document =
        caretPosition.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
    
    Microsoft.CodeAnalysis.CSharp.Syntax.InvocationExpressionSyntax invocationExpressionNode = 
        document.GetSyntaxRootAsync().Result.
            FindToken(caretPosition).Parent.AncestorsAndSelf().
            OfType<Microsoft.CodeAnalysis.CSharp.Syntax.InvocationExpressionSyntax>().
            FirstOrDefault();
    

    See Create a typed variable from the current method invocation for a complete example.

    0 讨论(0)
提交回复
热议问题