Visual Studio的文本编辑器扩展 [英] Visual Studio Text Editor Extension

查看:785
本文介绍了Visual Studio的文本编辑器扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图开始在Visual Studio(2010)扩展和我有一个很难找到合适的材料。我有SDK,但是包含的样本似乎是一样的东西装饰器,窗口和图标。

I am trying to get started in Visual Studio (2010) extensions and I am having a hard time finding the right materials. I have the SDK, but the included samples seem to be things like adorners, windows, and icons.

我试图让一个扩展,将直接与文本编辑器的工作(按字母顺序排列所有的方法名中的一类,或使所有的常量名的大写例如),但我找不到这种类型的功能,甚至教程演示。

I am trying to make an extension that will work directly with the text editor (to alphabetize all of my method names in a class, or make all constant names upper case for example) but I can't find a demo for this type of functionality, or even a tutorial.

有谁知道在哪里可以找到这种东西?

Does anyone know where I can find this kind of stuff?

推荐答案

我有相同的问题,现在已经浏览网页好几个小时,直到我能够理解并解释你需要如何做起了这样的一个扩展。

I had the exact same question and now have browsed the web several hours until I was being able to understand and explain how you'd need to start with such an extension.

在我下面的例子中,我们将创建一个小又哑的扩展,它总是你好添加到代码文件的开头,当编辑已经取得进展。 。这是非常基本的,但应该给你一个想法如何继续开发这件事情

In my following example we will create a small and dumb extension which will always add "Hello" to the beginning of a code file when an edit has been made. It's very basic but should give you an idea how to continue developing this thing.

被警告:你必须完全解析你自己的代码文件 - Visual Studio的不让你在何处类,方法或什么,以及它们所包含内容的任何信息。这是做一个代码格式化工具时要采取的最大的障碍,并不会在这个答案范围之内。[*]

Be warned: You have to parse the code files completely on your own - Visual Studio does not give you any information about where classes, methods or whatever are and what they contain. That's the biggest hurdle to be taken when doing a code formatting tool and will not be covered in this answer.[*]

对于那些谁跳过这个答案,要确保你下载并安装了Visual Studio的SDK第一或你不会找到在第一步中提到的项目类型。

For those who skipped to this answer, make sure you downloaded and installed the Visual Studio SDK first or you will not find the project type mentioned in step one.

创建项目


  1. 开始用,如果你选择了.NET Framework 4的创造型的Visual C#>扩展> VSIX项目(唯一可见的一个新项目作为目标框架)。的请注意,您可能需要选择得到它的工作编辑分类项目类型,而不是VSIX项目型,S。下面发表评论。

该项目已被创建后,source.extension.vsixmanifest文件将被打开,给你的能力,成立了产品名称,作者,版本,描述,图标等。我觉得这一步是相当自我解释,你现在可以关闭选项卡,后来打开vsixmanifest文件进行恢复。

After the project has been created, the "source.extension.vsixmanifest" file will be opened, giving you the ability to set up product name, author, version, description, icon and so on. I think this step is pretty self-explaining, you can close the tab now and restore it later by opening the vsixmanifest file.

创建一个监听器类,以收到通知的文本编辑器实例作品

接下来,我们需要倾听每当一个文本编辑器已创建在Visual Studio和约束我们的代码格式化工具吧。在VS2010的文本编辑器是 IWpfTextView 的一个实例。

Next, we need to listen whenever a text editor has been created in Visual Studio and bind our code formatting tool to it. A text editor in VS2010 is an instance of IWpfTextView.


  1. 添加一个新的类到我们的项目并将其命名为 TextViewCreationListener 。这个类必须实现 Microsoft.VisualStudio.Text.Editor.IWpfTextViewCreationListener 接口。你需要一个参考的 Microsoft.VisualStudio.Text.UI.Wpf 的添加到项目中。该组件DLL在您的Visual Studio SDK目录下发现的 VisualStudioIntegration\Common\Assemblies\v4.0

  1. Add a new class to our project and name it TextViewCreationListener. This class has to implement the Microsoft.VisualStudio.Text.Editor.IWpfTextViewCreationListener interface. You need to add a reference to Microsoft.VisualStudio.Text.UI.Wpf to your project. The assembly DLL is found in your Visual Studio SDK directory under VisualStudioIntegration\Common\Assemblies\v4.0.

你必须实现该接口的 TextViewCreated 方法。这种方法有一个参数,指定已创建的文本编辑器的实例。我们将创建此实例传递给后一个新的代码格式化类。

You have to implement the TextViewCreated method of the interface. This method has a parameter specifying the instance of the text editor which has been created. We will create a new code formatting class which this instance is passed to later on.

我们需要让 TextViewCreationListener 类到Visual Studio可见通过指定属性 [导出(typeof运算(IWpfTextViewCreationListener))] 。添加一个引用到的 System.ComponentModel.Composition 的到你的项目的导出属性。

We need to make the TextViewCreationListener class visible to Visual Studio by specifying the attribute [Export(typeof(IWpfTextViewCreationListener))]. Add a reference to System.ComponentModel.Composition to your project for the Export attribute.

此外,我们需要指定的代码格式化应该绑定到文本编辑器的文件类型。我们只喜欢格式化代码文件,而不是纯文本文件,所以我们的属性 [ContentType的(准则)] 添加到监听器类。你有一个参考的 Microsoft.VisualStudio.CoreUtility 的添加到您的项目这一点。

Additionally, we need to specify with which types of files the code formatter should be bound to the text editor. We only like to format code files and not plain text files, so we add the attribute [ContentType("code")] to the listener class. You have to add a reference to Microsoft.VisualStudio.CoreUtility to your project for this.

另外,我们只希望更改可编辑的代码,而不是周围的颜色或装饰(如被看见在示例项目),所以我们的属性 [TextViewRole(PredefinedTextViewRoles.Editable)] 添加到类。同样,你需要一个新的参考,这时候的 Microsoft.VisualStudio.Text.UI

Also, we only want to change editable code and not the colors or adornments around it (as seen in the example projects), so we add the attribute [TextViewRole(PredefinedTextViewRoles.Editable)] to the class. Again you need a new reference, this time to Microsoft.VisualStudio.Text.UI.

标记为内部密封类。至少这是我的建议。现在,你的类应该类似于此:

Mark the class as internal sealed. At least that's my recommendation. Now your class should look similar to this:

[ContentType("code")]
[Export(typeof(IWpfTextViewCreationListener))]
[TextViewRole(PredefinedTextViewRoles.Editable)]
internal sealed class TextViewCreationListener : IWpfTextViewCreationListener
{
    public void TextViewCreated(IWpfTextView textView)
    {
    }
}


创建代码格式化类

接下来,我们需要一个类处理代码格式逻辑,排序方式等。再次,在这个例子中,将简单的你好添加到每当编辑已经取得的文件的开始

Next, we need a class handling the code formatting logic, sorting methods and so on. Again, in this example it will simply add "Hello" to the start of the file whenever an edit has been made.

添加一个名为新类格式化到项目中。

  1. Add a new class called Formatter to your project.

添加一个构造函数,需要一个 IWpfTextView 参数。请记住,我们要创建的编辑器实例传递给我们的监听器类的 TextViewCreated 方法,这种格式类(只需添加新的格式化程序(的TextView); 来那里的方法)。

Add a constructor which takes one IWpfTextView argument. Remember that we wanted to pass the created editor instance to this formatting class in the TextViewCreated method of our listener class (simply add new Formatter(textView); to the method there).

保存通过实例的成员变量。后来格式化代码时(例如用于检索的插入位置),它会变得得心应手。还绑了更改 PostChanged 事件的 TextBuffer 编辑器实例的属性:

Save the passed instance in a member variable. It'll become handy when formatting the code later on (e.g. for retrieving the caret position). Also tie up the Changed and PostChanged events of the TextBuffer property of the editor instance:

public Formatter(IWpfTextView view)
{
    _view = view;
    _view.TextBuffer.Changed += new EventHandler<TextContentChangedEventArgs>(TextBuffer_Changed);
    _view.TextBuffer.PostChanged += new EventHandler(TextBuffer_PostChanged);
}


  • 更改事件被称为每次编辑已取得时间(如输入一个字符,粘贴代码或修改的程序化)。因为它也反作用于的程序化的变化我用一个bool确定我们的扩展或用户/别的此刻更改代码,只叫我的自定义 FormatCode()方法如果我们的扩展尚未进行编辑。否则,你会递归调用此方法将导致程序崩溃的Visual Studio:

  • The Changed event is called every time an edit has been made (e.g. typing a char, pasting code or programmatical changes). Because it also reacts on programmatical changes I use a bool determining if our extension or the user / anything else is changing the code at the moment and call my custom FormatCode() method only if our extension is not already editing. Otherwise you'll recursively call this method which would crash Visual Studio:

    private void TextBuffer_Changed(object sender, TextContentChangedEventArgs e)
    {
        if (!_isChangingText)
        {
            _isChangingText = true;
            FormatCode(e);
        }
    }
    


  • 我们必须重置这个布尔成员变量在 PostChanged 事件处理程序再次

    让我们打发更改事件的事件参数来我们自定义的 FormatCode 方法,因为它们包含了什么的变化最后的编辑,现在。这些编辑存储在阵列中的 e.Changes 的类型 INormalizedTextChangeCollection (S,在年底的联系我张贴有关此类型的详细信息)。我们遍历所有这些修改和调用我们自定义的 HandleChange 方法与此编辑产生了新的文本。

    Let's pass the event args of the Changed event to our custom FormatCode method because they contain what has changed between the last edit and now. Those edits are stored in the array e.Changes of the type INormalizedTextChangeCollection (s. the link at the end of my post for more information about this type). We loop through all those edits and call our custom HandleChange method with the new text which this edit has produced.

    private void FormatCode(TextContentChangedEventArgs e)
    {
        if (e.Changes != null)
        {
            for (int i = 0; i < e.Changes.Count; i++)
            {
                HandleChange(e.Changes[0].NewText);
            }
        }
    }
    


  • HandleChange 方法,我们实际上可以扫描关键字来处理这些以特定的方式(请记住,你必须分析你自己的代码!) - 但在这里,我们只是默默地加上你好到用于测试目的的文件的开始。例如。我们必须改变我们的编辑器实例的 TextBuffer 。要做到这一点,我们需要创建一个 ITextEdit 对象,使我们可以操纵的文本,并应用它的变化之后。该代码是相当自我解释:

  • In the HandleChange method we could actually scan for keywords to handle those in a specific way (remember, you have to parse any code on yourself!) - but here we just dumbly add "Hello" to the start of the file for testing purposes. E.g. we have to change the TextBuffer of our editor instance. To do so, we need to create an ITextEdit object with which we can manipulate text and apply it's changes afterwards. The code is pretty self-explaining:

    private void HandleChange(string newText)
    {
        ITextEdit edit = _view.TextBuffer.CreateEdit();
        edit.Insert(0, "Hello");
        edit.Apply();
    }
    


  • 在编写本加-in,Visual Studio中的一个实验蜂巢启动时,只有我们的扩展加载。创建一个新的C#文件,并开始键入看到的结果。

    When compiling this add-in, an experimental hive of Visual Studio starts up with only our extension loaded. Create a new C# file and start typing to see the results.

    我希望这给你一些想法如何继续这个话题。我现在去探索它自己。

    I hope this gives you some ideas how to continue in this topic. I have to explore it myself now.

    我强烈建议在MSDN上编辑的文本模式的文档,以获得有关你怎么可以做这做那的提示。
    http://msdn.microsoft.com/en-us/library/dd885240。 ASPX#textmodel

    I highly recommend the documentation of the text model of the editor on MSDN to get hints about how you could do this and that. http://msdn.microsoft.com/en-us/library/dd885240.aspx#textmodel

    脚注

    [*]注意的Visual Studio 2015配备了Rosyln编译器平台,这的确已经分析了C#和VB.NET文件,你(及其他可能预安装的语言太),并暴露了他们的层次语法结构,但我不是专家本主题中尚未就如何使用这些新服务的一个答案。作为反正在该答案描述开始编辑延伸的基本进展保持不变。注意 - 如果你使用这些服务 - 你将成为依赖于Visual Studio的2015年,和扩展将不会在较早版本的工作。

    [*] Note that Visual Studio 2015 comes with the Rosyln Compiler Platform, which indeed already analyzes C# and VB.NET files for you (and probably other pre-installed languages too) and exposes their hierarchical syntactical structure, but I'm not an expert in this topic yet to give an answer on how to use these new services. The basic progress of starting an editor extension stays the same as described in this answer anyway. Be aware that - if you use these services - you will become dependent on Visual Studio 2015, and the extension will not work in earlier versions.

    这篇关于Visual Studio的文本编辑器扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