예제 #1
0
        public void Execute()
        {
            foreach (IndentSquareBracket Bracket in Children)
            {
                //向下一行,[ 不需要缩进,后续子Bracket的缩进是建立在 [ 的缩进深度的基础上
                Bracket.Start.LineDown();

                EditPoint CurrentEditLintPoint = Bracket.Start.CreateEditPoint();
                if (CurrentEditLintPoint == null)
                {
                    continue;
                }

                //循环本区间的每行,删除空白,后面根据层级深度,添加缩进
                do
                {
                    //检查是否在在括号内,子括号内的内容,交给子括号处理
                    if (Bracket.EditLineIsInChildren(CurrentEditLintPoint))
                    {
                        CurrentEditLintPoint.LineDown();
                        continue;
                    }

                    //处理缩进,对比应该的缩进深度,大于缩进深度,则剔除,小于则添加
                    HandleIndent(Bracket, CurrentEditLintPoint);

                    CurrentEditLintPoint.LineDown();
                } while (CurrentEditLintPoint.Line <= Bracket.End.Line);//同时处理最后一个 ] 跟 [ 的深度保持一致

                //遍历执行所有的子Bracket
                Bracket.Execute();
            }
        }
예제 #2
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 Execute(object sender, EventArgs e)
        {
            // Verify the current thread is the UI thread.
            ThreadHelper.ThrowIfNotOnUIThread();

            // This command will only work when there's an active document to examine.
            if (FormatCommentCommand.environment.ActiveDocument == null)
            {
                return;
            }

            // Get the selected text from the environment.
            TextSelection selection = FormatCommentCommand.environment.ActiveDocument.Selection as TextSelection;

            // Get the start end points (round down and up to the start of a line).
            EditPoint startPoint = selection.AnchorPoint.CreateEditPoint();

            startPoint.StartOfLine();

            // The initial endpoint is one line below the start.
            EditPoint endPoint = selection.ActivePoint.CreateEditPoint();

            endPoint.StartOfLine();
            endPoint.LineDown(1);

            // If nothing is selected, then figure out what needs to be formatted by the start point up and the end point down.  As long as we
            // recognize a comment line we'll keep expanding the selection in both directions.
            if (selection.IsEmpty)
            {
                // Find the start of the block.
                while (!startPoint.AtStartOfDocument)
                {
                    if (!FormatCommentCommand.IsCommentLine(startPoint))
                    {
                        startPoint.LineDown(1);
                        break;
                    }

                    startPoint.LineUp(1);
                }

                // Find the end of the block.
                while (!endPoint.AtEndOfDocument)
                {
                    if (!FormatCommentCommand.IsCommentLine(endPoint))
                    {
                        break;
                    }

                    endPoint.LineDown(1);
                }
            }

            // This will swap the old comment for the new right-margin justified and beautified comment.
            startPoint.ReplaceText(
                endPoint,
                FormatCommentCommand.FormatCommentstring(startPoint.GetText(endPoint)),
                (int)(vsEPReplaceTextOptions.vsEPReplaceTextNormalizeNewlines | vsEPReplaceTextOptions.vsEPReplaceTextTabsSpaces));
        }
예제 #3
0
        /// <summary>
        /// Reformat all comments between the specified start and end point. Comments that start
        /// within the range, even if they overlap the end are included.
        /// </summary>
        /// <param name="textDocument">The text document.</param>
        /// <param name="start">The start point.</param>
        /// <param name="end">The end point.</param>
        public bool FormatComments(TextDocument textDocument, EditPoint start, EditPoint end)
        {
            bool foundComments = false;
            int  tabSize       = CodeCommentHelper.GetTabSize(_package, textDocument);

            while (start.Line <= end.Line)
            {
                if (CodeCommentHelper.IsCommentLine(start))
                {
                    var comment = new CodeComment(start, tabSize);
                    if (comment.IsValid)
                    {
                        comment.Format();
                        foundComments = true;
                    }

                    if (comment.EndPoint != null)
                    {
                        start = comment.EndPoint.CreateEditPoint();
                    }
                }

                if (start.Line == textDocument.EndPoint.Line)
                {
                    break;
                }

                start.LineDown();
                start.StartOfLine();
            }

            return(foundComments);
        }
        private static int GetCodeBehindLineFromLinePragmas(TextDocument codeBehindDoc, int sourceLine)
        {
            EditPoint start     = codeBehindDoc.StartPoint.CreateEditPoint();
            int       lineCount = codeBehindDoc.EndPoint.Line;

            while (start.Line <= lineCount - 1)
            {
                start.LineDown();
                string lineText = start.GetText(start.LineLength);
                //#line 8
                //#ExternalSource("SpecFlowFeature2.feature",8)
                var match = linePragmaRe.Match(lineText);
                if (match.Success)
                {
                    int linePragmaValue;
                    if (int.TryParse(match.Groups["lineno"].Value, out linePragmaValue))
                    {
                        if (linePragmaValue >= sourceLine)
                        {
                            return(start.Line + 1);
                        }
                    }
                }
            }

            return(0);
        }
예제 #5
0
        /// <summary>
        /// Reformat all comments between the specified start and end point. Comments that start
        /// within the range, even if they overlap the end are included.
        /// </summary>
        /// <param name="textDocument">The text document.</param>
        /// <param name="start">The start point.</param>
        /// <param name="end">The end point.</param>
        public bool FormatComments(TextDocument textDocument, EditPoint start, EditPoint end)
        {
            bool foundComments = false;
            int tabSize = CodeCommentHelper.GetTabSize(_package, textDocument);

            while (start.Line <= end.Line)
            {
                if (CodeCommentHelper.IsCommentLine(start))
                {
                    var comment = new CodeComment(start, tabSize);
                    if (comment.IsValid)
                    {
                        comment.Format();
                        foundComments = true;
                    }

                    if (comment.EndPoint != null)
                    {
                        start = comment.EndPoint.CreateEditPoint();
                    }
                }

                if (start.Line == textDocument.EndPoint.Line)
                {
                    break;
                }

                start.LineDown();
                start.StartOfLine();
            }

            return foundComments;
        }
예제 #6
0
        /// <summary>
        /// Performs the style task.
        /// </summary>
        /// <param name="projectItem">The project Item</param>
        /// <param name="ideWindow">The IDE window.</param>
        protected override void DoWork(ProjectItem projectItem, EnvDTE.Window ideWindow)
        {
            if (projectItem.Name.EndsWith(".cs"))
            {
                Debug.WriteLine("Removing Unnecessary Blank Lines: " + projectItem.Name);
                try
                {
                    TextDocument objTextDoc   = (TextDocument)ideWindow.Document.Object("TextDocument");
                    EditPoint    objEditPoint = objTextDoc.CreateEditPoint(objTextDoc.StartPoint);
                    while (!objEditPoint.AtEndOfDocument)
                    {
                        int secondFarthestLine = objEditPoint.Line + 2;
                        if (secondFarthestLine > objTextDoc.EndPoint.Line)
                        {
                            secondFarthestLine = objEditPoint.Line + 1;
                        }

                        if (objEditPoint.GetLines(objEditPoint.Line, secondFarthestLine).Trim() == string.Empty)
                        {
                            objEditPoint.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical);
                            objEditPoint.Insert("\r\n");
                        }

                        objEditPoint.LineDown(1);
                    }
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc.ToString());
                    Debug.WriteLine("Removing Unnecessary Blank Lines failed, skipping");
                }
            }
        }
        private static async Task AddCommentsAsync(EditPoint objEditPt)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            objEditPt.StartOfLine();
            var template = GetTemplate();
            int index    = 0;

            while (index < template.Count)
            {
                var line = string.Empty;
                if (!objEditPt.AtEndOfDocument)
                {
                    line = objEditPt.GetText(objEditPt.LineLength);
                }
                if (!string.Equals(line, template[index]))
                {
                    objEditPt.Insert($"{template[index]}{Environment.NewLine}");
                    //objEditPt.LineDown();
                    objEditPt.StartOfLine();
                }
                else
                {
                    objEditPt.LineDown();
                }

                index++;
            }
        }
예제 #8
0
        /// <summary>
        /// Reformat all comments between the specified start and end point. Comments that start
        /// within the range, even if they overlap the end are included.
        /// </summary>
        /// <param name="textDocument">The text document.</param>
        /// <param name="start">The start point.</param>
        /// <param name="end">The end point.</param>
        public bool FormatComments(TextDocument textDocument, EditPoint start, EditPoint end)
        {
            var options = new CodeCommentOptions(Settings.Default, _package, textDocument);

            bool foundComments = false;

            while (start.Line <= end.Line)
            {
                if (CodeCommentHelper.IsCommentLine(start))
                {
                    var comment = new CodeComment(start);
                    if (comment.IsValid)
                    {
                        comment.Format(options);
                        foundComments = true;
                    }

                    if (comment.EndPoint != null)
                    {
                        start = comment.EndPoint.CreateEditPoint();
                    }
                }

                if (start.Line == textDocument.EndPoint.Line)
                {
                    break;
                }

                start.LineDown();
                start.StartOfLine();
            }

            return(foundComments);
        }
        public sealed override void Undo()
        {
            EditPoint ep = _codeMethod.StartPoint.CreateEditPoint();

            ep.LineDown(1);
            ep.Delete(_codeMethod.EndPoint);
            ep.Insert("{\r\n}");
        }
        public static void DeleteCurrentLine(this EditPoint start)
        {
            start.StartOfLine();
            var point = start.CreateEditPoint();

            start.LineDown();
            start.StartOfLine();
            point.Delete(start);
        }
예제 #11
0
        public void LineDown(int line, int lineCount)
        {
            EditPoint editPoint = GetEditPoint(line, 0);

            if (editPoint != null)
            {
                editPoint.LineDown(lineCount);
            }
        }
