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

Linkify Add-in for Visual Studio

, 2 Aug 2008
Link source code comments to your bug tracker, MSDN, development Wiki and more.
linkifybin_1.2.zip
Linkify.AddIn
Linkify.dll
linkifybin_1pt2.zip
Linkify.AddIn
Linkify.dll
linkifysetup_1.2.zip
LinkifySetup_1.2.exe
linkifysetup_1pt2.zip
LinkifySetup_1.2.exe
linkifysrc_1.2.zip
Linkify
IconDataConvert.exe
Linkify.AddIn
Linkify.csproj.user
linkify.ico
Setup
LinkifySetup.iss
Setup.vcproj.CALIGULA.PH.user
utility
linkifysrc_1pt2.zip
IconDataConvert.exe
Linkify.AddIn
Linkify.csproj.user
linkify.ico
LinkifySetup.iss
Setup.vcproj.CALIGULA.PH.user
Linkify_1pt3_bin.zip
Linkify.dll
Linkify2005.AddIn
Linkify2008.AddIn
Linkify_1pt3_Setup.zip
LinkifySetup.exe
Linkify_1pt3_src.zip
IconDataConvert.exe
imlConfirm.bmp
linkify.ico
Linkify2005.AddIn
Linkify2008.AddIn
LinkifySetup.iss
Setup.vcproj.CALIGULA.PH.user
��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.Diagnostics;

using System.Xml.Serialization;

using System.IO;

using System.Text;

using System.Text.RegularExpressions;





namespace Linkify

{



  // Text Save Helper

  class TSHSavePos : IDisposable

  {

    private int m_prevActiveOffset,

                m_prevAnchorOffset;



    private TextSelection m_sel;

    private bool disposed = false;



    public TSHSavePos(TextSelection sel)

    {

      m_sel = sel;

      m_prevActiveOffset = m_sel.ActivePoint.AbsoluteCharOffset;

      m_prevAnchorOffset = m_sel.AnchorPoint.AbsoluteCharOffset;

    }



    ~TSHSavePos()

    {

      Dispose(false);

    }



    public void Dispose()

    {

      Dispose(true);

      GC.SuppressFinalize(this);

    }



    private void Dispose(bool disposing)

    {

      if (!this.disposed)

      {

        // restore selection

        m_sel.MoveToAbsoluteOffset(m_prevActiveOffset, true);

        m_sel.MoveToAbsoluteOffset(m_prevAnchorOffset, false);

      }



      if (disposing)

      {

        // Dispose everything else disposable

      }



      disposed = true;

    }



  }



  public class TSH

  {



    /// <summary>

    /// retrieves the current line (of the active position) and the range that is 

    /// selected on this line. 

    /// </summary>

    public static string GetLine(TextSelection sel, out int selStart, out int selEnd)

    {

      // save current selection

      using (TSHSavePos svp_ = new TSHSavePos(sel))

      {

        // get absolute anchor/active point positions 

        int selStartAbs = sel.AnchorPoint.AbsoluteCharOffset;

        int selEndAbs = sel.ActivePoint.AbsoluteCharOffset;



        // move to start of line and make selection relative to line

        sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn, false);



        int lineOffs = sel.ActivePoint.AbsoluteCharOffset;

        selStart = selStartAbs - lineOffs;

        selEnd = selEndAbs - lineOffs;



        if (selEnd < selStart)

        {

          int temp = selEnd;

          selEnd = selStart;

          selStart = temp;

        }



        // move to end of line, get text, and limit selection to this line

        sel.EndOfLine(true);

        string text = sel.Text;



        if (selEnd > text.Length)

          selEnd = text.Length;



        return text;

      }

    }

    public static string GetLine(TextSelection sel)

    {

      int dummyA, dummyB;

      return GetLine(sel, out dummyA, out dummyB);

    }

  };





}





namespace Linkify

{

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

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

  public class Connect : IDTExtensibility2, IDTCommandTarget

  {

    const String idLinkifySettings = "phLinkifySettings";



    /// <summary>contains Add-In Settings</summary>

    Settings settings;





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

    public Connect()

    {

    }



    public enum ETextSource

    {

      Null,

      OutputWindow,

      TextSelection

    };



    internal class LineInfo

    {

      public LineInfo(string text, int selStart, int selEnd, ETextSource source)

