簡體   English   中英

如何從 Visual Studio 編輯器中檢索文本以與 Roslyn SyntaxTree 一起使用?

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

我正在嘗試編寫一個 Visual Studio 擴展來分析編輯器中顯示的 C# 代碼,並可能根據我發現的內容更新代碼。 這將是按需(通過菜單項),而不是使用分析器和代碼修復。

網上有很多示例和示例,但它們都是從示例中硬編碼的源代碼開始,或者創建一個新文檔,或者查看打開的VS解決方案中的每個文件。 如何從活動編輯器窗口訪問源代碼?

首先,您需要安裝Microsoft.CodeAnalysis.EditorFeatures.Text包。

然后你需要添加適當的 using 語句:

 using Microsoft.CodeAnalysis.Text;

現在,您可以使用此處找到的擴展方法在 Visual Studio 概念( ITextSnapshotITextBuffer等)和 Roslyn 概念( DocumentSourceText等)之間進行映射: https : //github.com/dotnet/roslyn/blob/master/src/ EditorFeatures/Text/Extensions.cs

例如:

ITextSnapshot snapshot = ... //Get this from Visual Studio
var documents = snapshot.GetRelatedDocuments(); //There may be more than one

在對我的原始問題的評論中,@SJP 提供了一個鏈接,指向@Frank Bakker 在Calling Roslyn from VSIX Command 中對問題的回答。 這確實如概述的那樣工作。

@JoshVarty 在上面的回答中提供了方向的提示。 我將其與@user1912383 提供的代碼結合起來,了解如何在 2010 RC 擴展中獲得 IWpfTextView回答問題Find an IVsTextView or IWpfTextView for a given ProjectItem 這是我想出的代碼:

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  = (textView.TextBuffer.ContentType.TypeName.Equals("CSharp"))
            ? textView : null;

在@user1912383 上面提到的代碼之后的評論中,@kman 提到這不適用於 .sql 文件等文檔類型。 但是,它確實適用於我將使用它的 .cs 文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM