Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Visual Studio Add-in for testing regular expressions

, 1 Dec 2010
An add-in for debugging and creating regular expression directly in Visual Studio
��using System;

using Extensibility;

using EnvDTE;

using EnvDTE80;

using Microsoft.VisualStudio.CommandBars;

using System.Resources;

using System.Reflection;

using System.Globalization;

using System.Windows.Forms;

using System.IO;

using System.Text.RegularExpressions;

using System.Collections.Generic;

using RegexTester.Parsing.VB;

using RegexTester.Parsing.CSharp;



namespace RegexTester

{

    /// <summary>The object for implementing an Add-in.</summary>

    /// <seealso class='IDTExtensibility2' />

    public class Connect : IDTExtensibility2, IDTCommandTarget

    {

        /// <summary>Implements the constructor for the Add-in object. Place your initialization code within this method.</summary>

        public Connect()

        {



        }



        /// <summary>Implements the OnConnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being loaded.</summary>

        /// <param term='application'>Root object of the host application.</param>

        /// <param term='connectMode'>Describes how the Add-in is being loaded.</param>

        /// <param term='addInInst'>Object representing this Add-in.</param>

        /// <seealso class='IDTExtensibility2' />

        public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)

        {

            _applicationObject = (DTE2)application;

            _addInInstance = (AddIn)addInInst;

            new RegexFinder();

            if (connectMode == ext_ConnectMode.ext_cm_UISetup)

            {

                object[] contextGUIDS = new object[] { };

                Commands2 commands = (Commands2)_applicationObject.Commands;



                Microsoft.VisualStudio.CommandBars.CommandBar editContextCommandBar =

                    ((Microsoft.VisualStudio.CommandBars.CommandBars)_applicationObject.CommandBars)["Editor Context Menus"];



                CommandBarPopup toolsPopup = (CommandBarPopup)editContextCommandBar.Controls["Code Window"];



                try

                {

                    //Add a command to the Commands collection:

                    Command command = commands.AddNamedCommand2(_addInInstance, "RegexTester",

                        "Test regular expression",

                        "Test regular expression",

                        true,

                        59,

                        ref contextGUIDS,

                        (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled,

                        (int)vsCommandStyle.vsCommandStyleText,

                        vsCommandControlType.vsCommandControlTypeButton);

                    command.Bindings = "Text Editor::Ctrl+r, Ctrl+x";

                    if (command != null && toolsPopup != null && toolsPopup.CommandBar != null)

                    {

                        command.AddControl(toolsPopup.CommandBar, 1);

                    }

                }

                catch (System.ArgumentException)

                {

                    //If we are here, then the exception is probably because a command with that name

                    //  already exists. If so there is no need to recreate the command and we can 

                    //  safely ignore the exception.

                }

            }

        }



        /// <summary>Implements the OnDisconnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being unloaded.</summary>

        /// <param term='disconnectMode'>Describes how the Add-in is being unloaded.</param>

        /// <param term='custom'>Array of parameters that are host application specific.</param>

        /// <seealso class='IDTExtensibility2' />

        public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom)

        {

        }



        /// <summary>Implements the OnAddInsUpdate method of the IDTExtensibility2 interface. Receives notification when the collection of Add-ins has changed.</summary>

        /// <param term='custom'>Array of parameters that are host application specific.</param>

        /// <seealso class='IDTExtensibility2' />		

        public void OnAddInsUpdate(ref Array custom)

        {

        }



        /// <summary>Implements the OnStartupComplete method of the IDTExtensibility2 interface. Receives notification that the host application has completed loading.</summary>

        /// <param term='custom'>Array of parameters that are host application specific.</param>

        /// <seealso class='IDTExtensibility2' />

        public void OnStartupComplete(ref Array custom)

        {

        }



        /// <summary>Implements the OnBeginShutdown method of the IDTExtensibility2 interface. Receives notification that the host application is being unloaded.</summary>

        /// <param term='custom'>Array of parameters that are host application specific.</param>

        /// <seealso class='IDTExtensibility2' />

        public void OnBeginShutdown(ref Array custom)

        {

        }



        /// <summary>Implements the QueryStatus method of the IDTCommandTarget interface. This is called when the command's availability is updated</summary>

        /// <param term='commandName'>The name of the command to determine state for.</param>

        /// <param term='neededText'>Text that is needed for the command.</param>

        /// <param term='status'>The state of the command in the user interface.</param>

        /// <param term='commandText'>Text requested by the neededText parameter.</param>

        /// <seealso class='Exec' />

        public void QueryStatus(string commandName, vsCommandStatusTextWanted neededText, ref vsCommandStatus status, ref object commandText)

        {

            if (neededText == vsCommandStatusTextWanted.vsCommandStatusTextWantedNone)

            {

                if (commandName == "RegexTester.Connect.RegexTester")

                {

                    status = vsCommandStatus.vsCommandStatusSupported | vsCommandStatus.vsCommandStatusEnabled;

                    if (_applicationObject.ActiveDocument != null &&

                        !string.IsNullOrEmpty((_applicationObject.ActiveDocument.Object() as TextDocument).Selection.Text))

                    {

                        status |= vsCommandStatus.vsCommandStatusEnabled;

                    }

                }

            }

        }



        /// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary>

        /// <param term='commandName'>The name of the command to execute.</param>

        /// <param term='executeOption'>Describes how the command should be run.</param>

        /// <param term='varIn'>Parameters passed from the caller to the command handler.</param>

        /// <param term='varOut'>Parameters passed from the command handler to the caller.</param>

        /// <param term='handled'>Informs the caller if the command was handled or not.</param>

        /// <seealso class='Exec' />

        public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)

        {

            handled = false;

            if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)

            {

                if (commandName == "RegexTester.Connect.RegexTester")

                {

                    TextDocument doc = (_applicationObject.ActiveDocument.Object() as TextDocument);

                    RegexFinder regexFinder = null;

                    if (_applicationObject.ActiveDocument.ProjectItem.ContainingProject.CodeModel.Language == EnvDTE.CodeModelLanguageConstants.vsCMLanguageVB)

                    {

                        regexFinder = new RegexFinder(new VBRegexFormatProvider());

                    }

                    else

                    {

                        regexFinder = new RegexFinder(new CSharpRegexFormatProvider());

                    }

                    EditPoint startPoint = doc.Selection.TopPoint.CreateEditPoint();

                    EditPoint endPoint = doc.Selection.BottomPoint.CreateEditPoint();

                    IRegexFindResults regexFindResults = regexFinder.FindRegex(doc.Selection.Text);

                    RegexTesterForm form = new RegexTesterForm();

                    if (regexFindResults.FoundMatch)

                    {

                        regexFindResults.ConvertToDisplay();

                        form.RegularExpression = regexFindResults.Regex;

                        if (regexFindResults.ToMatch != null)

                        {

                            form.ToMatch = regexFindResults.ToMatch;

                        }

                        if (regexFindResults.ReplacePattern != null)

                        {

                            form.ReplacePattern = regexFindResults.ReplacePattern;

                        }

                        form.Options = regexFindResults.RegexOptions;

                    }

                    form.FormClosing += new FormClosingEventHandler((s, e) =>

                    {

                        if (form.DialogResult == DialogResult.OK)

                        {

                            regexFindResults.Regex = form.RegularExpression;

                            if (!string.IsNullOrEmpty(form.ReplacePattern))

                            {

                                regexFindResults.ReplacePattern = form.ReplacePattern;

                            }

                            if (!string.IsNullOrEmpty(form.ToMatch) && regexFindResults.ToMatch == null)

                            {

                                regexFindResults.ToMatch = form.ToMatch;

                            }

                            regexFindResults.RegexOptions = form.Options;

                            regexFindResults.ConvertToEdit();

                            doc.Selection.MoveToPoint(startPoint, false);

                            doc.Selection.MoveToPoint(endPoint, true);

                            doc.Selection.Text = regexFindResults.GetRegexString();

                        }



                    });

                    form.Show();

                }

                handled = true;

                return;

            }

        }

        private DTE2 _applicationObject;

        private AddIn _addInInstance;

    }

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Andreas Andersen
Software Developer (Senior)
Denmark Denmark
.NET developer. I wanted to be first an astronaut, then a jet pilot, but when I got a Commodore 64 for Christmas I never looked back. Also I would never have qualified for the first two things and everybody knows computer programmers get all the girls.

| Advertise | Privacy | Mobile
Web04 | 2.8.140814.1 | Last Updated 1 Dec 2010
Article Copyright 2010 by Andreas Andersen
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid