/// <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)
        {
            DTE2 dte = GetDTE();

            try
            {
                Document activeDoc = dte.ActiveDocument;

                if (activeDoc != null && activeDoc.ProjectItem != null && activeDoc.ProjectItem.ContainingProject != null)
                {
                    TextDocument objTextDoc      = activeDoc.Object("TextDocument") as TextDocument;
                    EditPoint2   startPoint      = objTextDoc.StartPoint.CreateEditPoint() as EditPoint2;
                    EditPoint2   endPoint        = objTextDoc.EndPoint.CreateEditPoint() as EditPoint2;
                    string       wholeWindowText = startPoint.GetText(endPoint);
                    wholeWindowText = Regex.Replace(wholeWindowText, @"^\s+${2,}", string.Empty, RegexOptions.Multiline);

                    wholeWindowText = Regex.Replace(wholeWindowText, @"\r\n\n\s*\}\r\n\s*$", "\r\n}\r\n", RegexOptions.Multiline);
                    wholeWindowText = Regex.Replace(wholeWindowText, @"\r\n\n\s*\}", "\r\n}", RegexOptions.Multiline);
                    wholeWindowText = Regex.Replace(wholeWindowText, @"\{\r\n\n", "{\r\n", RegexOptions.Multiline);
                    startPoint.ReplaceText(endPoint, wholeWindowText, 3);
                    startPoint.SmartFormat(endPoint);

                    dte.ActiveDocument.Activate();
                    dte.ExecuteCommand("Edit.FormatDocument");
                    dte.ExecuteCommand("Edit.SortUsings");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
            }
        }
        protected bool makeSemicolon(TextSelection textSelection)
        {
            EditPoint2 epend   = textSelection.ActivePoint.CreateEditPoint() as EditPoint2;
            EditPoint2 epbegin = textSelection.ActivePoint.CreateEditPoint() as EditPoint2;

            epbegin.StartOfLine();

            String strOrgText = epbegin.GetText(epend);

            // Check for bracket pair
            int bOpen  = 0;
            int bClose = 0;

            foreach (char c in strOrgText.Trim())
            {
                if (c == '}')
                {
                    ++bClose;
                }
                if (c == '{')
                {
                    ++bOpen;
                }
            }

            if (bClose != bOpen)
            {
                m_logger.Log(String.Format("{0}: CodeBeautifier encounter error while parsing line ( bracket not equal ).", m_appOptions.name));
                return(false);
            }

            String strNewText = getLeadingWhiteSpace(strOrgText) + makeText(strOrgText, textSelection.Parent.Parent.FullName);

            if (String.IsNullOrEmpty(strOrgText) || String.IsNullOrEmpty(strNewText))
            {
                m_logger.Log(String.Format("{0}: CodeBeautifier encounter error while parsing document.", m_appOptions.name));
                return(false);
            }

            if (strNewText.Equals(strOrgText))
            {
                m_logger.Log(String.Format("{0}: No changes after document format.", m_appOptions.name), OptionsGeneral.LoggerPriority.Medium);
                return(true);
            }

            epbegin.ReplaceText(epend, strNewText, (int)(vsEPReplaceTextOptions.vsEPReplaceTextKeepMarkers | vsEPReplaceTextOptions.vsEPReplaceTextNormalizeNewlines));

            return(false);
        }
        /// <summary>Parses for strings by iterating through the text lines.</summary>
        /// <param name="element">The element.</param>
        /// <param name="stringResources">The string resources.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="isCSharp">If set to <c>true</c> it is CSharp code.</param>
        /// <param name="startLine">The start line.</param>
        /// <param name="endLine">The end line.</param>
        /// <returns>The last parsed line number or -1.</returns>
        private int ParseForStrings(CodeElement element,
                                    List <StringResource> stringResources,
                                    ISettings settings,
                                    bool isCSharp,
                                    int startLine,
                                    int endLine)
        {
            TextPoint startPoint = element.StartPoint;
            TextPoint endPoint   = element.EndPoint;

            try
            {
                if (element.Kind == vsCMElement.vsCMElementFunction)
                {
                    try
                    {
                        //we want to have the body only (throws COMException when inspecting an expression bodied function)
                        startPoint = element.GetStartPoint(vsCMPart.vsCMPartBody);
                        endPoint   = element.GetEndPoint(vsCMPart.vsCMPartBody);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.Print("ParseForStrings(vsCMElementFunction, line {0}): {1} - {2}", startPoint.Line, ex.GetType().Name, ex.Message);
                    }
                }

                EditPoint2 editPoint = startPoint.CreateEditPoint() as EditPoint2;

                int    editLine   = editPoint.Line;
                int    editColumn = editPoint.LineCharOffset;
                string text       = editPoint.GetText(endPoint);

                ICodeTools             codeTools        = ViewModelLocator.Instance.GetInstance <ICodeTools>();
                List <CodeTextElement> codeTextelements = codeTools.GetCodeElements(editLine, text);
                List <CodeTextLine>    textLines        = codeTools.GetFilteredLines(
                    codeTextelements, settings);

                bool isComment = false;

                FindStringsInCodeBlock(
                    textLines, editColumn, startLine, endLine, stringResources, settings, ref isComment);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Print("### Error: ParseForStrings(): {0} - {1}", ex.GetType().Name, ex.Message);
            }

            return(endPoint?.Line ?? (-1));
        }
Esempio n. 4
0
        private string GetTestsOutput()
        {
            Window       outputToolWindow = this.dte.Windows.Item(Constants.vsWindowKindOutput);
            OutputWindow outputWindow     = (OutputWindow)outputToolWindow.Object;

            OutputWindowPane outputWindowPane = outputWindow.OutputWindowPanes.Item("Tests");

            // Create a reference to the pane contents.
            // Select the Tests pane in the Output window.
            outputWindowPane.Activate();
            TextDocument outputWindowPaneTextDocument = outputWindowPane.TextDocument;

            // Retrieve the text contents of the pane.
            EditPoint2 strtPt = (EditPoint2)outputWindowPaneTextDocument.StartPoint.CreateEditPoint();

            return(strtPt.GetText(outputWindowPaneTextDocument.EndPoint));
        }
        /// <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 Execute(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            string message = string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.GetType().FullName);
            string title   = "DeleteBlankLine";

            // Show a message box to prove we were here
            VsShellUtilities.ShowMessageBox(
                this.package,
                message,
                title,
                OLEMSGICON.OLEMSGICON_INFO,
                OLEMSGBUTTON.OLEMSGBUTTON_OK,
                OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);

            DTE2 dte = GetDTE();

            try
            {
                Document activeDoc = dte.ActiveDocument;

                if (activeDoc != null && activeDoc.ProjectItem != null && activeDoc.ProjectItem.ContainingProject != null)
                {
                    TextDocument objTextDoc      = activeDoc.Object("TextDocument") as TextDocument;
                    EditPoint2   startPoint      = objTextDoc.StartPoint.CreateEditPoint() as EditPoint2;
                    EditPoint2   endPoint        = objTextDoc.EndPoint.CreateEditPoint() as EditPoint2;
                    string       wholeWindowText = startPoint.GetText(endPoint);
                    wholeWindowText = Regex.Replace(wholeWindowText, @"^\s+${2,}", string.Empty, RegexOptions.Multiline);

                    wholeWindowText = Regex.Replace(wholeWindowText, @"\r\n\n\s*\}\r\n\s*$", "\r\n}\r\n", RegexOptions.Multiline);
                    wholeWindowText = Regex.Replace(wholeWindowText, @"\r\n\n\s*\}", "\r\n}", RegexOptions.Multiline);
                    wholeWindowText = Regex.Replace(wholeWindowText, @"\{\r\n\n", "{\r\n", RegexOptions.Multiline);
                    startPoint.ReplaceText(endPoint, wholeWindowText, 3);
                    startPoint.SmartFormat(endPoint);

                    dte.ActiveDocument.Activate();
                    dte.ExecuteCommand("Edit.FormatDocument");
                    dte.ExecuteCommand("Edit.SortUsings");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
            }
        }
Esempio n. 6
0
        protected bool makeBracketClose(TextSelection textSelection)
        {
            EditPoint2 epend   = textSelection.ActivePoint.CreateEditPoint() as EditPoint2;
            EditPoint2 epbegin = textSelection.ActivePoint.CreateEditPoint() as EditPoint2;

            String bracketOpen;
            int    otherbracket = 0;

            do
            {
                EditPoint2 last = epbegin.CreateEditPoint() as EditPoint2;
                epbegin.CharLeft();
                bracketOpen = epbegin.GetText(last);

                if (bracketOpen.CompareTo("}") == 0)
                {
                    ++otherbracket;
                }
                if (bracketOpen.CompareTo("{") == 0)
                {
                    --otherbracket;
                }

                if (epbegin.AtStartOfDocument &&
                    (bracketOpen.CompareTo("{") != 0 || otherbracket != 0))
                {
                    return(false);
                }
            } while(bracketOpen.CompareTo("{") != 0 || otherbracket != 0);

            epbegin.StartOfLine();

            String strOrgText = epbegin.GetText(epend);
            String strNewText = makeText(strOrgText, textSelection.Parent.Parent.FullName);

            if (String.IsNullOrEmpty(strOrgText) || String.IsNullOrEmpty(strNewText))
            {
                m_logger.Log(String.Format("{0}: CodeBeautifier encounter error while parsing document.", m_appOptions.name));
                return(false);
            }

            // Insert leading white space to each line
            String strNewIdentText   = String.Empty;
            String leadingWhiteSpace = getLeadingWhiteSpace(strOrgText);

            using (StringReader reader = new StringReader(strNewText))
            {
                string line = reader.ReadLine();
                do
                {
                    strNewIdentText += leadingWhiteSpace + line;

                    line = reader.ReadLine();
                    if (line != null)
                    {
                        strNewIdentText += Environment.NewLine;
                    }
                } while(line != null);
            }

            if (strNewIdentText.Equals(strOrgText))
            {
                m_logger.Log(String.Format("{0}: No changes after document format.", m_appOptions.name), OptionsGeneral.LoggerPriority.Medium);
                return(true);
            }

            epbegin.ReplaceText(epend, strNewIdentText, (int)(vsEPReplaceTextOptions.vsEPReplaceTextKeepMarkers | vsEPReplaceTextOptions.vsEPReplaceTextNormalizeNewlines));

            return(true);
        }
        /// <summary>Parses for strings by iterating through the text lines.</summary>
        /// <param name="element">The element.</param>
        /// <param name="stringResources">The string resources.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="isCSharp">If set to <c>true</c> it is CSharp code.</param>
        /// <param name="startLine">The start line.</param>
        /// <param name="endLine">The end line.</param>
        /// <returns>The last parsed line number or -1.</returns>
        private static int ParseForStrings(CodeElement element,
                                           List <StringResource> stringResources,
                                           Settings settings,
                                           bool isCSharp,
                                           int startLine,
                                           int endLine)
        {
            TextPoint startPoint = element.StartPoint,
                      endPoint   = element.EndPoint;
            EditPoint2 editPoint = null;

            try
            {
                if (element.Kind == vsCMElement.vsCMElementFunction)
                {
#if DEBUG_OUTPUT
                    System.Diagnostics.Debug.Print("    function kind: {0}", (element as CodeFunction).FunctionKind);
#endif

                    try
                    {
                        //we want to have the body only (throws COMException when inspecting an expression bodied function)
                        startPoint = element.GetStartPoint(vsCMPart.vsCMPartBody);
                        endPoint   = element.GetEndPoint(vsCMPart.vsCMPartBody);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.Print("ParseForStrings(vsCMElementFunction, line {0}): {1} - {2}", startPoint.Line, ex.GetType().Name, ex.Message);
                    }
                } //if

                editPoint = startPoint.CreateEditPoint() as EditPoint2;

                //if ((element.Kind == vsCMElement.vsCMElementVariable) && (startPoint.LineCharOffset > 1))
                //  editPoint.CharLeft(startPoint.LineCharOffset - 1);

//#if DEBUG
//        if (element.Kind == vsCMElement.vsCMElementFunction)
//          System.Diagnostics.Debug.Print("got a function, named: {0} in line {1} to {2}", element.Name, element.StartPoint.Line, element.EndPoint.Line);
//        else
//          System.Diagnostics.Debug.Print("got a variable, named: {0} in line {1} to {2}", element.Name, element.StartPoint.Line, element.EndPoint.Line);
//#endif
                //if (element.Children.Count > 0)
                //  editPoint = element.Children.Item(element.Children.Count).EndPoint.CreateEditPoint() as EditPoint2;
                //else
                //  editPoint = element.StartPoint.CreateEditPoint() as EditPoint2;
//#if DEBUG
//        if (element.Children.Count > 0) System.Diagnostics.Debug.Print("      line {0} to {1}", editPoint.Line, element.EndPoint.Line);
//#endif

                #region veeeeeery sloooooow
                //int endPoint      = element.EndPoint.Line,
                //    endColumn     = element.EndPoint.LineCharOffset,
                //    absoluteEnd   = element.EndPoint.AbsoluteCharOffset,
                //    editLine      = editPoint.Line,
                //    editColumn    = editPoint.LineCharOffset,
                //    absoluteStart = editPoint.AbsoluteCharOffset,
                //    editLength    = (editLine == endPoint) ? (absoluteEnd - absoluteStart + 1)
                //                                           : (editPoint.LineLength - editColumn + 1);

                //while ((editLine < endPoint) || ((editLine == endPoint) && (editColumn <= endColumn)))
                //{
                //  string textLine = editPoint.GetText(editLength);

                //  //System.Diagnostics.Debug.Print(">>>{0}<<<", textLine);

                //  if (!string.IsNullOrEmpty(textLine.Trim()))
                //    ParseForStrings(textLine, editLine, editColumn, stringResources, settings);

                //  editPoint.LineDown(1);
                //  editPoint.StartOfLine();

                //  editLine      = editPoint.Line;
                //  editColumn    = editPoint.LineCharOffset;
                //  absoluteStart = editPoint.AbsoluteCharOffset;
                //  editLength    = (editLine == endPoint) ? (absoluteEnd - absoluteStart + 1)
                //                                         : (editPoint.LineLength - editColumn + 1);
                //} //while
                #endregion

                //this is much faster (by factors)!!!
                int editLine       = editPoint.Line,
                    editColumn     = editPoint.LineCharOffset;
                string   text      = editPoint.GetText(endPoint);
                string[] txtLines  = text.Replace("\r", string.Empty).Split('\n');
                bool     isComment = false;
#if IGNORE_METHOD_ARGUMENTS
                bool isIgnoreMethodArguments = false;
#endif

                foreach (string txtLine in txtLines)
                {
                    if ((editLine >= startLine) && (editLine <= endLine))
                    {
                        //this is a changed text line in the block

#if !IGNORE_METHOD_ARGUMENTS
                        if (txtLine.Contains("\""))
                        {
                            ParseForStrings(txtLine, editLine, editColumn, stringResources, settings, isCSharp, ref isComment);
                        }
#else
                        if (line.Contains("\""))
                        {
                            ParseForStrings(line, editLine, editColumn, stringResources, settings, ref isComment, ref isIgnoreMethodArguments);
                        }
#endif
                    } //if

                    ++editLine;

                    //only for the first line of the text block LineCharOffset will be used
                    if (editColumn > 1)
                    {
                        editColumn = 1;
                    }
                } //foreach
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Print("### Error: ParseForStrings(): {0} - {1}", ex.GetType().Name, ex.Message);
            }

            return(endPoint?.Line ?? (-1));
        }
        /// <summary>
        /// Adds context to the result item, coming from code block starting at given position
        /// </summary>
        protected void AddContextToItem(AbstractResultItem item, EditPoint2 editPoint)
        {
            StringBuilder context = new StringBuilder();
            // indices +1 !!

            int topLines = 0;

            int currentLine         = item.ReplaceSpan.iStartLine;
            int contextRelativeLine = 0;

            // add NumericConstants.ContextLineRadius lines above the result item with at least 2 non-whitespace characters
            while (currentLine >= 1 && topLines < NumericConstants.ContextLineRadius)
            {
                editPoint.MoveToLineAndOffset(currentLine, 1);
                string lineText = editPoint.GetText(editPoint.LineLength);
                if (lineText.Trim().Length > 0)
                {
                    context.Insert(0, lineText + Environment.NewLine);
                    contextRelativeLine++;
                    if (lineText.Trim().Length > 1)
                    {
                        topLines++;
                    }
                }
                currentLine--;
            }

            editPoint.MoveToLineAndOffset(item.ReplaceSpan.iStartLine + 1, 1);
            context.Append(editPoint.GetText(item.ReplaceSpan.iStartIndex));

            context.Append(StringConstants.ContextSubstituteText); // add text that will be displayed instead of actual result item

            editPoint.MoveToLineAndOffset(item.ReplaceSpan.iEndLine + 1, item.ReplaceSpan.iEndIndex + 1);
            context.Append(editPoint.GetText(editPoint.LineLength - item.ReplaceSpan.iEndIndex + 1));

            int botLines = 0;

            currentLine = item.ReplaceSpan.iEndLine + 2;
            // add NumericConstants.ContextLineRadius lines below the result item with at least 2 non-whitespace characters
            while (botLines < NumericConstants.ContextLineRadius)
            {
                editPoint.MoveToLineAndOffset(currentLine, 1);
                string lineText = editPoint.GetText(editPoint.LineLength);
                if (lineText.Trim().Length > 0)
                {
                    context.Append(Environment.NewLine + lineText);
                    if (lineText.Trim().Length > 1)
                    {
                        botLines++;
                    }
                }
                editPoint.EndOfLine();
                if (editPoint.AtEndOfDocument)
                {
                    break;
                }
                currentLine++;
            }

            item.Context             = context.ToString();
            item.ContextRelativeLine = contextRelativeLine; // index of "middle" line
        }
        /// <summary>Parses for strings by iterating through the text lines.</summary>
        /// <param name="element">The element.</param>
        /// <param name="stringResources">The string resources.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="isCSharp">If set to <c>true</c> it is CSharp code.</param>
        /// <param name="startLine">The start line.</param>
        /// <param name="endLine">The end line.</param>
        /// <returns>The last parsed line number or -1.</returns>
        private static int ParseForStrings(CodeElement element,
                                           List <StringResource> stringResources,
                                           Settings settings,
                                           bool isCSharp,
                                           int startLine,
                                           int endLine)
        {
            TextPoint startPoint = element.StartPoint,
                      endPoint   = element.EndPoint;
            EditPoint2 editPoint = null;

            try
            {
                if (element.Kind == vsCMElement.vsCMElementFunction)
                {
#if DEBUG_OUTPUT
                    System.Diagnostics.Debug.Print("    function kind: {0}", (element as CodeFunction).FunctionKind);
#endif

                    try
                    {
                        //we want to have the body only (throws COMException when inspecting an expression bodied function)
                        startPoint = element.GetStartPoint(vsCMPart.vsCMPartBody);
                        endPoint   = element.GetEndPoint(vsCMPart.vsCMPartBody);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.Print("ParseForStrings(vsCMElementFunction, line {0}): {1} - {2}", startPoint.Line, ex.GetType().Name, ex.Message);
                    }
                }

                editPoint = startPoint.CreateEditPoint() as EditPoint2;

                int editLine       = editPoint.Line,
                    editColumn     = editPoint.LineCharOffset;
                string   text      = editPoint.GetText(endPoint);
                string[] txtLines  = text.Replace("\r", string.Empty).Split('\n');
                bool     isComment = false;
#if IGNORE_METHOD_ARGUMENTS
                bool isIgnoreMethodArguments = false;
#endif

                foreach (string txtLine in txtLines)
                {
                    if ((editLine >= startLine) && (editLine <= endLine))
                    {
                        //this is a changed text line in the block

#if !IGNORE_METHOD_ARGUMENTS
                        if (txtLine.Contains("\""))
                        {
                            ParseForStrings(txtLine, editLine, editColumn, stringResources, settings, isCSharp, ref isComment);
                        }
#else
                        if (line.Contains("\""))
                        {
                            ParseForStrings(line, editLine, editColumn, stringResources, settings, ref isComment, ref isIgnoreMethodArguments);
                        }
#endif
                    }

                    ++editLine;

                    //only for the first line of the text block LineCharOffset will be used
                    if (editColumn > 1)
                    {
                        editColumn = 1;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Print("### Error: ParseForStrings(): {0} - {1}", ex.GetType().Name, ex.Message);
            }

            return(endPoint?.Line ?? (-1));
        }