繁体   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