Ejemplo n.º 1
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Moves the up before comment.
        /// </summary>
        /// <param name="sel">The sel.</param>
        /// ------------------------------------------------------------------------------------
        private void MoveUpBeforeComment(TextSelection sel)
        {
            TextRanges textRanges = null;

            for (; true;)
            {
                if (sel.FindPattern("\\<summary\\>|/// ---", (int)(vsFindOptions.vsFindOptionsBackwards | vsFindOptions.vsFindOptionsRegularExpression),
                                    ref textRanges))
                {
                    // GhostDoc messes up dashed lines from inherited comments from base class,
                    // so delete those
                    if (sel.Text.StartsWith("/// ---"))
                    {
                        sel.EndOfLine(true);
                        sel.WordRight(true, 1);
                        sel.Delete(1);
                    }
                    else if (sel.Text.StartsWith("<summary>"))
                    {
                        while (true)
                        {
                            sel.MoveToLineAndOffset(sel.ActivePoint.Line - 1, 1, false);
                            sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                            sel.EndOfLine(true);
                            if (!sel.Text.StartsWith("///"))
                            {
                                if (sel.Text.Length > 0)
                                {
                                    // there is a non-empty comment line. We want to start at the end
                                    // of it
                                    sel.EndOfLine(false);
                                }
                                else
                                {
                                    sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                                }
                                break;
                            }

                            // GhostDoc messes up dashed lines from inherited comments from base class,
                            // so delete those
                            if (sel.Text.StartsWith("/// -----"))
                            {
                                sel.WordRight(true, 1);
                                sel.Delete(1);
                            }
                        }
                        return;
                    }
                }
                else
                {
                    return;
                }
            }
        }
Ejemplo n.º 2
0
        private void UpdateCallback(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            DTE dte = ServiceProvider.GetServiceAsync(typeof(DTE)).Result as DTE;

            if (dte == null)
            {
                return;
            }

            TextSelection section = dte.ActiveDocument.Selection as TextSelection;

            // 光标移动至第一行第一列
            section.MoveToLineAndOffset(1, 1);
            bool result = section.FindText("database", (int)vsFindOptions.vsFindOptionsRegularExpression);

            if (!result)
            {
                section.SelectAll();
                section.Delete();
            }
            else
            {
                //需要添加此操作,否则不会替换成功
                section.SelectAll();
                section.Text = "";
            }
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Removes special characters after inserting header
 /// </summary>
 /// <param name="textSelection">Text selection</param>
 /// <param name="template">Template</param>
 private void RemoveSpecialCharacters(TextSelection textSelection, string template)
 {
     // Remove special characters from beginning of each line in template
     textSelection.StartOfDocument();
     for (int i = 0; i < template.Split('\n').Length; i++)
     {
         textSelection.StartOfLine();
         textSelection.CharRight(true, SpecialCharacters.Length);
         textSelection.Delete();
         textSelection.LineDown();
     }
 }
Ejemplo n.º 4
0
        public static void CreateClass(this Project pro, string directory, string name, string content)
        {
            if (pro == null)
            {
                return;
            }
            var add = false;

            foreach (ProjectItem projectItem in pro.ProjectItems)
            {
                var dname = projectItem.Name;
                if (dname == directory)
                {
                    var item = projectItem.GetItem(name + ".cs");
                    if (item == null)
                    {
                        string templatePath =
                            GetSolution3().GetProjectItemTemplate("Class.zip", "CSharp");
                        projectItem.ProjectItems.AddFromTemplate(templatePath, name + ".cs");
                        TextSelection txtSel = (TextSelection)Application.ActiveDocument.Selection;
                        txtSel.SelectAll();
                        txtSel.Delete();
                        txtSel.Insert(content);
                        add = true;
                    }
                    else
                    {
                        item.Open();
                        TextSelection txtSel = (TextSelection)Application.ActiveDocument.Selection;
                        txtSel.SelectAll();
                        txtSel.Delete();
                        txtSel.Insert(content);
                        add = true;
                    }
                }
            }

            if (!add)
            {
                pro.ProjectItems.AddFolder(directory);
                var    projectItem  = pro.GetItem(directory);
                string templatePath =
                    GetSolution3().GetProjectItemTemplate("Class.zip", "CSharp");
                projectItem.ProjectItems.AddFromTemplate(templatePath, name + ".cs");
                TextSelection txtSel = (TextSelection)Application.ActiveDocument.Selection;

                txtSel.SelectAll();
                txtSel.Delete();
                txtSel.Insert(content);
                add = true;
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        ///     A TextSelection extension method that replaces the selected text.
        /// </summary>
        /// <param name="selection">
        ///     The selection to act on.
        /// </param>
        /// <param name="newText">
        ///     The new text.
        /// </param>
        public static void ReplaceSelectedText(this TextSelection selection, string newText)
        {
            selection.Trim();
            var editPoint = selection.TopPoint.CreateEditPoint();

            selection.Delete();
            var topPoint = selection.TopPoint.AbsoluteCharOffset;

            editPoint.Insert(newText);
            selection.MoveToAbsoluteOffset(selection.ActivePoint.AbsoluteCharOffset);
            selection.MoveToAbsoluteOffset(topPoint, true);
            selection.SmartFormat();
        }
        private void BeforeKeyPress(string keypress, TextSelection selection,
		                            bool inStatementCompletion, ref bool cancelKeypress)
        {
            if (!ConvertTabsToSpaces || !selection.IsEmpty || inStatementCompletion) return;

            switch (keypress)
            {
                case BACKSPACE_KEY:
                    do
                    {
                        selection.CharLeft(true);
                        if (selection.Text == " ")
                        {
                            cancelKeypress = true;
                            selection.Delete();
                            continue;
                        }
                        selection.CharRight(true);
                        return;
                    } while (selection.CurrentColumn%IndentSize != 1);
                    return;

                case DELETE_KEY:
                    for (var i = 0; i < IndentSize; i++)
                    {
                        selection.CharRight(true);
                        if (selection.Text == " ")
                        {
                            cancelKeypress = true;
                            selection.Delete();
                            continue;
                        }
                        selection.CharLeft(true);
                        return;
                    }
                    return;
            }
        }
Ejemplo n.º 7
0
        public void ReplaceSelectionWith(string text)
        {
            DTE2          a         = (DTE2)provider.SsmsDte2;
            Document      document  = a.ActiveDocument;
            TextSelection selection = document.Selection as TextSelection;

            selection.Delete();

            var editPoint = GetEditPointAtTopOfSelection();
            var endPoint  = GetEditPointAtTopOfSelection();

            editPoint.Delete(endPoint);
            editPoint.Insert(text + Environment.NewLine);
        }
Ejemplo n.º 8
0
        internal void CreateFile(string fileName, string content)
        {
            DTE dte = (DTE)GetService(typeof(DTE));

            dte.ItemOperations.NewFile("General\\Text File", fileName);

            TextSelection textSel = (TextSelection)dte.ActiveDocument.Selection;
            TextDocument  textDoc = (TextDocument)dte.ActiveDocument.Object();

            textSel.SelectAll();
            textSel.Delete();
            textSel.Insert(content);

            textSel.GotoLine(1);
        }
Ejemplo n.º 9
0
        private void CreateNewFile(string filename, string content)
        {
            DTE dte = (DTE)GetService(typeof(DTE));

            dte.ItemOperations.NewFile(@"General\Visual C# Class", filename, EnvDTE.Constants.vsViewKindTextView);
            TextSelection txtSel = (TextSelection)dte.ActiveDocument.Selection;
            TextDocument  txtDoc = (TextDocument)dte.ActiveDocument.Object("");

            txtSel.SelectAll();
            txtSel.Delete();
            txtSel.Insert(content);
            //    //var dte = (EnvDTE.DTE)ServiceProvider.GlobalProvider.GetService(typeof(EnvDTE.DTE));
            //    // https://social.msdn.microsoft.com/Forums/vstudio/en-US/a7da9e48-7282-4e22-a07a-36e66426316e/add-in-trying-to-add-class-fails-with-template-invalid-for-that-project?forum=vsx
            //    EnvDTE80.DTE2 dte = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE80.DTE2;

            //    if (dte == null)
            //    {
            //        //Alert("Could not create new file.");
            //        System.Diagnostics.Debug.WriteLine("Could not get EnvDTE.DTE service.");
            //        return;
            //    }

            //    var solution = dte.Solution as EnvDTE80.Solution2;

            //    if (solution == null)
            //    {
            //        //Alert("Could not create new file.");
            //        System.Diagnostics.Debug.WriteLine("Could not get DTE solution.");
            //        return;
            //    }

            //    var x = solution.GetProjectItemTemplate(filename, "CSharp");
            //    //dte.ActiveDocument.ProjectItem.ContainingProject;


            //    //dte.ItemOperations.AddNewItem(@"Visual C# Project Items\Class", name);
            //    // http://stackoverflow.com/questions/11049758/selected-project-from-solution-explorer

            //    var txtSel = (EnvDTE.TextSelection)dte.ActiveDocument.Selection;
            //    var txtDoc = (EnvDTE.TextDocument)dte.ActiveDocument.Object();

            //    txtSel.SelectAll();
            //    txtSel.Delete();
            //    txtSel.Insert(content);
        }
Ejemplo n.º 10
0
        void ProcessOpenStartFile(object sender, EventArgs e)
        {
            Debug.WriteLine("OpenStartFile");

            var inValue = ((OleMenuCmdEventArgs)e).InValue as string;

            Debug.WriteLine($"param: {inValue}");

            DTE dte = (DTE)GetService(typeof(EnvDTE.DTE));

            var prjs = dte.Solution.Projects;

            System.Diagnostics.Debug.WriteLine($"Number of projects is {prjs.Count}");

            if (prjs.Count > 0)
            {
                var prj     = prjs.Item(1);
                var pritems = prj.ProjectItems;
                ShowProjectItems(pritems, 0, inValue);

                dte.ActiveDocument.Activate();
                dte.Find.PatternSyntax     = vsFindPatternSyntax.vsFindPatternSyntaxRegExpr;
                dte.Find.FindWhat          = "//startstarttypingtypingherehere";
                dte.Find.Target            = vsFindTarget.vsFindTargetCurrentDocument;
                dte.Find.MatchCase         = false;
                dte.Find.MatchWholeWord    = false;
                dte.Find.Backwards         = false;
                dte.Find.MatchInHiddenText = false;
                dte.Find.Action            = vsFindAction.vsFindActionFind;
                if (dte.Find.Execute() == vsFindResult.vsFindResultNotFound)
                {
                    throw new System.Exception("vsFindResultNotFound");
                }
                dte.Windows.Item("{CF2DDC32-8CAD-11D2-9302-005345000000}").Close();
                TextSelection ts = (TextSelection)dte.ActiveDocument.Selection;
                ts.Delete();

                dte.ExecuteCommand("File.SaveAll", string.Empty);
                dte.ExecuteCommand("Build.BuildSolution");
                dte.ActiveDocument.Activate();
            }
        }
Ejemplo n.º 11
0
        private void ApplyInline(TextSelection selection)
        {
            var closeUndoContext = false;

            if (!selection.DTE.UndoContext.IsOpen)
            {
                selection.BeginUpdate("Surround With " + Name);
                closeUndoContext = true;
            }

            var sb = new StringBuilder();

            sb.Append(_preText[0]);
            sb.Append(selection.Text);
            sb.Append(_postText[0]);

            var line = selection.TopLine;
            var col  = selection.TopPoint.DisplayColumn;

            selection.Delete();
            selection.Insert(sb.ToString());

            if (_caretLine >= 0)
            {
                selection.MoveToDisplayColumn(line, col + _caretCol - 1);
            }
            else
            {
                selection.MoveToDisplayColumn(line, col, true);
            }

            if (closeUndoContext)
            {
                selection.EndUpdate();
            }
        }
Ejemplo n.º 12
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Moves the down after comment.
        /// </summary>
        /// <param name="sel">The sel.</param>
        /// ------------------------------------------------------------------------------------
        private void MoveDownAfterComment(TextSelection sel)
        {
            // Go to the beginning of the line and move down until we find a line that doesn't
            // start with ///.
            while (true)
            {
                sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                sel.EndOfLine(true);
                if (!sel.Text.StartsWith("///"))
                {
                    break;
                }

                // GhostDoc messes up dashed lines from inherited comments from base class,
                // so delete those
                if (sel.Text.StartsWith("/// -----"))
                {
                    sel.WordRight(true, 1);
                    sel.Delete(1);
                    sel.LineUp(false, 1);
                }
                sel.MoveToLineAndOffset(sel.ActivePoint.Line + 1, 1, false);
            }
        }
Ejemplo n.º 13
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Moves the down after comment.
        /// </summary>
        /// <param name="sel">The sel.</param>
        /// ------------------------------------------------------------------------------------
        private void MoveDownAfterComment(TextSelection sel)
        {
            // Go to the beginning of the line and move down until we find a line that doesn't
            // start with ///.
            while (true)
            {
                sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                sel.EndOfLine(true);
                if (!sel.Text.StartsWith("///"))
                    break;

                // GhostDoc messes up dashed lines from inherited comments from base class,
                // so delete those
                if (sel.Text.StartsWith("/// -----"))
                {
                    sel.WordRight(true, 1);
                    sel.Delete(1);
                    sel.LineUp(false, 1);
                }
                sel.MoveToLineAndOffset(sel.ActivePoint.Line + 1, 1, false);
            }
        }
Ejemplo n.º 14
0
        /// <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.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormatSelectionOrActiveWindow"))
                {
                    string fileExtension = System.IO.Path.GetExtension(_applicationObject.ActiveDocument.FullName);
                    bool   isSqlFile     = fileExtension.ToUpper().Equals(".SQL");

                    if (isSqlFile ||
                        MessageBox.Show(_generalResourceManager.GetString("FileTypeWarningMessage"), _generalResourceManager.GetString("FileTypeWarningMessageTitle"), MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        string        fullText  = SelectAllCodeFromDocument(_applicationObject.ActiveDocument);
                        TextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection;
                        if (!selection.IsActiveEndGreater)
                        {
                            selection.SwapAnchor();
                        }
                        if (selection.Text.EndsWith(Environment.NewLine) || selection.Text.EndsWith(" "))
                        {
                            selection.CharLeft(true, 1); //newline counts as a distance of one.
                        }
                        string selectionText       = selection.Text;
                        bool   formatSelectionOnly = selectionText.Length > 0 && selectionText.Length != fullText.Length;


                        string textToFormat = formatSelectionOnly ? selectionText : fullText;
                        var    formatter    = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(
                            Properties.Settings.Default.IndentString.Replace("\\t", "\t"),
                            Properties.Settings.Default.SpacesPerTab,
                            Properties.Settings.Default.MaxLineWidth,
                            Properties.Settings.Default.ExpandCommaLists,
                            Properties.Settings.Default.TrailingCommas,
                            Properties.Settings.Default.SpaceAfterExpandedComma,
                            Properties.Settings.Default.ExpandBooleanExpressions,
                            Properties.Settings.Default.ExpandCaseStatements,
                            Properties.Settings.Default.ExpandBetweenConditions,
                            Properties.Settings.Default.BreakJoinOnSections,
                            Properties.Settings.Default.UppercaseKeywords,
                            false,
                            Properties.Settings.Default.KeywordStandardization
                            );
                        formatter.ErrorOutputPrefix = _generalResourceManager.GetString("ParseErrorWarningPrefix");
                        var    formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(formatter);
                        bool   errorsFound       = false;
                        string formattedText     = formattingManager.Format(textToFormat, ref errorsFound);

                        bool abortFormatting = false;
                        if (errorsFound)
                        {
                            abortFormatting = MessageBox.Show(_generalResourceManager.GetString("ParseErrorWarningMessage"), _generalResourceManager.GetString("ParseErrorWarningMessageTitle"), MessageBoxButtons.YesNo) != DialogResult.Yes;
                        }

                        if (!abortFormatting)
                        {
                            if (formatSelectionOnly)
                            {
                                selection.Delete(1);
                                selection.Insert(formattedText, (int)EnvDTE.vsInsertFlags.vsInsertFlagsContainNewText);
                            }
                            else
                            {
                                ReplaceAllCodeInDocument(_applicationObject.ActiveDocument, formattedText);
                            }
                        }
                    }

                    handled = true;
                    return;
                }
                if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormattingOptions"))
                {
                    SettingsForm settings = new SettingsForm();
                    if (settings.ShowDialog() == DialogResult.OK)
                    {
                        SetFormatHotkey();
                    }
                    settings.Dispose();
                }
            }
        }
Ejemplo n.º 15
0
        /// <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.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormatSelectionOrActiveWindow"))
                {
                    string fileExtension = System.IO.Path.GetExtension(_applicationObject.ActiveDocument.FullName);
                    bool   isSqlFile     = fileExtension.ToUpper().Equals(".SQL");

                    if (isSqlFile ||
                        MessageBox.Show(_generalResourceManager.GetString("FileTypeWarningMessage"), _generalResourceManager.GetString("FileTypeWarningMessageTitle"), MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        string        fullText  = SelectAllCodeFromDocument(_applicationObject.ActiveDocument);
                        TextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection;
                        if (!selection.IsActiveEndGreater)
                        {
                            selection.SwapAnchor();
                        }
                        if (selection.Text.EndsWith(Environment.NewLine) || selection.Text.EndsWith(" "))
                        {
                            selection.CharLeft(true, 1); //newline counts as a distance of one.
                        }
                        string selectionText       = selection.Text;
                        bool   formatSelectionOnly = selectionText.Length > 0 && selectionText.Length != fullText.Length;


                        string textToFormat  = formatSelectionOnly ? selectionText : fullText;
                        bool   errorsFound   = false;
                        string formattedText = _formattingManager.Format(textToFormat, ref errorsFound);

                        bool abortFormatting = false;
                        if (errorsFound)
                        {
                            abortFormatting = MessageBox.Show(_generalResourceManager.GetString("ParseErrorWarningMessage"), _generalResourceManager.GetString("ParseErrorWarningMessageTitle"), MessageBoxButtons.YesNo) != DialogResult.Yes;
                        }

                        if (!abortFormatting)
                        {
                            if (formatSelectionOnly)
                            {
                                selection.Delete(1);
                                selection.Insert(formattedText, (int)EnvDTE.vsInsertFlags.vsInsertFlagsContainNewText);
                            }
                            else
                            {
                                ReplaceAllCodeInDocument(_applicationObject.ActiveDocument, formattedText);
                            }
                        }
                    }

                    handled = true;
                    return;
                }
                if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormattingOptions"))
                {
                    SettingsForm settings = new SettingsForm(Properties.Settings.Default, Assembly.GetExecutingAssembly(), _generalResourceManager.GetString("ProjectAboutDescription"), new SettingsForm.GetTextEditorKeyBindingScopeName(GetTextEditorKeyBindingScopeName));
                    if (settings.ShowDialog() == DialogResult.OK)
                    {
                        SetFormatHotkey();
                        _formattingManager = Utils.GetFormattingManager(Properties.Settings.Default);
                    }
                    settings.Dispose();
                }
            }
        }
        /// <summary>
        /// Removes the header.
        /// </summary>
        /// <param name="instance">The instance.</param>
        public static void RemoveHeader(this ProjectItem instance)
        {
            TraceService.WriteLine("ProjectItemExtensions::RemoveHeader Name=" + instance.Name);

            if (instance.IsCSharpFile())
            {
                Window window = instance.Open(VSConstants.VsViewKindCode);

                if (window != null)
                {
                    try
                    {
                        window.Activate();
                    }
                    catch (Exception exception)
                    {
                        ///// i think this happens when i am debugging (i could be wrong!)
                        TraceService.WriteError("Cant Remove Header Window Activate wont work exception=" + exception.Message);
                        return;
                    }

                    TextSelection selection = (TextSelection)instance.Document.Selection;

                    bool continueLoop = true;
                    int  loopCounter  = 0;

                    do
                    {
                        //// just in case we get infinity loop problem!
                        if (loopCounter > 100)
                        {
                            TraceService.WriteLine("breaking out of loop");
                            continueLoop = false;
                        }

                        selection.GotoLine(1, true);
                        selection.SelectLine();

                        TraceService.WriteLine("text=" + selection.Text);

                        if (selection.Text.TrimStart().StartsWith("//"))
                        {
                            TraceService.WriteLine("*** deleting selection");
                            selection.Delete();
                            loopCounter++;
                        }
                        else
                        {
                            TraceService.WriteLine("*** NOT deleting selection");
                            continueLoop = false;
                        }
                    }while (continueLoop);
                }
            }

            //// don't forget sub items.

            if (instance.ProjectItems != null)
            {
                IEnumerable <ProjectItem> subProjectItems = instance.GetCSharpProjectItems();

                foreach (ProjectItem subProjectItem in subProjectItems)
                {
                    subProjectItem.RemoveHeader();
                }
            }
        }
Ejemplo n.º 17
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Inserts the method header.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public void InsertMethodHeader()
        {
            TextSelection sel = (TextSelection)m_applicationObject.ActiveDocument.Selection;

            CodeElement codeElement = GetMethodOrProperty(sel);

            if (codeElement == null)
            {
                codeElement = sel.ActivePoint.get_CodeElement(vsCMElement.vsCMElementClass);
                if (codeElement == null)
                {
                    codeElement = sel.ActivePoint.get_CodeElement(vsCMElement.vsCMElementInterface);
                }
                if (codeElement == null || codeElement.StartPoint.Line != sel.ActivePoint.Line)
                {
                    // not a function or property, so just insert /// <summary/>
                    sel.LineUp(false, 1);
                    if (!IsXmlCommentLine)
                    {
                        sel.EndOfLine(false);
                        sel.NewLine(1);
                        sel.Text = "///";
                        sel.LineDown(true, 1);
                        sel.Delete(1);
                        sel.LineUp(false, 1);
                        sel.EndOfLine(false);
                        sel.WordRight(true, 2);
                        sel.Delete(1);
                    }
                    else
                    {
                        sel.LineDown(false, 1);
                    }
                    return;
                }
            }

            sel.MoveToPoint(codeElement.StartPoint, false);

            // Figure out indentation and build dashed line
            sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn, false);
            sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, true);
            string indent = sel.Text;

            sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
            string dashedLine = indent + "/// " +
                                new string('-', kLineLen - sel.ActivePoint.VirtualDisplayColumn - 4);

            bool fGhostDoc = true;

            try
            {
                // Use GhostDoc if available
                string addinName = string.Empty;
                foreach (AddIn addin in m_applicationObject.AddIns)
                {
                    if (addin.Name == "GhostDoc")
                    {
                        addinName = (addin.ProgID == "SubMain.GhostDoc.Connect") ?
                                    "Tools.SubMain.GhostDoc.DocumentThis" : "Weigelt.GhostDoc.AddIn.DocumentThis";
                        break;
                    }
                }
                if (addinName != string.Empty)
                {
                    m_applicationObject.ExecuteCommand(addinName, string.Empty);
                }
                else
                {
                    fGhostDoc = false;
                }
            }
            catch
            {
                fGhostDoc = false;
            }

            if (fGhostDoc)
            {
                int nLine       = sel.ActivePoint.Line;
                int nLineOffset = sel.ActivePoint.LineCharOffset;

                // Check to see if we're in the middle of the comment or at the beginning of
                // the method.
                sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                if (GetMethodOrProperty(sel) == null)
                {
                    // we're in the middle of the comment - move to the end of the comment
                    MoveDownAfterComment(sel);

                    // we're inserting one line (//---) above
                    nLine++;
                }
                else
                {
                    // We are at the beginning of the method.
                    // Check to see if the line above the current line is an attribute. If it is we want to
                    // start there, otherwise we start at the current line.
                    sel.LineUp(false, 1);
                    sel.CharRight(false, 1);
                    if (sel.ActivePoint.get_CodeElement(vsCMElement.vsCMElementAttribute) == null)
                    {
                        sel.MoveToLineAndOffset(nLine, 1, false);
                    }

                    // we're inserting two lines above
                    nLine += 2;
                }
                // In case the line is wrapped, we want to go to the real beginning of the line
                sel.MoveToLineAndOffset(sel.ActivePoint.Line, 1, false);
                sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn, false);

                // Insert a new line and then insert our dashed line.
                sel.Insert(dashedLine + Environment.NewLine, (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);

                sel.LineUp(false, 1);
                sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                MoveUpBeforeComment(sel);

                sel.Insert(Environment.NewLine + dashedLine, (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);

                // put IP at previous location
                sel.MoveToLineAndOffset(nLine, nLineOffset, false);
            }
            else
            {
                // check if we already have a comment
                sel.LineUp(false, 1);
                if (!IsXmlCommentLine)
                {
                    // Insert comment
                    sel.EndOfLine(false);
                    sel.NewLine(1);
                    sel.Text = "///";
                }

                // Insert line above
                MoveUpBeforeComment(sel);
                sel.EndOfLine(false);
                sel.NewLine(1);
                sel.Text = dashedLine;
                int upperLine = sel.ActivePoint.Line;
                sel.LineDown(false, 1);

                // reformat text
                for (; IsXmlCommentLine;)
                {
                    int curLine = sel.CurrentLine;
                    // go through all words in this line
                    for (; sel.CurrentLine == curLine; sel.WordRight(false, 1))
                    {
                        if (sel.ActivePoint.VirtualDisplayColumn > kLineLen)
                        {
                            // we have to break before this word
                            sel.WordLeft(true, 1);
                            // skip all punctuation characters
                            for (; sel.Text.Length == 1 && char.IsPunctuation(sel.Text[0]);)
                            {
                                sel.CharLeft(false, 1);                                 // removes selection
                                sel.WordLeft(true, 1);
                            }
                            sel.CharLeft(false, 1);                             // removes selection

                            // break the line
                            sel.NewLine(1);

                            // join next line with remainder of current line
                            sel.EndOfLine(false);
                            sel.LineDown(true, 1);
                            sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, true);
                            sel.WordRight(true, 1);
                            sel.Delete(1);

                            // insert a space between the two lines
                            sel.Text = " ";
                        }
                    }
                }

                // Insert line below
                sel.GotoLine(upperLine + 1, false);
                MoveDownAfterComment(sel);
                sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                sel.NewLine(1);
                sel.LineUp(false, 1);
                sel.Text = dashedLine;
                sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                sel.LineDown(false, 1);
            }
        }
        public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            try
            {
                if (VsShellUtilities.IsInAutomationFunction(m_provider.ServiceProvider))
                {
                    return(m_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut));
                }

                // make a copy of this so we can look at it after forwarding some commands
                uint commandID = nCmdID;
                char typedChar = char.MinValue;

                // make sure the input is a char before getting it
                if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (uint)VSConstants.VSStd2KCmdID.TYPECHAR)
                {
                    typedChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn);
                }

                // check for the triple slash
                if (typedChar == '/' && m_dte != null)
                {
                    string currentLine = m_textView.TextSnapshot.GetLineFromPosition(
                        m_textView.Caret.Position.BufferPosition.Position).GetText();
                    if ((currentLine + "/").Trim() == "///")
                    {
                        // Calculate how many spaces
                        string        spaces    = currentLine.Replace(currentLine.TrimStart(), "");
                        TextSelection ts        = m_dte.ActiveDocument.Selection as TextSelection;
                        int           oldLine   = ts.ActivePoint.Line;
                        int           oldOffset = ts.ActivePoint.LineCharOffset;
                        ts.LineDown();
                        ts.EndOfLine();

                        CodeElement   codeElement = null;
                        FileCodeModel fcm         = m_dte.ActiveDocument.ProjectItem.FileCodeModel;
                        if (fcm != null)
                        {
                            codeElement = fcm.CodeElementFromPoint(ts.ActivePoint, vsCMElement.vsCMElementFunction);
                        }

                        ts.MoveToLineAndOffset(oldLine, oldOffset - 2);
                        ts.Delete(2);

                        if (codeElement != null && codeElement is CodeFunction)
                        {
                            ts.Insert(createJavaStyleComment(codeElement, spaces));

                            ts.MoveToLineAndOffset(oldLine, oldOffset);
                            ts.LineDown();
                            ts.EndOfLine();
                            return(VSConstants.S_OK);
                        }
                        else
                        {
                            ts.Insert("/**\r\n" + spaces + "* \r\n" + spaces + "* \r\n" + spaces + "*/");
                            ts.MoveToLineAndOffset(oldLine, oldOffset);
                            ts.LineDown();
                            ts.EndOfLine();
                            return(VSConstants.S_OK);
                        }
                    }
                }

                if (m_session != null && !m_session.IsDismissed)
                {
                    // check for a commit character
                    if (nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN ||
                        nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB ||
                        typedChar == '>')
                    {
                        // check for a selection
                        // if the selection is fully selected, commit the current session
                        if (m_session.SelectedCompletionSet.SelectionStatus.IsSelected)
                        {
                            string selectedCompletion = m_session.SelectedCompletionSet.SelectionStatus.Completion.DisplayText;
                            m_session.Commit();
                            TextSelection ts = m_dte.ActiveDocument.Selection as TextSelection;
                            switch (selectedCompletion)
                            {
                            case "<!-->":
                                ts.CharLeft(false, 3);
                                break;

                            case "<![CDATA[>":
                                ts.CharLeft(false, 3);
                                break;

                            case "<c>":
                                ts.CharLeft(false, 4);
                                break;

                            case "<code>":
                                ts.CharLeft(false, 7);
                                break;

                            case "<example>":
                                ts.CharLeft(false, 10);
                                break;

                            case "<exception>":
                                ts.CharLeft(false, 14);
                                break;

                            case "<include>":
                                ts.CharLeft(false, 21);
                                break;

                            case "<list>":
                                ts.CharLeft(false, 7);
                                break;

                            case "<para>":
                                ts.CharLeft(false, 7);
                                break;

                            case "<param>":
                                ts.CharLeft(false, 10);
                                break;

                            case "<paramref>":
                                ts.CharLeft(false, 13);
                                break;

                            case "<permission>":
                                ts.CharLeft(false, 15);
                                break;

                            case "<remarks>":
                                ts.CharLeft(false, 10);
                                break;

                            case "<returns>":
                                ts.CharLeft(false, 10);
                                break;

                            case "<see>":
                                ts.CharLeft(false, 3);
                                break;

                            case "<seealso>":
                                ts.CharLeft(false, 3);
                                break;

                            case "<typeparam>":
                                ts.CharLeft(false, 14);
                                break;

                            case "<value>":
                                ts.CharLeft(false, 8);
                                break;

                            default:
                                break;
                            }

                            // also, don't add the character to the buffer
                            return(VSConstants.S_OK);
                        }
                        else
                        {
                            // if there is no selection, dismiss the session
                            m_session.Dismiss();
                        }
                    }
                }
                else
                {
                    if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN)
                    {
                        string currentLine = m_textView.TextSnapshot.GetLineFromPosition(
                            m_textView.Caret.Position.BufferPosition.Position).GetText();
                        if (currentLine.TrimStart().StartsWith("///"))
                        {
                            TextSelection ts     = m_dte.ActiveDocument.Selection as TextSelection;
                            string        spaces = currentLine.Replace(currentLine.TrimStart(), "");
                            ts.Insert("\r\n" + spaces + "/// ");
                            return(VSConstants.S_OK);
                        }
                    }
                }

                // pass along the command so the char is added to the buffer
                int retVal = m_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
                if (typedChar == '<')
                {
                    string currentLine = m_textView.TextSnapshot.GetLineFromPosition(
                        m_textView.Caret.Position.BufferPosition.Position).GetText();
                    if (currentLine.TrimStart().StartsWith("///"))
                    {
                        if (m_session == null || m_session.IsDismissed) // If there is no active session, bring up completion
                        {
                            if (this.TriggerCompletion())
                            {
                                m_session.Filter();
                                return(VSConstants.S_OK);
                            }
                        }
                    }
                }
                else if (
                    commandID == (uint)VSConstants.VSStd2KCmdID.BACKSPACE ||
                    commandID == (uint)VSConstants.VSStd2KCmdID.DELETE ||
                    char.IsLetter(typedChar))
                {
                    if (m_session != null && !m_session.IsDismissed) // the completion session is already active, so just filter
                    {
                        m_session.Filter();
                        return(VSConstants.S_OK);
                    }
                }

                return(retVal);
            }
            catch
            {
            }

            return(VSConstants.E_FAIL);
        }
Ejemplo n.º 19
0
        /// <summary></summary>
        bool ChangeSelectedTextCase(TextSelection selection, TextTransformationOption option)
        {
            string before = selection.Text;
            string after = CodeManager.TransformText(before, option);
            bool changed = (before != after);

            if (changed)
            {
                selection.Delete();
                selection.Insert(after);
            }
            return changed;
        }
Ejemplo n.º 20
0
        private static void addContentToProject(SolutionData solutionData, Project project, DTE2 dte2)
        {
            #region CPP Writing
            if (solutionData.projectType == ProjectType.CppEmpty) //CPP Example
            {
                Directory.CreateDirectory(solutionData.directoryPath + "\\Source Files");
                Directory.CreateDirectory(solutionData.directoryPath + "\\Header Files");

                foreach (ClassData classData in solutionData.classes)
                {
                    #region Class
                    if (classData.classType == ClassType.Class)
                    {
                        Document      doc    = dte2.ItemOperations.NewFile("General\\Text File", classData.className).Document;
                        TextSelection txtsel = (TextSelection)doc.Selection;
                        txtsel.Text = "";
                        txtsel.Insert("#include \"" + classData.className + ".h\"\n\n" + classData.className + "::" + classData.className + "()\n{\n}\n\n" + classData.className + "::~" + classData.className + "()\n{\n}");
                        doc.Save(solutionData.directoryPath + "\\Source Files\\" + classData.className + ".cpp");
                        project.ProjectItems.AddFromFile(solutionData.directoryPath + "\\Source Files\\" + classData.className + ".cpp");

                        Document      doc2    = dte2.ItemOperations.NewFile("General\\Text File", classData.className).Document;
                        TextSelection txtsel2 = (TextSelection)doc2.Selection;
                        txtsel2.Text = "";
                        txtsel2.Insert("#pragma once");
                        if (classData.superClassName != "")
                        {
                            txtsel2.Insert("\n#include \"" + classData.superClassName + "\"");
                        }
                        foreach (string interfaceName in classData.interfaceNames)
                        {
                            txtsel2.Insert("\n#include \"" + interfaceName + "\"");
                        }
                        txtsel2.Insert("\n\nclass " + classData.className);
                        if (classData.superClassName != "")
                        {
                            txtsel2.Insert(" : public " + classData.superClassName);

                            foreach (string interfaceName in classData.interfaceNames)
                            {
                                txtsel2.Insert(", " + interfaceName);
                            }
                        }
                        else if (classData.interfaceNames.Count != 0)
                        {
                            txtsel2.Insert(" : " + classData.interfaceNames[0]);

                            for (int i = 1; i < classData.interfaceNames.Count; ++i)
                            {
                                txtsel2.Insert(", " + classData.interfaceNames[i]);
                            }
                        }
                        txtsel2.Insert("\n{\npublic:\n\t" + classData.className + "();\n\t~" + classData.className + "();\n\nprivate:\n\n};");
                        doc2.Save(solutionData.directoryPath + "\\Header Files\\" + classData.className + ".h");
                        project.ProjectItems.AddFromFile(solutionData.directoryPath + "\\Header Files\\" + classData.className + ".h");
                    }
                    #endregion
                    #region Enum
                    else if (classData.classType == ClassType.Enum)
                    {
                        EnvDTE.Document doc2    = dte2.ItemOperations.NewFile("General\\Text File", classData.className).Document;
                        TextSelection   txtsel2 = (TextSelection)doc2.Selection;
                        txtsel2.Text = "";
                        txtsel2.Insert("#pragma once\n\nenum " + classData.className + "\n{\n\n};");
                        doc2.Save(solutionData.directoryPath + "\\Header Files\\" + classData.className + ".h");
                        project.ProjectItems.AddFromFile(solutionData.directoryPath + "\\Header Files\\" + classData.className + ".h");
                    }
                    #endregion
                }
            }
            #endregion
            #region C# Writing
            else //C# Example
            {
                foreach (ProjectItem pItem in project.ProjectItems)
                {
                    if (pItem.Name == "Form1.cs")
                    {
                        pItem.Remove();
                    }
                }

                foreach (ClassData classData in solutionData.classes)
                {
                    if (classData.classType == ClassType.Enum || classData.classType == ClassType.Class || classData.classType == ClassType.Interface)
                    {
                        project.ProjectItems.AddFromTemplate(@"C:\Program Files (x86)\Microsoft Visual Studio " + dte2.Version + @"\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class\Class.vstemplate", classData.className + ".cs");
                    }
                    else if (classData.classType == ClassType.Form)
                    {
                        project.ProjectItems.AddFromTemplate(@"c:\Program Files (x86)\Microsoft Visual Studio " + dte2.Version + @"\Common7\IDE\ItemTemplates\CSharp\Windows Forms\1033\Form\windowsform.vstemplate", classData.className + ".cs");
                    }

                    ProjectItem projectItem = null;
                    foreach (ProjectItem pItem in project.ProjectItems)
                    {
                        if (pItem.Name == classData.className + ".cs")
                        {
                            projectItem = pItem;
                            break;
                        }
                    }

                    projectItem.Save();
                    TextSelection txtsel = (TextSelection)projectItem.Document.Selection;

                    #region Class
                    if (classData.classType == ClassType.Class)
                    {
                        txtsel.GotoLine(9);
                        txtsel.EndOfLine();
                        if (classData.superClassName != "")
                        {
                            txtsel.Insert(" : " + classData.superClassName);

                            foreach (string interfaceName in classData.interfaceNames)
                            {
                                txtsel.Insert(", " + interfaceName);
                            }
                        }
                        else if (classData.interfaceNames.Count != 0)
                        {
                            txtsel.Insert(" : " + classData.interfaceNames[0]);

                            for (int i = 1; i < classData.interfaceNames.Count; ++i)
                            {
                                txtsel.Insert(", " + classData.interfaceNames[i]);
                            }
                        }
                    }
                    #endregion
                    #region Enum
                    else if (classData.classType == ClassType.Enum)
                    {
                        txtsel.GotoLine(9);
                        txtsel.StartOfLine();
                        txtsel.CharRight(false, 4);
                        txtsel.DestructiveInsert("enum");
                        txtsel.Delete();
                    }
                    #endregion
                    #region Interface
                    else if (classData.classType == ClassType.Interface)
                    {
                        txtsel.GotoLine(9);
                        txtsel.StartOfLine();
                        txtsel.CharRight(false, 4);
                        txtsel.Insert("interface");
                        txtsel.Delete(5);
                    }
                    #endregion
                }
            }
            #endregion
        }
Ejemplo n.º 21
0
        void ProcessOpenCSharpConApp(object sender, EventArgs e)
        {
            Debug.WriteLine("Open CSharp Console App");
            IVsOutputWindow outWindow       = Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow;
            Guid            generalPaneGuid = VSConstants.GUID_OutWindowGeneralPane;
            Guid            debugPane       = VSConstants.GUID_OutWindowDebugPane;

            outWindow.GetPane(ref debugPane, out var paneToWriteTo);
            paneToWriteTo.OutputString("Opening start file\r\n");


            DTE dte = (DTE)GetService(typeof(EnvDTE.DTE));

            var prjs = dte.Solution.Projects;

            if (prjs.Count > 0)
            {
                // get full path of solution (including name of solution file):
                string solutionFullPathname = dte.Solution.FullName;

                // extract the directory of the solution:
                string dir = System.IO.Path.GetDirectoryName(solutionFullPathname);

                // get the name of the first project
                string projectName = dte.Solution.Projects.Item(1).Name;

                // combine the solution dir with the project dir and "program.cs":
                string programfname = System.IO.Path.Combine(dir, projectName, "program.cs");
                //System.Windows.Forms.MessageBox.Show("hello: " + programfname);

                dte.ItemOperations.OpenFile(programfname, EnvDTE.Constants.vsViewKindCode);

                var findString = "//startstarttypingtypingherehere";
                paneToWriteTo.OutputString($"opened file {programfname}\r\n");
                paneToWriteTo.OutputString($"searching for {findString}\r\n");

                dte.ActiveDocument.Activate();
                dte.Find.PatternSyntax     = vsFindPatternSyntax.vsFindPatternSyntaxRegExpr;
                dte.Find.FindWhat          = findString;
                dte.Find.Target            = vsFindTarget.vsFindTargetCurrentDocument;
                dte.Find.MatchCase         = false;
                dte.Find.MatchWholeWord    = false;
                dte.Find.Backwards         = false;
                dte.Find.MatchInHiddenText = false;
                dte.Find.Action            = vsFindAction.vsFindActionFind;
                if (dte.Find.Execute() == vsFindResult.vsFindResultNotFound)
                {
                    paneToWriteTo.OutputString($"{findString} not found.\r\n");
                }
                else
                {
                    paneToWriteTo.OutputString($"{findString} found\r\n");
                }
                dte.Windows.Item("{CF2DDC32-8CAD-11D2-9302-005345000000}").Close();
                TextSelection ts = (TextSelection)dte.ActiveDocument.Selection;
                ts.Delete();

                dte.ExecuteCommand("File.SaveAll", string.Empty);
                dte.ExecuteCommand("Build.BuildSolution");
                dte.ActiveDocument.Activate();
            }

            paneToWriteTo.Activate(); // Brings this pane into view
        }
Ejemplo n.º 22
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Moves the up before comment.
        /// </summary>
        /// <param name="sel">The sel.</param>
        /// ------------------------------------------------------------------------------------
        private void MoveUpBeforeComment(TextSelection sel)
        {
            TextRanges textRanges = null;
            for (; true; )
            {
                if (sel.FindPattern("\\<summary\\>|/// ---", (int)(vsFindOptions.vsFindOptionsBackwards | vsFindOptions.vsFindOptionsRegularExpression),
                    ref textRanges))
                {
                    // GhostDoc messes up dashed lines from inherited comments from base class,
                    // so delete those
                    if (sel.Text.StartsWith("/// ---"))
                    {
                        sel.EndOfLine(true);
                        sel.WordRight(true, 1);
                        sel.Delete(1);
                    }
                    else if (sel.Text.StartsWith("<summary>"))
                    {
                        while (true)
                        {
                            sel.MoveToLineAndOffset(sel.ActivePoint.Line - 1, 1, false);
                            sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                            sel.EndOfLine(true);
                            if (!sel.Text.StartsWith("///"))
                            {
                                if (sel.Text.Length > 0)
                                {
                                    // there is a non-empty comment line. We want to start at the end
                                    // of it
                                    sel.EndOfLine(false);
                                }
                                else
                                    sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                                break;
                            }

                            // GhostDoc messes up dashed lines from inherited comments from base class,
                            // so delete those
                            if (sel.Text.StartsWith("/// -----"))
                            {
                                sel.WordRight(true, 1);
                                sel.Delete(1);
                            }
                        }
                        return;
                    }
                }
                else
                    return;
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Runs custom wizard logic when a project has finished generating.
        /// </summary>
        /// <param name="project"></param>
        public void ProjectFinishedGenerating(Project project)
        {
            // Iterate through the project items and
            // remove any files that begin with the word "Placeholder".
            // and the Rates class unless it's the Telescope class
            // done this way to avoid removing items from inside a foreach loop
            List <string> rems = new List <string>();

            foreach (ProjectItem item in project.ProjectItems)
            {
                if (item.Name.StartsWith("Placeholder", StringComparison.OrdinalIgnoreCase) ||
                    item.Name.StartsWith("Rate", StringComparison.OrdinalIgnoreCase) &&
                    !this.DeviceClass.Equals("Telescope", StringComparison.OrdinalIgnoreCase))
                {
                    //MessageBox.Show("adding " + item.Name);
                    rems.Add(item.Name);
                }
            }
            foreach (string item in rems)
            {
                //MessageBox.Show("Deleting " + item);
                project.ProjectItems.Item(item).Delete();
            }

            // Special handling for VB and C# driver template projects to add the interface implementation to the core driver code
            try
            {
                // Check the name of each item in the project and execute if this is a driver template project (contains Driver.vb or Driver.cs)
                foreach (ProjectItem projectItem in project.ProjectItems)
                {
                    TL.LogMessage("ProjectFinishedGenerating", "Item name: " + projectItem.Name);
                    if ((projectItem.Name.ToUpperInvariant() == "DRIVER.CS") | (projectItem.Name.ToUpperInvariant() == "DRIVER.VB"))
                    {
                        driverTemplate = projectItem; // Save the driver item
                        // This is a driver template
                        // Get the filename and directory of the Driver.xx file
                        string directory = Path.GetDirectoryName(projectItem.FileNames[1].ToString());
                        TL.LogMessage("ProjectFinishedGenerating", "File name: " + projectItem.FileNames[1].ToString() + ", Directory: " + directory);
                        TL.LogMessage("ProjectFinishedGenerating", "Found " + projectItem.Name);

                        projectItem.Open(); // Open the item for editing
                        TL.LogMessage("ProjectFinishedGenerating", "Done Open");

                        Document itemDocument = projectItem.Document; // Get the open file's document object
                        TL.LogMessage("ProjectFinishedGenerating", "Created Document");

                        itemDocument.Activate(); // Make this the current document
                        TL.LogMessage("ProjectFinishedGenerating", "Activated Document");

                        TextSelection documentSelection = (TextSelection)itemDocument.Selection; // Create a document selection
                        TL.LogMessage("ProjectFinishedGenerating", "Created Selection object");

                        const string insertionPoint = "//INTERFACECODEINSERTIONPOINT"; // Find the insertion point in the Driver.xx item
                        documentSelection.FindText(insertionPoint, (int)vsFindOptions.vsFindOptionsMatchWholeWord);
                        TL.LogMessage("ProjectFinishedGenerating", "Done INTERFACECODEINSERTIONPOINT FindText:" + documentSelection.Text);

                        // Create the name of the device interface file to be inserted
                        string insertFile = directory + "\\Device" + this.DeviceClass + Path.GetExtension(projectItem.Name);
                        TL.LogMessage("ProjectFinishedGenerating", "Opening file: " + insertFile);

                        documentSelection.InsertFromFile(insertFile); // Insert the required file at the current selection point
                        TL.LogMessage("ProjectFinishedGenerating", "Done InsertFromFile");

                        // Remove the top lines of the inserted file until we get to #Region
                        // These lines are only there to make the file error free in the template develpment project and are not required here
                        documentSelection.SelectLine(); // Select the current line
                        TL.LogMessage("ProjectFinishedGenerating", "Selected initial line: " + documentSelection.Text);
                        while (!documentSelection.Text.ToUpperInvariant().Contains("#REGION"))
                        {
                            TL.LogMessage("ProjectFinishedGenerating", "Deleting start line: " + documentSelection.Text);
                            documentSelection.Delete();     // Delete the current line
                            documentSelection.SelectLine(); // Select the new current line ready to test on the next loop
                        }

                        // Find the end of file marker that came from the inserted file
                        const string endOfInsertFile = "//ENDOFINSERTEDFILE";
                        documentSelection.FindText(endOfInsertFile, (int)vsFindOptions.vsFindOptionsMatchWholeWord);
                        TL.LogMessage("ProjectFinishedGenerating", "Done ENDOFINSERTEDFILE FindText:" + documentSelection.Text);

                        // Delete the marker line and the last 2 lines from the inserted file
                        documentSelection.SelectLine();
                        TL.LogMessage("ProjectFinishedGenerating", "Found end line: " + documentSelection.Text);
                        while (!documentSelection.Text.ToUpperInvariant().Contains("#REGION"))
                        {
                            TL.LogMessage("ProjectFinishedGenerating", "Deleting end line: " + documentSelection.Text);
                            documentSelection.Delete();     // Delete the current line
                            documentSelection.SelectLine(); // Select the new current line ready to test on the next loop
                            TL.LogMessage("ProjectFinishedGenerating", "Found end line: " + documentSelection.Text);
                        }

                        // Reformat the document to make it look pretty
                        documentSelection.SelectAll();
                        TL.LogMessage("ProjectFinishedGenerating", "Done SelectAll");
                        documentSelection.SmartFormat();
                        TL.LogMessage("ProjectFinishedGenerating", "Done SmartFormat");

                        itemDocument.Save(); // Save the edited file readyfor use!
                        TL.LogMessage("ProjectFinishedGenerating", "Done Save");
                        itemDocument.Close(vsSaveChanges.vsSaveChangesYes);
                        TL.LogMessage("ProjectFinishedGenerating", "Done Close");
                    }
                }

                // Iterate through the project items and remove any files that begin with the word "Device".
                // These are the partial device implementations that are merged in to create a complete device driver template by the code above
                // They are not required in the final project

                // Done this way to avoid removing items from inside a foreach loop
                rems = new List <string>();
                foreach (ProjectItem item in project.ProjectItems)
                {
                    if (item.Name.StartsWith("Device", StringComparison.OrdinalIgnoreCase))
                    {
                        //MessageBox.Show("adding " + item.Name);
                        rems.Add(item.Name);
                    }
                }
                foreach (string item in rems)
                {
                    TL.LogMessage("ProjectFinishedGenerating", "Deleting file: " + item);
                    project.ProjectItems.Item(item).Delete();
                }
            }
            catch (Exception ex)
            {
                TL.LogMessageCrLf("ProjectFinishedGenerating Exception", ex.ToString());                                              // Log any error message
                MessageBox.Show(ex.ToString(), "ProjectFinishedGenerating Wizard Error", MessageBoxButtons.OK, MessageBoxIcon.Error); // Show an error message
            }

            TL.LogMessage("ProjectFinishedGenerating", "End");
            TL.Enabled = false;
        }
Ejemplo n.º 24
0
        public void Apply(TextSelection selection)
        {
            if (Inline)
            {
                ApplyInline(selection);
                return;
            }

            var closeUndoContext = false;

            if (!selection.DTE.UndoContext.IsOpen)
            {
                selection.BeginUpdate("Surround With " + Name);
                closeUndoContext = true;
            }

            if (_extendSelection)
            {
                selection.ExtendToFullLine();
            }
            var indentSize = selection.Text.Lines().Where(l => !string.IsNullOrWhiteSpace(l)).Min(l => l.Length - l.TrimStart().Length);

            var content = selection.Text.Lines();

            var leadingSpace = new string(' ', indentSize);
            var indent       = new string(' ', selection.Parent.IndentSize);

            var sb = new StringBuilder();

            foreach (var s in _preText)
            {
                sb.Append(leadingSpace).AppendLine(s);
            }

            foreach (var s in content)
            {
                if (_indentSelection)
                {
                    sb.Append(indent);
                }
                sb.AppendLine(s);
            }

            foreach (var s in _postText)
            {
                sb.Append(leadingSpace).AppendLine(s);
            }

            var line = selection.TopLine;
            var col  = selection.TopPoint.DisplayColumn;

            selection.Delete();
            selection.Insert(sb.ToString());

            if (_caretLine >= _preText.Length)
            {
                selection.MoveToLineAndOffset(line + _caretLine + content.Count, _caretCol + indentSize, false);
            }
            else if (_caretLine >= 0)
            {
                selection.MoveToLineAndOffset(line + _caretLine, _caretCol + indentSize, false);
            }
            else
            {
                selection.MoveToDisplayColumn(line, col, true);
            }

            if (closeUndoContext)
            {
                selection.EndUpdate();
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Generates a Doxygen comment block to the current caret location.
        /// </summary>
        private void GenerateComment()
        {
            var    currentILine = m_textView.TextSnapshot.GetLineFromPosition(m_textView.Caret.Position.BufferPosition.Position);
            int    len          = m_textView.Caret.Position.BufferPosition.Position - currentILine.Start.Position;
            string currentLine  = m_textView.TextSnapshot.GetText(currentILine.Start.Position, len);
            string spaces       = currentLine.Replace(currentLine.TrimStart(), "");
            string next2char    = m_textView.TextSnapshot.GetText(currentILine.Start.Position + len, 2);

            ThreadHelper.ThrowIfNotOnUIThread();
            TextSelection ts = m_dte.ActiveDocument.Selection as TextSelection;

            // Save current care position.
            int oldLine   = ts.ActivePoint.Line;
            int oldOffset = ts.ActivePoint.LineCharOffset;

            // Removing the auto inserted "*/"
            if (next2char == "*/")
            {
                ts.Delete(2);
            }

            // Check if we're at the beginning of the document and should generate a file comment.
            if (oldLine == 1)
            {
                string fileComment = m_generator.GenerateFileComment(m_dte, out int selectedLine);
                ts.DeleteLeft(2); // Removing the // part here.

                ts.Insert(fileComment);

                // Move the caret.
                ts.MoveToLineAndOffset(selectedLine + 1, 1);

                ts.EndOfLine();
                return;
            }

            // Search for the associated code element for which to generate the comment.
            CodeElement codeElement = null;

            ts.LineDown();
            ts.EndOfLine();

            FileCodeModel fcm = this.GetFileCodeModel(m_dte.ActiveDocument);

            if (fcm != null)
            {
                while (codeElement == null)
                {
                    codeElement = CodeElementFromPoint(fcm, ts.ActivePoint,
                                                       vsCMElement.vsCMElementNamespace,
                                                       vsCMElement.vsCMElementClass,
                                                       vsCMElement.vsCMElementStruct,
                                                       vsCMElement.vsCMElementEnum,
                                                       vsCMElement.vsCMElementFunction,
                                                       vsCMElement.vsCMElementUnion);

                    if (ts.ActivePoint.AtEndOfDocument)
                    {
                        break;
                    }

                    if (codeElement == null)
                    {
                        ts.LineDown();
                    }
                }

                // if active line is in function body, set codeElement to null
                if (codeElement is CodeFunction function && oldLine > codeElement.StartPoint.Line && oldLine < codeElement.EndPoint.Line)
                {
                    codeElement = null;
                }
            }

            // Generate the comment and add it to the document.
            string doxyComment = m_generator.GenerateComment(spaces, codeElement, "");

            ts.MoveToLineAndOffset(oldLine, oldOffset);
            ts.DeleteLeft(2); // Removing the // part here.
            ts.Insert(doxyComment);


            if (!m_generator.UseSingleLineComment(codeElement))
            {
                // Move caret to the position where the main comment will be written.
                ts.MoveToLineAndOffset(oldLine, oldOffset);
                ts.LineDown();
                ts.EndOfLine();
            }
            else
            {
                ts.MoveToLineAndOffset(oldLine, oldOffset + 2);
            }
        }
Ejemplo n.º 26
0
 void BeforeKeyPress(string Keypress, TextSelection Selection, bool InStatementCompletion, ref bool CancelKeypress)
 {
     if (isOn) {
         bool isAlpha = (Keypress[0] >= 'A' && Keypress[0] <= 'Z') || (Keypress[0] >= 'a' && Keypress[0] <= 'z');
         bool swap = Selection.IsActiveEndGreater;
         if (isAlpha) {
             if (!nextShouldBeCaps) {
                 if (swap)
                     Selection.SwapAnchor();
                 Selection.CharLeft(true);
                 if (Selection.Text[0] == '_')
                     nextShouldBeCaps = true;
                 Selection.CharRight(true);
                 if (swap)
                     Selection.SwapAnchor();
             }
             if (nextShouldBeCaps) {
                 CancelKeypress = true;
                 if (!Selection.IsEmpty) {
                     Selection.Delete();
                 }
                 Selection.Insert(Keypress.ToUpper());
             }
         } else if (Keypress == " ") {
             CancelKeypress = true;
             if (!Selection.IsEmpty) {
                 Selection.Delete();
             }
             Selection.Insert("_");
         } else if (Keypress == "(") {
             CancelKeypress = false;
             ToggleIsOn();
         }
         nextShouldBeCaps = false;
     }
 }
Ejemplo n.º 27
0
        /// <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.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormatSelectionOrActiveWindow"))
                {
                    string fileExtension = System.IO.Path.GetExtension(_applicationObject.ActiveDocument.FullName);
                    bool   isSqlFile     = fileExtension.ToUpper().Equals(".SQL");

                    if (isSqlFile ||
                        MessageBox.Show(_generalResourceManager.GetString("FileTypeWarningMessage"), _generalResourceManager.GetString("FileTypeWarningMessageTitle"), MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        string        fullText  = SelectAllCodeFromDocument(_applicationObject.ActiveDocument);
                        TextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection;
                        if (!selection.IsActiveEndGreater)
                        {
                            selection.SwapAnchor();
                        }
                        if (selection.Text.EndsWith(Environment.NewLine) || selection.Text.EndsWith(" "))
                        {
                            selection.CharLeft(true, 1); //newline counts as a distance of one.
                        }
                        string selectionText       = selection.Text;
                        bool   formatSelectionOnly = selectionText.Length > 0 && selectionText.Length != fullText.Length;
                        int    cursorPoint         = selection.ActivePoint.AbsoluteCharOffset;

                        string textToFormat  = formatSelectionOnly ? selectionText : fullText;
                        bool   errorsFound   = false;
                        string formattedText = _formattingManager.Format(textToFormat, ref errorsFound);

                        bool abortFormatting = false;
                        if (errorsFound)
                        {
                            abortFormatting = MessageBox.Show(_generalResourceManager.GetString("ParseErrorWarningMessage"), _generalResourceManager.GetString("ParseErrorWarningMessageTitle"), MessageBoxButtons.YesNo) != DialogResult.Yes;
                        }

                        if (!abortFormatting)
                        {
                            if (formatSelectionOnly)
                            {
                                //if selection just delete/insert, so the active point is at the end of the selection
                                selection.Delete(1);
                                selection.Insert(formattedText, (int)EnvDTE.vsInsertFlags.vsInsertFlagsContainNewText);
                            }
                            else
                            {
                                //if whole doc then replace all text, and put the cursor approximately where it was (using proportion of text total length before and after)
                                int newPosition = (int)Math.Round(1.0 * cursorPoint * formattedText.Length / textToFormat.Length, 0, MidpointRounding.AwayFromZero);
                                ReplaceAllCodeInDocument(_applicationObject.ActiveDocument, formattedText);
                                ((TextSelection)(_applicationObject.ActiveDocument.Selection)).MoveToAbsoluteOffset(newPosition, false);
                            }
                        }
                    }

                    handled = true;
                    return;
                }
                if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormattingOptions"))
                {
                    GetFormatHotkey();
                    SettingsForm settings = new SettingsForm(Properties.Settings.Default, Assembly.GetExecutingAssembly(), _generalResourceManager.GetString("ProjectAboutDescription"), new SettingsForm.GetTextEditorKeyBindingScopeName(GetTextEditorKeyBindingScopeName));
                    if (settings.ShowDialog() == DialogResult.OK)
                    {
                        SetFormatHotkey();
                        _formattingManager = Utils.GetFormattingManager(Properties.Settings.Default);
                    }
                    settings.Dispose();
                }
            }
        }
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuFormatCallback(object sender, EventArgs e)
        {
            if (_applicationObject.ActiveDocument == null)
            {
                return;
            }

            string fileExtension = System.IO.Path.GetExtension(_applicationObject.ActiveDocument.FullName);
            bool   isSqlFile     = fileExtension.ToUpper().Equals(".SQL");

            if (isSqlFile ||

                VsShellUtilities.ShowMessageBox(
                    this.ServiceProvider,
                    _generalResourceManager.GetString("FileTypeWarningMessage"),
                    _generalResourceManager.GetString("FileTypeWarningMessageTitle"),
                    OLEMSGICON.OLEMSGICON_INFO,
                    OLEMSGBUTTON.OLEMSGBUTTON_YESNO,
                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
                    ) == OLEMSGRESULT_YES)
            {
                string        fullText  = SelectAllCodeFromDocument(_applicationObject.ActiveDocument);
                TextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection;
                if (!selection.IsActiveEndGreater)
                {
                    selection.SwapAnchor();
                }
                if (selection.Text.EndsWith(Environment.NewLine) || selection.Text.EndsWith(" "))
                {
                    selection.CharLeft(true, 1); //newline counts as a distance of one.
                }
                string selectionText       = selection.Text;
                bool   formatSelectionOnly = selectionText.Length > 0 && selectionText.Length != fullText.Length;
                int    cursorPoint         = selection.ActivePoint.AbsoluteCharOffset;

                string textToFormat  = formatSelectionOnly ? selectionText : fullText;
                bool   errorsFound   = false;
                string formattedText = _formattingManager.Format(textToFormat, ref errorsFound);

                bool abortFormatting = false;
                if (errorsFound)
                {
                    abortFormatting =
                        VsShellUtilities.ShowMessageBox(
                            this.ServiceProvider,
                            _generalResourceManager.GetString("ParseErrorWarningMessage"),
                            _generalResourceManager.GetString("ParseErrorWarningMessageTitle"),
                            OLEMSGICON.OLEMSGICON_INFO,
                            OLEMSGBUTTON.OLEMSGBUTTON_YESNO,
                            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
                            ) != OLEMSGRESULT_YES;
                }

                if (!abortFormatting)
                {
                    if (formatSelectionOnly)
                    {
                        //if selection just delete/insert, so the active point is at the end of the selection
                        selection.Delete(1);
                        selection.Insert(formattedText, (int)EnvDTE.vsInsertFlags.vsInsertFlagsContainNewText);
                    }
                    else
                    {
                        //if whole doc then replace all text, and put the cursor approximately where it was (using proportion of text total length before and after)
                        //int newPosition = (int)Math.Round(1.0 * cursorPoint * formattedText.Length / textToFormat.Length, 0, MidpointRounding.AwayFromZero);
                        ReplaceAllCodeInDocument(_applicationObject.ActiveDocument, formattedText);
                        //((TextSelection)(_applicationObject.ActiveDocument.Selection)).MoveToAbsoluteOffset(newPosition, false);
                    }
                }
            }
        }
Ejemplo n.º 29
0
        public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            try
            {
                if (VsShellUtilities.IsInAutomationFunction(m_provider.ServiceProvider))
                {
                    return(m_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut));
                }

                // make a copy of this so we can look at it after forwarding some commands
                uint commandID = nCmdID;
                char typedChar = char.MinValue;

                // make sure the input is a char before getting it
                if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (uint)VSConstants.VSStd2KCmdID.TYPECHAR)
                {
                    typedChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn);
                }
                if (m_dte != null)
                {
                    string currentLine = m_textView.TextSnapshot.GetLineFromPosition(
                        m_textView.Caret.Position.BufferPosition.Position).GetText();

                    // check for the Javadoc slash and two asterisk pattern while compensating for visual studio's block comment closing generation
                    if (typedChar == '*' && currentLine.Trim() == "/**/")
                    {
                        // Calculate how many spaces
                        string        spaces = currentLine.Replace(currentLine.TrimStart(), "");
                        TextSelection ts     = m_dte.ActiveDocument.Selection as TextSelection;
                        //Remember where the cursor was when command was triggered
                        int oldLine   = ts.ActivePoint.Line;
                        int oldOffset = ts.ActivePoint.LineCharOffset;
                        ts.LineDown();
                        ts.EndOfLine();
                        ts.SelectLine();

                        //Detect and skip over Unreal Engine Function Macros
                        string trimmedFuncLine = ts.Text.Trim();
                        if (trimmedFuncLine != "" && trimmedFuncLine.StartsWith("UFUNCTION("))
                        {
                            ts.EndOfLine();
                        }
                        else
                        {
                            ts.MoveToLineAndOffset(oldLine, oldOffset);
                            ts.LineDown();
                            ts.EndOfLine();
                        }

                        CodeElement   codeElement = null;
                        FileCodeModel fcm         = m_dte.ActiveDocument.ProjectItem.FileCodeModel;
                        if (fcm != null)
                        {
                            codeElement = fcm.CodeElementFromPoint(ts.ActivePoint, vsCMElement.vsCMElementFunction);
                        }

                        if (codeElement != null && codeElement is CodeFunction)
                        {
                            CodeFunction  function         = codeElement as CodeFunction;
                            StringBuilder sb               = new StringBuilder("*");
                            bool          isNoArgsNoReturn = true;
                            foreach (CodeElement child in codeElement.Children)
                            {
                                CodeParameter parameter = child as CodeParameter;
                                if (parameter != null)
                                {
                                    sb.AppendFormat("\r\n" + spaces + " * @param {0} ", parameter.Name);
                                    isNoArgsNoReturn = false;
                                }
                            }

                            if (function.Type.AsString != "void")
                            {
                                isNoArgsNoReturn = false;
                                if (function.Type.AsString == "bool")
                                {
                                    sb.AppendFormat("\r\n" + spaces + " * @return true \r\n" + spaces + " * @return false ");
                                }
                                else
                                {
                                    sb.AppendFormat("\r\n" + spaces + " * @return ");
                                }
                            }

                            //If function has a return type or parameters then we generate them and return, otherwise we skip to generate a single line comment
                            if (!isNoArgsNoReturn)
                            {
                                sb.Insert(1, "\r\n" + spaces + " * ");
                                sb.AppendFormat("\r\n" + spaces + " ");
                                ts.MoveToLineAndOffset(oldLine, oldOffset);
                                ts.Insert(sb.ToString());
                                ts.MoveToLineAndOffset(oldLine, oldOffset);
                                ts.LineDown();
                                ts.EndOfLine();
                                return(VSConstants.S_OK);
                            }
                        }
                        //For variables and void functions with no parameters we can do a single line comment
                        ts.MoveToLineAndOffset(oldLine, oldOffset);
                        ts.Insert("*  ");
                        ts.MoveToLineAndOffset(oldLine, oldOffset + 2);
                        return(VSConstants.S_OK);
                    }
                    else if (nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN)
                    {
                        //Get text on current line before and after cursor
                        TextSelection ts        = m_dte.ActiveDocument.Selection as TextSelection;
                        int           oldLine   = ts.ActivePoint.Line;
                        int           oldOffset = ts.ActivePoint.LineCharOffset;
                        ts.EndOfLine(true);
                        string afterCursor = ts.Text;
                        ts.MoveToLineAndOffset(oldLine, oldOffset);
                        ts.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn, true);
                        string beforeCursor        = ts.Text;
                        string beforeCursorTrimmed = beforeCursor.TrimStart();
                        ts.MoveToLineAndOffset(oldLine, oldOffset);

                        // Calculate how many spaces
                        string spaces = beforeCursorTrimmed == "" ? beforeCursor : beforeCursor.Replace(beforeCursorTrimmed, "");

                        bool hasAsteriskBeforeCursor               = beforeCursorTrimmed == "" ? false : beforeCursorTrimmed.StartsWith("* ");
                        bool hasBlockTerminatorAfterCursor         = afterCursor == "" ? false : afterCursor.EndsWith("*/");
                        bool hasBlockTerminatorDirectlyAfterCursor = hasBlockTerminatorAfterCursor && afterCursor.Trim() == "*/";

                        //Add a space to maintain correct asterisk alignment if needed
                        if (beforeCursorTrimmed != "" && beforeCursorTrimmed.StartsWith("/*"))
                        {
                            hasAsteriskBeforeCursor = true;
                            spaces += " ";
                        }

                        if (hasAsteriskBeforeCursor)
                        {
                            ts.Insert("\r\n" + spaces);
                            if (!hasBlockTerminatorAfterCursor)
                            {
                                ts.Insert("* ");
                            }
                            else if (hasBlockTerminatorDirectlyAfterCursor)
                            {
                                ts.Delete(afterCursor.Length);
                                ts.Insert("*/");
                                ts.MoveToLineAndOffset(ts.ActivePoint.Line, ts.ActivePoint.LineCharOffset - 2);
                            }
                            return(VSConstants.S_OK);
                        }
                        else if (hasBlockTerminatorAfterCursor)
                        {
                            ts.Insert("* \r\n" + spaces);
                            if (hasBlockTerminatorDirectlyAfterCursor)
                            {
                                ts.Delete(afterCursor.Length);
                                ts.Insert("*/");
                                ts.MoveToLineAndOffset(ts.ActivePoint.Line, ts.ActivePoint.LineCharOffset - 2);
                            }
                            return(VSConstants.S_OK);
                        }
                    }
                }
                // pass along the command so the char is added to the buffer
                return(m_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut));
            }
            catch
            {
            }

            return(VSConstants.E_FAIL);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            DTE          dte    = Package.GetGlobalService(typeof(DTE)) as DTE;
            Document     doc    = dte.ActiveDocument;
            TextDocument txtDoc = doc.Object() as TextDocument;
            var          text   = txtDoc.CreateEditPoint(txtDoc.StartPoint).GetText(txtDoc.EndPoint);

            text = text.Replace("\r", "");

            uint cookie = 0;

            StatusBar.Progress(ref cookie, 1, string.Empty, 0, 0);

            if (txtDoc.Language == "HTMLX" || txtDoc.Language == "HTML")
            {
                var html           = text;
                var elementList    = new List <HtmlElement>();
                var parsed         = _parser.ParseHtml(html, elementList, txtDoc, StatusBar, ref cookie);
                var cssFileContent = string.Empty;

                if (elementList.Any())
                {
                    foreach (var item in elementList)
                    {
                        var cssClass = string.Empty;
                        if (string.IsNullOrEmpty(item.Class))
                        {
                            cssClass = string.Format(".{0}", string.IsNullOrEmpty(item.Id) ? CreateUniqueElementKey(item.Name, item.LineNumber) : item.Id);
                        }
                        else
                        {
                            cssClass = string.Format(".{0} .{1}", item.Class, CreateUniqueElementKey(item.Name, item.LineNumber));
                        }

                        var idAttr      = string.IsNullOrEmpty(item.Id) ? string.Empty : string.Format("id=\"{0}\"", item.Id);
                        var replaceText = string.Format("{0} {1} class=\"{2}\"", item.Name, idAttr, cssClass.Replace(".", string.Empty));

                        parsed          = parsed.Replace(item.Guid, replaceText);
                        cssFileContent += string.Format("{0}{{{1}}}\n\n", cssClass, "\n" + item.Style);
                    }

                    //css file beautification
                    cssFileContent = cssFileContent.Replace(";", ";\n");

                    //update html file
                    TextSelection txtSelHtml = (TextSelection)doc.Selection;
                    txtSelHtml.SelectAll();
                    txtSelHtml.Delete();
                    txtSelHtml.Insert(parsed);

                    //create css file
                    var docName = doc.Name.Substring(0, doc.Name.IndexOf('.'));
                    docName = string.Format("{0}.css", docName);
                    string solutionDir = System.IO.Path.GetDirectoryName(dte.Solution.FullName);
                    dte.ItemOperations.NewFile(@"General\Text File", docName, EnvDTE.Constants.vsViewKindTextView);
                    TextSelection txtSelCss = (TextSelection)dte.ActiveDocument.Selection;
                    txtSelCss.SelectAll();
                    txtSelCss.Delete();
                    txtSelCss.Insert(cssFileContent);
                }
                else
                {
                    VsShellUtilities.ShowMessageBox(this.ServiceProvider, "Not found inline css.", "That's Cool!",
                                                    OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                }
            }
            else
            {
                VsShellUtilities.ShowMessageBox(this.ServiceProvider, "This is not a html file!", "Oops!",
                                                OLEMSGICON.OLEMSGICON_WARNING, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
            }

            // Clear the progress bar.
            StatusBar.Progress(ref cookie, 0, string.Empty, 0, 0);
            StatusBar.FreezeOutput(0);
            StatusBar.Clear();
        }