예제 #12
0
        /// <summary>
        /// Sorts all using statements in ascending order, with System using statements on top.
        /// </summary>
        /// <param name="usingStatementsItems">List of using Statement codeItems</param>
        /// <param name="namespaceItems">List of namespace codeItems</param>
        internal void MoveUsingStatementsWithinNamespace(List <CodeItemUsingStatement> usingStatementsItems, List <CodeItemNamespace> namespaceItems)
        {
            if (namespaceItems.Count != 1)
            {
                //We return back as is, if multiple namespaces are found.
                return;
            }

            CodeItemNamespace theOnlyNamespace = namespaceItems.First();

            EditPoint namespaceInsertCursor = theOnlyNamespace.StartPoint;

            // Setting the start point where we will start inserting using statements.
            namespaceInsertCursor.LineDown();
            namespaceInsertCursor.CharRight();
            namespaceInsertCursor.Insert(Environment.NewLine);

            //Sort the using code items in ascending string order, with system usings on top.
            usingStatementsItems.Sort((usingStatement1Item, usingStatement2Item) =>
            {
                string textOfUsingStatement1 = usingStatement1Item.StartPoint.GetText(usingStatement1Item.EndPoint);
                string textOfUsingStatement2 = usingStatement2Item.StartPoint.GetText(usingStatement2Item.EndPoint);

                var referenceNameOfStatement1 = ExtractUsingStatementReferenceName(textOfUsingStatement1);
                var referenceNameOfStatement2 = ExtractUsingStatementReferenceName(textOfUsingStatement2);

                if (IsSystemReference(referenceNameOfStatement1) && !IsSystemReference(referenceNameOfStatement2))
                {
                    return(-1);
                }
                else if (!IsSystemReference(referenceNameOfStatement1) && IsSystemReference(referenceNameOfStatement2))
                {
                    return(1);
                }
                else
                {
                    return(string.Compare(referenceNameOfStatement1, referenceNameOfStatement2));
                }
            });

            foreach (var usingStatement in usingStatementsItems)
            {
                var startPoint = usingStatement.StartPoint;
                var endPoint   = usingStatement.EndPoint;

                string text = startPoint.GetText(usingStatement.EndPoint);
                startPoint.Delete(usingStatement.EndPoint);

                namespaceInsertCursor.Insert(text);
                namespaceInsertCursor.Indent(Count: 1);
                namespaceInsertCursor.Insert(Environment.NewLine);
            }
        }
예제 #13
0
        internal static void InsertBlankLineAfterPoint(EditPoint point)
        {
            if (point.AtEndOfDocument) return;

            point.LineDown(1);
            point.StartOfLine();

            string text = point.GetLines(point.Line, point.Line + 1);
            if (Regex.IsMatch(text, @"^\s*[^\s\}]"))
            {
                point.Insert(Environment.NewLine);
            }
        }
예제 #14
0
        /// <summary>
        /// Generates code in
        /// </summary>
        /// <param name="genAttr"></param>
        /// <param name="parentWriter"></param>
        /// <remarks></remarks>
        private void GenInMember(NotifyPropertyChanged_GenAttribute genAttr, Writer parentWriter)
        {
            var prop = genAttr.ParentProperty;
            //!Parent can be either CodeFunction(only for ExtraNotifications) or CodeProperty
            string code = null;

            switch (genAttr.GenerationType)
            {
            case NotifyPropertyChanged_GenAttribute.GenerationTypes.NotifyOnly:
                //Only notification
                code = string.Format("this.NotifyChanged({0})", prop.Name);
                break;

            default:
                code = (genAttr.ParentProperty != null) ? string.Format("this.SetPropertyAndNotify(ref _{0}, value, \"{0}\");", prop.Name) : "";
                break;
            }

            //Extra notifications
            var extraNotifyCode = GenInMember_ExtraNotifications(genAttr, parentWriter);

            code = code.Conjoin(Environment.NewLine, extraNotifyCode);

            //Code Element, could be property setter or a method
            var codeElement  = (CodeFunction2)((prop != null) ? prop.Setter : genAttr.ParentFunction);
            var memberWriter = new Writer(parentWriter)
            {
                GenAttribute = genAttr, SearchStart = codeElement.StartPoint, SearchEnd = codeElement.EndPoint, Content = code, SegmentType = Types.Statements
            };

            //Find insertion point
            EditPoint insertPoint = null;
            var       insertTag   = Manager.FindInsertionPoint(memberWriter);

            if (insertTag == null)
            {
                //!No insertion point tag specified, by default insert as last line of setter
                insertPoint = codeElement.GetPositionBeforeClosingBrace();
                //always insert new line in case the everything in one line
            }
            else
            {
                //!InsertPoint Tag found, insert right after it
                insertPoint = insertTag.EndPoint.CreateEditPoint();
                insertPoint.LineDown(1);
                insertPoint.StartOfLine();
            }

            memberWriter.InsertStart = insertPoint;
            Manager.InsertOrReplace(memberWriter);
        }
예제 #15
0
        private static IEnumerable <(string line, int index)> GetLines(this TextDocument document)
        {
            EditPoint currentLine = document.CreateEditPoint();
            int       processedLineIndex;

            do
            {
                string lineText = currentLine.GetText(currentLine.LineLength);
                yield return(lineText, currentLine.Line - 1);

                processedLineIndex = currentLine.Line;
                currentLine.LineDown();
            }while (processedLineIndex != currentLine.Line);
        }
        public static string GetNextLineText(this EditPoint point)
        {
            point.LineDown();
            point.StartOfLine();
            var start = point.CreateEditPoint();

            point.EndOfLine();
            var end = point.CreateEditPoint();

            string text = start.GetText(end);

            point.LineUp();

            return(text);
        }
예제 #17
0
        public override string GetLine(int lineIndex)
        {
            if (dte == null || dte.ActiveDocument == null)
            {
                return("");
            }

            EnvDTE.TextDocument objTextDoc = GetCurrentVSTextDocument();
            EditPoint           ep         = objTextDoc.StartPoint.CreateEditPoint();

            ep.LineDown(lineIndex - 1);
            EditPoint ep2 = ep.CreateEditPoint();

            ep2.EndOfLine();
            return(ep.GetText(ep2));
        }
예제 #18
0
        public bool CreateSynchClass()
        {
            CodeClass synchClass = _cc.AddClass("Synch" + _cc.Name, -1, 0,
                                                0, EnvDTE.vsCMAccess.vsCMAccessPrivate);

            synchClass.AddBase(_cc, -1);

            //member variables
            synchClass.AddVariable("_root", "System.Object", -1, EnvDTE.vsCMAccess.vsCMAccessPrivate, null);
            synchClass.AddVariable("_parent", _cc.FullName, -1, EnvDTE.vsCMAccess.vsCMAccessPrivate, null);

            //constructor - add function can't handle this at the moment
            EditPoint classEndPt = synchClass.EndPoint.CreateEditPoint();

            classEndPt.StartOfLine();
            classEndPt.Insert("\n");

            EditPoint editPt = synchClass.StartPoint.CreateEditPoint();

            editPt.LineDown(3);
            editPt.EndOfLine();
            editPt.Insert("\ninternal " + synchClass.Name + "(" + _cc.Name +
                          " parent){\n_parent = parent;\n_root = parent.SyncRoot;\n}\n");
            editPt.MoveToPoint(synchClass.StartPoint);
            editPt.SmartFormat(synchClass.EndPoint);

            //functions, properties and indexers
            for (CodeType ct = (CodeType)_cc; ct != null;)
            {
                if (!AddMemberElementsFromType(ct, synchClass))
                {
                    return(false);
                }
                if (ct.Bases.Count != 0)
                {
                    ct = (CodeType)(ct.Bases.Item(1));
                    if (ct.Name == "Object")
                    {
                        break;
                    }
                }
            }

            synchClass.StartPoint.CreateEditPoint().SmartFormat(synchClass.EndPoint);

            return(true);
        }
예제 #19
0
        /// <summary>
        /// Checks to see if there should be additional blank lines after the end of a block.
        /// </summary>
        /// <param name="element">The current element to check</param>
        private void CheckBlockEnd(CodeElement element)
        {
            EditPoint endBlock   = element.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes).CreateEditPoint();
            EditPoint startBlock = element.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes).CreateEditPoint();
            string    original   = startBlock.GetText(endBlock);

            EditPoint endOfEnd = endBlock.CreateEditPoint();

            endOfEnd.EndOfLine();
            string endOfBlockLine = endBlock.GetText(endOfEnd).Trim();

            if (element.Kind == vsCMElement.vsCMElementAttribute || element.Kind == vsCMElement.vsCMElementOther)
            {
                if (endOfBlockLine != "]" && endOfBlockLine != ")]" && !endOfBlockLine.StartsWith(","))
                {
                    endOfEnd = endBlock.CreateEditPoint();
                    endOfEnd.EndOfLine();
                    endOfBlockLine = endBlock.GetText(endOfEnd).Trim();
                    if (endOfBlockLine != string.Empty)
                    {
                        endBlock.Insert(Environment.NewLine);
                        endBlock.SmartFormat(endOfEnd);
                    }
                }
            }
            else if (endOfBlockLine != string.Empty)
            {
                endBlock.Insert(Environment.NewLine);
                endBlock.SmartFormat(endOfEnd);
            }

            if (element.Kind != vsCMElement.vsCMElementImportStmt &&
                element.Kind != vsCMElement.vsCMElementAttribute &&
                element.Kind != vsCMElement.vsCMElementOther)
            {
                endOfEnd.LineDown(1);
                endOfEnd.EndOfLine();
                string lineAfterBlock = endBlock.GetText(endOfEnd).Trim();

                if (lineAfterBlock != string.Empty && !lineAfterBlock.StartsWith("else") && !lineAfterBlock.StartsWith("}"))
                {
                    endBlock.Insert(Environment.NewLine);
                    endBlock.SmartFormat(endOfEnd);
                }
            }
        }
예제 #20
0
        /// <summary>
        /// Inserts a blank line after the specified point except where adjacent to a brace.
        /// </summary>
        /// <param name="point">The point.</param>
        internal static void InsertBlankLineAfterPoint(EditPoint point)
        {
            if (point.AtEndOfDocument)
            {
                return;
            }

            point.LineDown(1);
            point.StartOfLine();

            string text = point.GetLine();

            if (RegexNullSafe.IsMatch(text, @"^\s*[^\s\}]"))
            {
                point.Insert(Environment.NewLine);
            }
        }
예제 #21
0
        /// <summary>
        /// Checks the document in the window for preprocessor directives.
        /// </summary>
        /// <param name="ideWindow">The window of the document to check.</param>
        /// <returns>True if there are preprocessor directives present.</returns>
        private bool CheckForPreprocessorDirectives(EnvDTE.Window ideWindow)
        {
            TextDocument doc       = (TextDocument)ideWindow.Document.Object("TextDocument");
            EditPoint    editPoint = doc.CreateEditPoint(doc.StartPoint);

            while (!editPoint.AtEndOfDocument)
            {
                if (editPoint.GetLines(editPoint.Line, editPoint.Line + 1).StartsWith("#"))
                {
                    return(true);
                }

                editPoint.LineDown(1);
            }

            return(false);
        }
예제 #22
0
        public void FindBracket()
        {
            EditPoint  EndPoint   = null;
            TextRanges dummy      = null;
            EditPoint  StartPoint = Start.CreateEditPoint();

            StartPoint.LineDown();
            //FindPattern 不能指定结束位置
            while (StartPoint.FindPattern(MaximumBracketPattern, StandardFindOptions, ref EndPoint, ref dummy))
            {
                //所以,需要 判读匹配的开始位置是否在,被包含的区间外
                if (StartPoint.Line >= End.Line)
                {
                    break;//在外面,则跳出,转入数组的下一个
                }
                if (StartPoint != null && EndPoint != null)
                {
                    IndentSquareBracket Child = new IndentSquareBracket(StartPoint, EndPoint, this);

                    StartPoint.StartOfLine();

                    int LineIndentCount;
                    //当父节区间为空时,取父区间的缩进,否则在父区间的基础上+1,逐级实现缩进
                    if (Parent == null)
                    {
                        string LineText = StartPoint.GetText(StartPoint.LineLength);
                        string textTemp = LineText.TrimStart('\t');
                        LineIndentCount = LineText.Length - textTemp.Length;//获取当前的缩进深度
                    }
                    else
                    {
                        LineIndentCount = IndentCount + 1;
                    }

                    Child.IndentCount = LineIndentCount;
                    Children.Add(Child);

                    //子Bracket递归查找
                    Child.FindBracket();
                }

                //再从区间的结束位置向后在下一个最大的包含区间
                StartPoint = EndPoint;
            }
        }
        private int FindPatternInDocument(TextDocument codeBehindDoc, params string[] patternsToLookFor)
        {
            EditPoint start     = codeBehindDoc.StartPoint.CreateEditPoint();
            int       lineCount = codeBehindDoc.EndPoint.Line;

            while (start.Line <= lineCount - 1)
            {
                start.LineDown();
                string lineText = start.GetText(start.LineLength);

                if (patternsToLookFor.Any(lineText.Contains))
                {
                    return(start.Line + 1);
                }
            }

            return(0);
        }
        /// <summary>
        /// Get and position EditPoint objects to include all of original text that is selected, plus surrounding text for complete lines of text
        /// </summary>
        /// <param name="document"></param>
        /// <param name="earlierPoint"></param>
        /// <param name="laterPoint"></param>
        public void GetEditPointsForLinesToCheck(TextDocument document, out EditPoint earlierPoint, out EditPoint laterPoint)
        {
            TextSelection selection = document.Selection;

            // Reorder selection points as needed
            if (selection.IsActiveEndGreater)
            {
                selection.SwapAnchor();
            }

            // Get and position EditPoint objects to include all of original text that is selected, plus surrounding text for complete lines of text
            earlierPoint = selection.ActivePoint.CreateEditPoint();
            laterPoint   = selection.AnchorPoint.CreateEditPoint();

            earlierPoint.StartOfLine();
            laterPoint.LineDown(1);
            laterPoint.StartOfLine();
        }
        /// <summary>
        /// Reformat all comments between the specified start and end point. Comments that start
        /// within the range, even if they overlap the end are included.
        /// </summary>
        /// <param name="textDocument">The text document.</param>
        /// <param name="start">The start point.</param>
        /// <param name="end">The end point.</param>
        public bool FormatComments(TextDocument textDocument, EditPoint start, EditPoint end)
        {
            bool foundComments = false;

            var options = FormatterOptions
                          .FromSettings(Settings.Default)
                          .Set(o =>
            {
                o.TabSize      = textDocument.TabSize;
                o.IgnoreTokens = CodeCommentHelper
                                 .GetTaskListTokens(_package)
                                 .Concat(Settings.Default.Formatting_IgnoreLinesStartingWith.Cast <string>())
                                 .ToArray();
            });

            while (start.Line <= end.Line)
            {
                if (CodeCommentHelper.IsCommentLine(start))
                {
                    var comment = new CodeComment(start, options);

                    if (comment.IsValid)
                    {
                        comment.Format();
                        foundComments = true;
                    }

                    if (comment.EndPoint != null)
                    {
                        start = comment.EndPoint.CreateEditPoint();
                    }
                }

                if (start.Line == textDocument.EndPoint.Line)
                {
                    break;
                }

                start.LineDown();
                start.StartOfLine();
            }

            return(foundComments);
        }
예제 #26
0
        private Tuple <TextPoint, TextPoint> GetCodeRange()
        {
            // The C# and VB code models don't return comments with vsCMPartWholeWithAttributes
            // (even though some of the member types have Comment and DocComment properties
            // and the code model's RemoveMember will remove the comments).  So we have to
            // grab any attached comment lines manually.
            TextPoint startPoint = this.element.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes);
            TextPoint endPoint   = this.element.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes);
            Regex     commentRegex;

            switch (this.language)
            {
            case Language.CSharp:
                // Look for lines starting with optional whitespace followed by //, /*, */, or *.
                commentRegex = new Regex(@"^\s*(//|/\*|\*/|\*)");
                break;

            case Language.VB:
                // Look for lines starting with optional whitespace followed by '.
                commentRegex = new Regex(@"^\s*'");
                break;

            default:
                throw new NotSupportedException("Unsupported language: " + this.language);
            }

            EditPoint startEdit = startPoint.CreateEditPoint();

            startEdit.LineUp();
            while (!startEdit.AtStartOfDocument &&
                   commentRegex.IsMatch(startEdit.GetLines(startEdit.Line, startEdit.Line + 1)))
            {
                startEdit.LineUp();
                startEdit.StartOfLine();
            }

            startEdit.LineDown();
            startEdit.StartOfLine();

            Tuple <TextPoint, TextPoint> result = Tuple.Create((TextPoint)startEdit, endPoint);

            return(result);
        }
예제 #27
0
        public void CommentSelectedText()
        {
            TextSelection textSelection = ActiveTextSelection;

            if (textSelection != null)
            {
                //editpoint,virsualpoint 都继承于TextPoint
                EditPoint topEditPoint = textSelection.TopPoint.CreateEditPoint();
                TextPoint bottomPoint  = textSelection.BottomPoint;

                UndoContext undoContext = ApplicationObject.UndoContext;
                undoContext.Open("Comment Region");
                while (topEditPoint.LessThan(bottomPoint))
                {
                    topEditPoint.Insert("//");
                    topEditPoint.LineDown();
                    topEditPoint.StartOfLine();
                }
                undoContext.Close();
            }
        }
예제 #28
0
        /// <summary>
        /// Returns an adjusted CodeElement. Walks comments 'down' to the next real element.
        /// From Rick Strahl's Weblog
        /// </summary>
        /// <returns></returns>
        static public CodeElement GetCodeElementFromActivePoint()
        {
            EditPoint selPoint = GetActiveEditPoint();

            if (selPoint == null)
            {
                return(null);
            }

            selPoint.StartOfLine();

            while (true)
            {
                if (selPoint.AtEndOfDocument)
                {
                    break;
                }
                string BlockText = selPoint.GetText(selPoint.LineLength).Trim();
                // *** Skip over any XML Doc comments
                if (BlockText.StartsWith("//"))
                {
                    selPoint.LineDown(1);
                    selPoint.StartOfLine();
                }
                else
                {
                    break;
                }
            }
            // *** Make sure the cursor is placed inside of the definition always
            // *** Especially required for single line methods/fields/events etc.
            selPoint.EndOfLine();
            selPoint.CharLeft(1);  // Force into the text

            return(GetActiveCodeElement());
        }
예제 #29
0
        /// <summary>
        /// Helper method to modify commands.xml.
        /// </summary>
        /// <param name="projectItem"></param>
        private void ModifyCommandTable(ProjectItem projectItem)
        {
            Document activeDoc = projectItem.Document;

            projectItem.Open();
            TextDocument editDoc   = (TextDocument)activeDoc.Object("TextDocument");
            EditPoint    objEditPt = editDoc.CreateEditPoint();
            EditPoint    objMovePt = editDoc.EndPoint.CreateEditPoint();

            objEditPt.StartOfDocument();
            activeDoc.ReadOnly = false;

            objEditPt.FindPattern("</KeyinTable>");
            objEditPt.Insert("\n");
            objEditPt.LineUp(1);
            objEditPt.Indent(objEditPt, 1);
            objEditPt.Insert("<Keyword CommandWord=\"" + FunctionName + "\"></Keyword>");
            objEditPt.LineDown(1);
            objEditPt.Indent(objEditPt, 2);

            objEditPt.FindPattern("</KeyinHandlers>");
            objEditPt.Insert("\n");
            objEditPt.LineUp(1);
            objEditPt.Indent(objEditPt, 1);
            objEditPt.Insert("<KeyinHandler Keyin=\"" + RootNamespace + " " + FunctionName + "\"\n");
            objEditPt.Indent(objEditPt, 4);

            if (!IsVBProject)
            {
                objEditPt.Insert("Function=\"" + RootNamespace + ".KeyinCommands." + FunctionName + "Keyin\"/>");
            }
            else
            {
                objEditPt.Insert("Function=\"" + RootNamespace + ".KeyinCommands." + FunctionName + "Keyin\"/>");
            }
        }
예제 #30
0
        /// <summary>
        /// Reformat all comments between the specified start and end point. Comments that start
        /// within the range, even if they overlap the end are included.
        /// </summary>
        /// <param name="textDocument">The text document.</param>
        /// <param name="start">The start point.</param>
        /// <param name="end">The end point.</param>
        public bool FormatComments(TextDocument textDocument, EditPoint start, EditPoint end)
        {
            var options = new CodeCommentOptions(Settings.Default, _package, textDocument);

            bool foundComments = false;

            while (start.Line <= end.Line)
            {
                if (CodeCommentHelper.IsCommentLine(start))
                {
                    var comment = new CodeComment(start);
                    if (comment.IsValid)
                    {
                        comment.Format(options);
                        foundComments = true;
                    }

                    if (comment.EndPoint != null)
                    {
                        start = comment.EndPoint.CreateEditPoint();
                    }
                }

                if (start.Line == textDocument.EndPoint.Line)
                {
                    break;
                }

                start.LineDown();
                start.StartOfLine();
            }

            return foundComments;
        }
예제 #31
0
        public static bool DeleteCodeSite(this CodeFunction value, bool bDelete = true)
        {
            if (bDelete && !value.ExistsCodeSite())
            {
                return(true);
            }
            EditPoint epStart = value.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();
            EditPoint epEnd = value.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint();
            EditPoint epFind = null, epFindStart = null;

            bool Find(string text, bool start)
            {
                string[] textSplit;
                if (start)
                {
                    epFind    = epStart.CreateEditPoint();
                    textSplit = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                }
                else
                {
                    epFind    = epEnd.CreateEditPoint();
                    textSplit = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Reverse().ToArray();
                }
                int iLine = 0;

                foreach (var item in textSplit)
                {
                    int    i = item.IndexOfAny(new char[] { '(', ' ' });
                    string s = i == -1 ? item : item.Substring(0, i + 1);

                    if ((start ? epFind.FindPattern(s) : epFind.FindPattern(s, (int)vsFindOptions.vsFindOptionsBackwards)) &&
                        (start ? epFind.LessThan(epEnd) : epFind.GreaterThan(epStart)) &&
                        (iLine == 0 || iLine == epFind.Line - (start ? 1 : -1)))
                    {
                        if (iLine == 0)
                        {
                            epFindStart = epFind.CreateEditPoint();
                        }
                        iLine = epFind.Line;
                        if (start)
                        {
                            epFind.EndOfLine();
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
                return(true);
            }

            void Delete()
            {
                if (epFind.GreaterThan(epFindStart))
                {
                    epFind.LineDown(1);
                }
                else
                {
                    epFindStart.LineDown(1);
                }
                epFind.StartOfLine();
                epFindStart.StartOfLine();
                epFindStart.Delete(epFind);
            }

            if (!Find(value.CSEnterText(), true))
            {
                return(false);
            }
            else if (bDelete)
            {
                Delete();
            }

            if (!Find(value.CSExitText(), false))
            {
                return(false);
            }
            else if (bDelete)
            {
                Delete();
            }
            else
            {
                return(true);
            }

            if (Find(value.CSCatchText(), false) && bDelete)
            {
                Delete();
            }

            //格式化指定范围内的文本
            value.StartPoint.CreateEditPoint().SmartFormat(value.EndPoint);
            return(true);
        }
예제 #32
0
        protected bool AddMemberElementsFromType(CodeType ct, CodeClass synchClass)
        {
            string indexerParamList = "";

            foreach (CodeElement member in ct.Members)
            {
                CodeFunction cf = member as CodeFunction;
                if (!AddSynchWrapperMember(synchClass, cf))
                {
                    return(false);
                }

                CodeProperty cp = member as CodeProperty;
                if (cp != null)
                {
                    string getter = "";
                    string setter = "";
                    //Getter and Setter throw if property lacks these methods
                    try{
                        if (cp.Getter != null)
                        {
                            getter = cp.Name;
                        }
                    }catch (Exception) {}
                    try{
                        if (cp.Setter != null)
                        {
                            setter = cp.Name;
                        }
                    }catch (Exception) {}

                    CodeFunction spSetter = null;
                    if (cp.Name != "SyncRoot")
                    {
                        CodeProperty sp        = synchClass.AddProperty(getter, setter, cp.Type, -1, cp.Access, null);
                        TextRanges   tr        = null;
                        bool         hasGetter = false;
                        sp.StartPoint.CreateEditPoint().ReplacePattern(sp.EndPoint, sp.Type.AsString, "override " + sp.Type.AsString,
                                                                       (int)EnvDTE.vsFindOptions.vsFindOptionsMatchWholeWord, ref tr);
                        if (getter != "")
                        {
                            hasGetter = true;
                            if (cp.Name != "IsSynchronized")
                            {
                                AddOneLineImpl(sp.Type.AsString + " ret;\nSystem.Threading.Monitor.Enter(_root);" +
                                               "\ntry{\nret = _parent." + getter + ";\n}\nfinally{System.Threading.Monitor.Exit(_root);}" +
                                               "\nreturn ret;", sp.Getter, true);
                            }
                            else
                            {
                                AddOneLineImpl("return true;", sp.Getter, true);
                            }
                        }
                        if (setter != "")
                        {
                            //bug work-around
                            foreach (CodeElement codeElm in synchClass.Members)
                            {
                                if (codeElm.Name == sp.Name)
                                {
                                    spSetter = ((CodeProperty)codeElm).Setter;
                                }
                            }

                            AddOneLineImpl("\nSystem.Threading.Monitor.Enter(_root);" +
                                           "\ntry{\n _parent." + setter + " = value;\n}\nfinally{System.Threading.Monitor.Exit(_root);}",
                                           spSetter, false);
                        }

                        if (cp.Name == "this")                         //fix up indexer override
                        //add parameters
                        {
                            CodeFunction getterOrSetter;
                            if (hasGetter)
                            {
                                getterOrSetter = cp.Getter;
                            }
                            else
                            {
                                getterOrSetter = cp.Setter;
                            }

                            System.Text.StringBuilder paramList        = new System.Text.StringBuilder();
                            System.Text.StringBuilder paramListNoTypes = new System.Text.StringBuilder();
                            bool first = true;
                            foreach (CodeParameter p in cp.Getter.Parameters)
                            {
                                if (!first)
                                {
                                    paramListNoTypes.Append(", ");
                                    paramList.Append(", ");
                                }
                                first = false;
                                paramList.Append(p.Type.AsString);
                                paramList.Append(" ");
                                paramList.Append(p.Name);
                                paramListNoTypes.Append(p.Name);
                            }

                            EditPoint firstLine  = sp.StartPoint.CreateEditPoint();
                            EditPoint secondLine = sp.StartPoint.CreateEditPoint();
                            TextPoint endPt      = sp.EndPoint;
                            secondLine.LineDown(1); secondLine.StartOfLine();
                            TextRanges tr1 = null;
                            firstLine.ReplacePattern(secondLine, "this", "this[" + paramList.ToString() + "]",
                                                     (int)EnvDTE.vsFindOptions.vsFindOptionsMatchWholeWord, ref tr1);

                            //calls - replace .this with [param1, param2]
                            paramListNoTypes.Insert(0, '[');
                            paramListNoTypes.Append("]");
                            indexerParamList = paramListNoTypes.ToString();
                        }
                    }
                }
                if (indexerParamList != "")
                {
                    TextRanges tr = null;
                    synchClass.StartPoint.CreateEditPoint().ReplacePattern(
                        synchClass.EndPoint, ".this", indexerParamList,
                        (int)EnvDTE.vsFindOptions.vsFindOptionsMatchCase, ref tr);
                }
            }
            return(true);
        }
예제 #33
0
        /// <summary>
        /// Help method to modify KeyinCommands.cs or KeyinCommands.vb.
        /// </summary>
        /// <param name="projectItem"></param>
        /// <param name="keyinCommandFunctionCS"></param>
        /// <param name="keyinCommandFunctionvb"></param>
        private void ModifyKeyinsCommands(ProjectItem projectItem,
                                          string keyinCommandFunctionCS,
                                          string keyinCommandFunctionvb,
                                          string keyinCommandFunctionCPP)
        {
            Document activeDoc = projectItem.Document;

            if (activeDoc == null)
            {
                return;
            }
            ProjectItem activeDocumentProjectItem = activeDoc.ProjectItem;

            if (activeDocumentProjectItem == null)
            {
                return;
            }
            FileCodeModel fileCodeModel = activeDocumentProjectItem.FileCodeModel;

            if (fileCodeModel == null)
            {
                return;
            }

            CodeElements codeElements = fileCodeModel.CodeElements;
            CodeClass    codeClass    = null;

            // look for the namespace in the active document
            CodeNamespace codeNamespace = null;

            foreach (CodeElement codeElement in codeElements)
            {
                if (codeElement.Kind == vsCMElement.vsCMElementNamespace)
                {
                    codeNamespace = codeElement as CodeNamespace;
                    break;
                }
            }
            if (codeNamespace == null)
            {
                if (IsVBProject)
                {
                    codeElements = fileCodeModel.CodeElements;
                }
                else
                {
                    return;
                }
            }
            else
            {
                codeElements = codeNamespace.Members;
            }

            if (codeElements == null)
            {
                return;
            }

            // look for the first class
            foreach (CodeElement codeElement in codeElements)
            {
                if (codeElement.Kind == vsCMElement.vsCMElementClass)
                {
                    codeClass = codeElement as CodeClass;
                    break;
                }
            }
            if (codeClass == null)
            {
                return;
            }

            if (IsCSProject)
            {
                CodeFunction codeFunction = codeClass.AddFunction(FunctionName + "Keyin", vsCMFunction.vsCMFunctionFunction, vsCMTypeRef.vsCMTypeRefVoid, -1, vsCMAccess.vsCMAccessPublic);
                codeFunction.AddParameter("unparsed", vsCMTypeRef.vsCMTypeRefString, -1);
                TextPoint textPoint     = codeFunction.GetStartPoint(vsCMPart.vsCMPartBody);
                EditPoint editPoint     = textPoint.CreateEditPoint();
                EditPoint objMovePt     = textPoint.CreateEditPoint();
                EditPoint UtilEditPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartHeader).CreateEditPoint();
                UtilEditPoint.ReplaceText(6, "public static", 0);
                editPoint.Insert
                (
                    keyinCommandFunctionCS
                );
                editPoint.StartOfDocument();
                objMovePt.EndOfDocument();
                editPoint.SmartFormat(objMovePt);
            }
            else if (IsVBProject)
            {
                CodeFunction codeFunction = codeClass.AddFunction(FunctionName + "Keyin", vsCMFunction.vsCMFunctionSub, vsCMTypeRef.vsCMTypeRefVoid, -1, vsCMAccess.vsCMAccessPublic);
                codeFunction.AddParameter("unparsed", vsCMTypeRef.vsCMTypeRefString, -1);
                TextPoint textPoint     = codeFunction.GetStartPoint(vsCMPart.vsCMPartBody);
                EditPoint editPoint     = textPoint.CreateEditPoint();
                EditPoint objMovePt     = textPoint.CreateEditPoint();
                EditPoint UtilEditPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartHeader).CreateEditPoint();
                UtilEditPoint.ReplaceText(6, "Public Shared", 0);
                editPoint.Insert
                (
                    keyinCommandFunctionvb
                );
                editPoint.StartOfDocument();
                objMovePt.EndOfDocument();
                editPoint.SmartFormat(objMovePt);
            }
            else if (IsVCProject)
            {
                TextDocument editDoc   = (TextDocument)activeDoc.Object("TextDocument");
                EditPoint    objEditPt = editDoc.CreateEditPoint();
                EditPoint    objMovePt = editDoc.EndPoint.CreateEditPoint();
                objEditPt.StartOfDocument();
                activeDoc.ReadOnly = false;

                if (objEditPt.FindPattern("#include"))
                {
                    objEditPt.LineDown(1);
                    objEditPt.Insert("#include \"" + FunctionName + ".h\"\n");
                }
                else if ((objEditPt.FindPattern("#using")))
                {
                    objEditPt.LineUp(1);
                    objEditPt.Insert("#include \"" + FunctionName + ".h\"\n");
                }
                else
                {
                    objEditPt.FindPattern("namespace");
                    objEditPt.LineUp(1);
                    objEditPt.Insert("#include \"" + FunctionName + ".h\"\n");
                }

                CodeFunction codeFunction = codeClass.AddFunction(FunctionName + "Keyin", vsCMFunction.vsCMFunctionFunction, vsCMTypeRef.vsCMTypeRefVoid, -1, vsCMAccess.vsCMAccessPublic);
                codeFunction.AddParameter("unparsed", "System::String^", -1);
                TextPoint textPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartBody);
                EditPoint editPoint = textPoint.CreateEditPoint();
                objMovePt = textPoint.CreateEditPoint();
                EditPoint UtilEditPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartHeader).CreateEditPoint();
                UtilEditPoint.ReplaceText(4, "public:static", 0);

                editPoint.Insert(keyinCommandFunctionCPP);
                if (objEditPt.FindPattern("throw gcnew System::NotImplementedException();"))
                {
                    editPoint.Delete(52);
                }

                editPoint.StartOfDocument();
                objMovePt.EndOfDocument();
                editPoint.SmartFormat(objMovePt);
            }
        }