      {

        m_text = text;

        m_startSelIdx = selStart;

        m_endSelIdx = selEnd;

        m_source = source;

      }



      private string m_text;

      private int m_startSelIdx;

      private int m_endSelIdx;

      private ETextSource m_source;



      public string Text { get { return m_text; } }

      public int StartSelIdx { get { return m_startSelIdx; } }

      public int EndSelIdx { get { return m_endSelIdx; } }

      public ETextSource Source { get { return m_source; } }



      public int LeftSelIdx { get { return Math.Min(m_startSelIdx, m_endSelIdx); } }

      public int RightSelIdx { get { return Math.Max(m_startSelIdx, m_endSelIdx); } }



      public string SelectedText { get { return m_text.Substring(m_startSelIdx, m_endSelIdx - m_startSelIdx); } }



      public char this[int index]

      {

        get

        {

          if (m_text == null || index < 0 || index >= m_text.Length)

            return '\0';

          else

            return m_text[index];

        }

      }

    }



    LineInfo GetSelInfo()

    {

      //EnvDTE.TextDocument document = _applicationObject.ActiveDocument as EnvDTE.TextDocument;

      EnvDTE.Window window = _applicationObject.ActiveWindow;



      string currentLine = "";           // the entire line under the cursor

      ETextSource source = ETextSource.Null;       // where above info was taken from

      int selStart = -1, selEnd = -1;



      try

      {

        EnvDTE.TextSelection sel = null;



        if (window is EnvDTE.OutputWindow) // ----- try "Output Window" ------------

        {

          sel = (window as OutputWindow).ActivePane.TextDocument.Selection;

          source = ETextSource.OutputWindow;

        }

        if (sel == null && window != null)

        {

          sel = window.Selection as TextSelection;

          source = ETextSource.TextSelection;

        }



        if (sel != null)

        {

          currentLine = TSH.GetLine(sel, out selStart, out selEnd);

          return new LineInfo(currentLine, selStart, selEnd, source);

        }

        else

          return null;

      }

      catch (Exception)  // presumably, it's a window where some of this doesn't work.

      {

      }

      return null;

    }





    // returns true if character stops scan to left of cursor

    static bool CharIsLeftStopper(char c)

    {

      return c == '\0' || c == ' ' || c == '\t';

    }



    // returns "closing quote" for given opening quote, '\0' if the given char is not an opening quote

    static char ReverseQuoteOf(char c)

    {

      switch (c)

      {

        case '"':

        case '\'': return c;



        // case '[': return ']';      // they might be useful, but two possible quoters should be enough

        // case '{': return '}';



        default: return '\0';



      }

    }



    private bool IsEndChar(char c, Protocol.Separator separator)

    {

      if (char.IsWhiteSpace(c) || c == '\0')

        return true;



      if (separator == Protocol.Separator.SpecialChar)

      {

        if (c == ')' || c == '.' || c == ';')

          return true;

      }



      return false;

    }







    Protocol MatchProtocol(LineInfo lineInfo, out string parameter)

    {

      parameter = "";



      if (lineInfo == null || lineInfo.Text.Length == 0)

        return null;



      int startIdx = lineInfo.StartSelIdx;



      while (!CharIsLeftStopper(lineInfo[startIdx - 1]))

        --startIdx;



      Protocol protocol = settings.protocols.MatchRequest(lineInfo.Text, startIdx);

      if (protocol == null)

      {

        // second chance: allow opening paranthesis

        if (lineInfo[startIdx] == '(')

        {

          protocol = settings.protocols.MatchRequest(lineInfo.Text, startIdx + 1);

          if (protocol != null)

            ++startIdx;

        }

        if (protocol == null)

          return null;

      }





      // ---- scan the link parameter ----



      // check for "RegEx"

      if (protocol.separator == Protocol.Separator.RegEx)

      {

        string remainder = lineInfo.Text.Substring(startIdx + protocol.prefix.Length);

        Regex rx = new Regex(protocol.regEx, protocol.regExOptions);

        Match m = rx.Match(remainder);

        parameter = Linkify.utility.RxHelper.GetValue(m, "link");

        if (parameter == null)

          parameter = Linkify.utility.RxHelper.GetValue(m);

        return protocol;

      }



      // check for "remainder of line":

      if (protocol.separator == Protocol.Separator.LineRemainder)

      {

        parameter = lineInfo.Text.Substring(startIdx + protocol.prefix.Length);

        parameter = parameter.TrimEnd(null);

        return protocol;

      }



      startIdx = startIdx + protocol.prefix.Length;



      // check for quoted:

      char quoteChar = lineInfo[startIdx];

      char quoteEnd = ReverseQuoteOf(quoteChar);

      if (quoteEnd != '\0')

      {

        int quoteEndIdx = lineInfo.Text.IndexOf(quoteEnd, startIdx + 1);

        if (quoteEndIdx > 0)

        {

          parameter = lineInfo.Text.Substring(startIdx + 1, quoteEndIdx - startIdx - 1);

          return protocol;

        }

      }



      // scan till end char

      int endIdx = startIdx;



      while (!IsEndChar(lineInfo[endIdx + 1], protocol.separator))

        ++endIdx;



      parameter = lineInfo.Text.Substring(startIdx, endIdx - startIdx + 1);

      return protocol;

    }









    /// <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;

      if (connectMode == ext_ConnectMode.ext_cm_UISetup)

      {

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

        Commands2 commands = (Commands2)_applicationObject.Commands;

        string toolsMenuName;



        // -------- Initialize Command - Wizard generated --------------

        try

        {

          //If you would like to move the command to a different menu, change the word "Tools" to the 

          //  English version of the menu. This code will take the culture, append on the name of the menu

          //  then add the command to that menu. You can find a list of all the top-level menus in the file

          //  CommandBar.resx.

          ResourceManager resourceManager = new ResourceManager("Linkify.CommandBar", Assembly.GetExecutingAssembly());

          CultureInfo cultureInfo = new System.Globalization.CultureInfo(_applicationObject.LocaleID);

          string resourceName = String.Concat(cultureInfo.TwoLetterISOLanguageName, "Tools");

          toolsMenuName = resourceManager.GetString(resourceName);

        }

        catch

        {

          //We tried to find a localized version of the word Tools, but one was not found.

          //  Default to the en-US word, which may work for the current culture.

          toolsMenuName = "Tools";

        }



        //Place the command on the tools menu.

        //Find the MenuBar command bar, which is the top-level command bar holding all the main menu items:

        Microsoft.VisualStudio.CommandBars.CommandBar menuBarCommandBar = ((Microsoft.VisualStudio.CommandBars.CommandBars)_applicationObject.CommandBars)["MenuBar"];



        //Find the Tools command bar on the MenuBar command bar:

        CommandBarControl toolsControl = menuBarCommandBar.Controls[toolsMenuName];

        CommandBarPopup toolsPopup = (CommandBarPopup)toolsControl;



        //This try/catch block can be duplicated if you wish to add multiple commands to be handled by your Add-in,

        //  just make sure you also update the QueryStatus/Exec method to include the new command names.

        try

        {

          //Add a command to the Commands collection:

          Command command = commands.AddNamedCommand2(_addInInstance, "Linkify", "Linkify", "Executes the command for Linkify", true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton);



          //Add a control for the command to the tools menu:

          if ((command != null) && (toolsPopup != 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.

        }





      } // mode = startup



      // -------- retrieve Settings --------------

      if (settings == null)

      {

        try

        {

          settings = null;

          String data = null;

          try

          {

            data = _applicationObject.Globals[idLinkifySettings] as String;

          }

          catch (ArgumentOutOfRangeException)

          {

            // no linkify settings available - fall through to "use defaults"

          }

          if (data != null && data.Length != 0)

            settings = Settings.LoadFromString(data);

        }

        catch (Exception x)

        {

#if _DEBUG

                    MessageBox.Show(x.ToString());  // dbg

#else

          string s = x.ToString();

#endif

        }

        if (settings == null)

          settings = Settings.GenerateSample();

      } // settings == 0

    }





    /// <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 == "Linkify.Connect.Linkify")

        {

          status = (vsCommandStatus)vsCommandStatus.vsCommandStatusSupported | vsCommandStatus.vsCommandStatusEnabled;

          return;

        }

      }

    }





    internal void AddConfirmFormInfo(FormConfirm form, Protocol protocol, string exe, string args, LineInfo lineInfo, string parameter)

    {

      if (protocol != null)

      {

        form.AddInfo("Protocol", protocol.prefix);

        form.AddInfo("Value", "[" + parameter + "]");

        form.AddInfo("Description", protocol.info);

        form.AddInfo("Run", exe ?? protocol.exe);

        form.AddInfo("Arguments", args ?? protocol.args);

        if (!String.IsNullOrEmpty(protocol.utilityUrl))

          form.SetUrl(protocol.utilityUrl);

      }

      else

        form.AddInfo("Protocol", "(none)");



      if (settings.TestMode)

      {

        if (lineInfo == null)

          form.AddInfo("lineInfo", "(null)");

        else

        {

          form.AddInfo("", "");

          form.AddInfo("Line", lineInfo.Text);

          form.AddInfo("Source", lineInfo.Source.ToString());

        }

      }

    }





    /// <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)

    {

      Win32WindowImpl parent = new Win32WindowImpl(

          new IntPtr(_applicationObject.MainWindow.HWnd));



      handled = false;

      if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)

      {

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

        {

          Protocol protocol = null;

          string parameter = "";

          string exe = null;

          string args = null;



          bool forceSettings = 

            settings.ShiftForcesConfigMode && 0 != (Control.ModifierKeys & Keys.Shift);



          LineInfo lineInfo = null;

          if (!forceSettings)

          {

            lineInfo = GetSelInfo();





            if (lineInfo != null)

              protocol = MatchProtocol(lineInfo, out parameter);



            if (protocol != null)

            {

              if (protocol.urlEscape)

                parameter = System.Web.HttpUtility.UrlEncode(parameter);



              exe = protocol.exe.Replace("*", parameter);

              args = protocol.args.Replace("*", parameter);



              if (protocol.expandEnvVars)

                exe = Environment.ExpandEnvironmentVariables(exe);



            }



            if (settings.TestMode || (protocol != null && protocol.confirmExecution))

            {

              FormConfirm form = new FormConfirm();

              form.SuspendLayout();

              AddConfirmFormInfo(form, protocol, exe, args, lineInfo, parameter);

              form.ResumeLayout();



              settings.CPConfirm.Restore(form);

              DialogResult rConfirm = form.ShowDialog(parent);

              settings.CPConfirm.Save(form);



              if (rConfirm != DialogResult.OK)

                return;



              forceSettings = form.ForceSettings;

            }

          }



          if (protocol != null && !forceSettings)

          {

            try

            {

              ProcessStartInfo psi = new ProcessStartInfo(exe, args);

              psi.UseShellExecute = true;

              System.Diagnostics.Process.Start(psi);

            }

            catch (Exception x)

            {

              FormConfirm fc = new FormConfirm();

              fc.SuspendLayout();

              fc.AddError(x.Message);

              AddConfirmFormInfo(fc, protocol, exe, args, lineInfo, parameter);

              fc.ResumeLayout();



              settings.CPConfirm.Restore(fc);

              DialogResult rConfirm = fc.ShowDialog(parent);

              settings.CPConfirm.Save(fc);

              forceSettings = fc.ForceSettings;

            }

          }

          else

            forceSettings = true;



          if (forceSettings)

          {

            FormConfig f = new FormConfig();

            try

            {

              f.EditSettings = settings.Clone() as Settings;

            }

            catch (Exception x)

            {

              MessageBox.Show(x.Message);

            }



            settings.CPConfig.Restore(f);

            DialogResult r = f.ShowDialog(parent);

            settings.CPConfig.Save(f);



            if (r == DialogResult.OK)

            {

              settings = f.EditSettings;

              _applicationObject.Globals[idLinkifySettings] = settings.SaveToString();

              _applicationObject.Globals.set_VariablePersists(idLinkifySettings, true);

            }

          }

          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

peterchen
Klippel
Germany Germany
Peter is tired of being called "Mr. Chen", even so certain individuals insist on it. No, he's not chinese.
 
Peter has seen lots of boxes you youngsters wouldn't even accept as calculators. He is proud of having visited the insides of a 16 Bit Machine.
 
In his spare time he ponders new ways of turning groceries into biohazards, or tries to coax South American officials to add some stamps to his passport.
 
Beyond these trivialities Peter works for Klippel[^], a small german company that wants to make mankind happier by selling them novel loudspeaker measurement equipment.
 

Where are you from?[^]



Please, if you are using one of my articles for anything, just leave me a comment. Seeing that this stuff is actually useful to someone is what keeps me posting and updating them.
Should you happen to not like it, tell me, too

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 2 Aug 2008
Article Copyright 2006 by peterchen
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid