Exemple #1
0
        private bool Evaluate(out object newValue)
        {
            newValue = null;
            CodeClass currentDSAClass = ExpressionEvaluationHelper.EvaluateExpression((IDictionaryService)GetService(typeof(IDictionaryService)),
                                                                                      currentDSAClassExpression) as CodeClass;

            if (currentDSAClass != null)
            {
                CodeProperty onlineProxyTypeProperty = CodeModelHelper.GetProperty(currentDSAClass, "OnlineProxyType", vsCMAccess.vsCMAccessPublic);
                if (onlineProxyTypeProperty != null)
                {
                    CodeFunction getMethod = onlineProxyTypeProperty.Getter;
                    EditPoint    edit      = getMethod.StartPoint.CreateEditPoint();
                    EditPoint    endpoint  = null;
                    TextRanges   tags      = null;
                    if (edit.FindPattern(@"(typeof|GetType)\((.+)\)", (int)vsFindOptions.vsFindOptionsRegularExpression, ref endpoint, ref tags))
                    {
                        EditPoint begin         = edit.CreateEditPoint();
                        string    proxyTypeName = begin.GetText(endpoint);
                        Regex     extractRegex  = new Regex(@"(typeof|GetType)\((.+)\)");
                        if (extractRegex.IsMatch(proxyTypeName) && extractRegex.Match(proxyTypeName).Groups.Count == 3)
                        {
                            proxyTypeName = extractRegex.Match(proxyTypeName).Groups[2].Value;
                            newValue      = proxyTypeName;
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Exemple #2
0
        /// <summary>
        /// Finds a pattern in the specified range of text and replaces it with the specified text.
        /// </summary>
        /// <param name="startPoint">The start point of the specified range of text.</param>
        /// <param name="endPoint">The end point of the specified range of text.</param>
        /// <param name="oldText">The text to replace.</param>
        /// <param name="newText">The replacement text for pattern.</param>
        public bool Replace(TextPoint startPoint, TextPoint endPoint, string oldText, string newText)
        {
            EditPoint  ep = Document.CreateEditPoint(startPoint);
            TextRanges tr = null;

            return(ep.ReplacePattern(endPoint, oldText, newText,
                                     (int)vsFindOptions.vsFindOptionsMatchWholeWord, ref tr));
        }
Exemple #3
0
        private bool Find(EditPoint2 editPoint,
                          string text)
        {
            EditPoint  endPoint = null;
            TextRanges tags     = null;

            return(editPoint.FindPattern(text, (int)vsFindOptions.vsFindOptionsMatchInHiddenText,
                                         ref endPoint, ref tags));
        }
        /// ------------------------------------------------------------------------------------
        /// <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;
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// Finds a pattern in the specified range of text and replaces it with the specified text.
        /// </summary>
        /// <param name="startLine">The start line of the specified range of text.</param>
        /// <param name="startRow">The start row of the specified range of text.</param>
        /// <param name="endLine">The end line of the specified range of text.</param>
        /// <param name="endRow">The end row of the specified range of text.</param>
        /// <param name="oldText">The text to replace.</param>
        /// <param name="newText">The replacement text for pattern.</param>
        public bool Replace(int startLine, int startRow, int endLine, int endRow, string oldText, string newText)
        {
            EditPoint  ep           = Document.CreateEditPoint(new LuaTextPoint(Document, startRow, startLine));
            TextRanges tr           = null;
            TextPoint  endTextPoint = new LuaTextPoint(Document, endRow, endLine);

            //Trace.WriteLine(string.Format("Start: {0} - End: {1}", new LuaTextPoint(Document, startRow, startLine),endTextPoint));
            return(ep.ReplacePattern(endTextPoint, oldText, newText,
                                     (int)vsFindOptions.vsFindOptionsMatchWholeWord, ref tr));
        }
        /// <summary>Finds all instances of a text in the document object for the provided item.</summary>
        /// <param name="item">Project item to search texts</param>
        /// <param name="text">Text to look for</param>
        /// <returns>A collection of BaseHardCodedString objects that references to text</returns>
        public static ReadOnlyCollection <BaseHardCodedString> FindAllInstancesInDocument(ProjectItem item, string text)
        {
            TextDocument doc = GetDocumentForItem(item);
            Collection <BaseHardCodedString> instances = new Collection <BaseHardCodedString>();
            EditPoint start = doc.StartPoint.CreateEditPoint();

            start.MoveToAbsoluteOffset(1);
            EditPoint end = null;
            // Unused object for FindPattern method.
            TextRanges ranges = null;

            System.Collections.IEnumerator comments = null;
            Match currentMatch = null;

            BaseHardCodedString instance = BaseHardCodedString.GetHardCodedString(item.Document);

            while (start.FindPattern(text, (int)(vsFindOptions.vsFindOptionsMatchCase), ref end, ref ranges))
            {
                if (instance != null)
                {
                    if (comments == null)
                    {
                        comments = instance.FindCommentsInDocument(item).GetEnumerator();
                    }
                    bool inComment = false;
                    while (currentMatch != null || (comments.MoveNext()))
                    {
                        currentMatch = (Match)(comments.Current);
                        // If this match appears earlier then current text skip
                        if (currentMatch.Index + currentMatch.Length <= (start.AbsoluteCharOffset - 1))
                        {
                            currentMatch = null;
                        }
                        // If this comment is later then current text stop processing comments
                        else if (currentMatch.Index >= (end.AbsoluteCharOffset - 1))
                        {
                            break;
                        }
                        // At this point current text must be part of a comment block
                        else
                        {
                            inComment = true;
                            break;
                        }
                    }
                    if (!inComment)
                    {
                        instance = instance.CreateInstance(item, start.AbsoluteCharOffset - 1, end.AbsoluteCharOffset - 1);
                        instances.Add(instance);
                    }
                }
                start = end;
            }
            return(new ReadOnlyCollection <BaseHardCodedString>(instances));
        }
        private EditPoint FindFirstMatch(EditPoint startPoint, string pattern)
        {
            EditPoint  endPoint = null;
            TextRanges tags     = null;

            if (startPoint != null && startPoint.FindPattern(pattern, (int)(vsFindOptions.vsFindOptionsRegularExpression | vsFindOptions.vsFindOptionsMatchInHiddenText), ref endPoint, ref tags))
            {
                return(startPoint.CreateEditPoint());
            }
            return(null);
        }
Exemple #8
0
        public void RemoveRegions(Proc replaceString)
        {
            Document      currentDocument     = _applicationObject.ActiveDocument;
            TextDocument  currentTextDocument = currentDocument.Object("") as TextDocument;
            TextSelection txtSel = (TextSelection)_applicationObject.ActiveDocument.Selection;

            if (currentTextDocument != null)
            {
                TextRanges refRanges = null;

                if (currentTextDocument.Language == "CSharp")
                {
                    try
                    {
                        txtSel.SelectAll();
                        txtSel.ReplacePattern(replaceString(), " ",
                                              (int)vsFindOptions.vsFindOptionsFromStart +
                                              (int)vsFindOptions.vsFindOptionsMatchInHiddenText +
                                              (int)vsFindOptions.vsFindOptionsKeepModifiedDocumentsOpen +
                                              (int)vsFindOptions.vsFindOptionsRegularExpression,
                                              ref refRanges);

                        //currentTextDocument.ReplacePattern(replaceString(), string.Empty,
                        //                                   (int) vsFindOptions.vsFindOptionsFromStart +
                        //                                   (int) vsFindOptions.vsFindOptionsMatchInHiddenText +
                        //                                   (int) vsFindOptions.vsFindOptionsKeepModifiedDocumentsOpen +
                        //                                   (int) vsFindOptions.vsFindOptionsRegularExpression,
                        //                                   ref refRanges);
                    }
                    catch (Exception e)
                    {
                        Console.Out.WriteLine("e = {0}", e);
                    }
                }

                #region some other crap

                #region inner region

                #  region

                #endregion

                #endregion

                #endregion

                #region

                #endregion
            }
        }
Exemple #9
0
        /// <summary>
        /// Gets the text between the specified start point and the first match.
        /// </summary>
        /// <param name="startPoint">The start point.</param>
        /// <param name="matchString">The match string.</param>
        /// <returns>The matching text, otherwise null.</returns>
        internal static string GetTextToFirstMatch(TextPoint startPoint, string matchString)
        {
            var        startEditPoint  = startPoint.CreateEditPoint();
            var        endEditPoint    = startEditPoint.CreateEditPoint();
            TextRanges subGroupMatches = null; // Not used - required for FindPattern.

            if (endEditPoint.FindPattern(matchString, StandardFindOptions, ref endEditPoint, ref subGroupMatches))
            {
                return(startEditPoint.GetText(endEditPoint));
            }

            return(null);
        }
Exemple #10
0
        /// <summary>
        /// Finds the first match of the specified pattern within the specified text document, otherwise null.
        /// </summary>
        /// <param name="textDocument">The text document.</param>
        /// <param name="patternString">The pattern string.</param>
        /// <returns>The first match, otherwise null.</returns>
        internal static EditPoint FirstOrDefaultMatch(TextDocument textDocument, string patternString)
        {
            var        cursor = textDocument.StartPoint.CreateEditPoint();
            EditPoint  end    = null;
            TextRanges dummy  = null;

            if (cursor != null && cursor.FindPattern(patternString, StandardFindOptions, ref end, ref dummy))
            {
                return(cursor.CreateEditPoint());
            }

            return(null);
        }
Exemple #11
0
        private List <EditPoint> FindAll(TextDocument doc, string toFind)
        {
            var        matches = new List <EditPoint>();
            var        cursor  = doc.StartPoint.CreateEditPoint();
            EditPoint  end     = null;
            TextRanges dummy   = null;

            while (cursor != null && cursor.FindPattern(toFind, standardFindOptions, ref end, ref dummy))
            {
                matches.Add(cursor.CreateEditPoint());
                cursor = end;
            }

            return(matches);
        }
Exemple #12
0
        /// <summary>
        /// Finds all matches of the specified pattern within the specified text document.
        /// </summary>
        /// <param name="textDocument">The text document.</param>
        /// <param name="patternString">The pattern string.</param>
        /// <returns>The set of matches.</returns>
        internal static IEnumerable <EditPoint> FindMatches(TextDocument textDocument, string patternString)
        {
            var        matches = new List <EditPoint>();
            var        cursor  = textDocument.StartPoint.CreateEditPoint();
            EditPoint  end     = null;
            TextRanges dummy   = null;

            while (cursor != null && cursor.FindPattern(patternString, StandardFindOptions, ref end, ref dummy))
            {
                matches.Add(cursor.CreateEditPoint());
                cursor = end;
            }

            return(matches);
        }
Exemple #13
0
        private bool GetIncludeInfo(ref string path)
        {
            //first we need to find the text thing
            Document doc = App().ActiveDocument;

            if (doc != null)
            {
                TextDocument text = (TextDocument)doc.Object("");

                //this is the current selection's top line #
                int line = text.Selection.CurrentLine;
                int col  = text.Selection.CurrentColumn;

                VirtualPoint activepoint = text.Selection.ActivePoint;
                EditPoint    point       = activepoint.CreateEditPoint();
                point.EndOfLine();

                EditPoint  endfound = null;
                TextRanges found    = null;
                bool       result   = point.FindPattern("opinclude[ \t]+\\\"{.*}\\\"", (int)(vsFindOptions.vsFindOptionsBackwards | vsFindOptions.vsFindOptionsRegularExpression), ref endfound, ref found);

                if (result)
                {
                    int foundline = endfound.Line;

                    //NOTE: I think this is correct...
                    int offset = line - foundline - 1;                    //TODO: get this 1 to be constant in macro expansion!

                    TextRange fullmatch = found.Item(1);

                    // need to break out if the active point wasn't in the line
                    if (fullmatch.StartPoint.Line != activepoint.Line)
                    {
                        return(false);
                    }

                    TextRange filematch = found.Item(2);
                    string    filetext  = filematch.StartPoint.GetText(filematch.EndPoint);

                    //NOTE: this returns what was in the opinclude, but does not resolve the path
                    path = filetext;

                    return(true);
                }
            }

            return(false);
        }
Exemple #14
0
        /// <summary>
        /// aspx页面中关于搜索条件样式替换
        /// </summary>
        /// <param name="textDocument"></param>
        /// <param name="patternString"></param>
        internal void PrcoessWhere(TextDocument textDocument, string patternString)
        {
            var        cursor = textDocument.StartPoint.CreateEditPoint();
            EditPoint  end    = null;
            TextRanges dummy  = null;

            while (cursor != null && cursor.FindPattern(patternString, (int)vsFindOptions.vsFindOptionsRegularExpression, ref end, ref dummy))
            {
                EditPoint startPoint = cursor.CreateEditPoint();
                //matches.Add(startPoint);
                cursor = end;
                string src         = startPoint.GetText(end);
                string replaceMent = "$1 CssClass=\"form-control\"${footer}";
                startPoint.ReplacePattern(end, patternString, replaceMent, (int)vsFindOptions.vsFindOptionsRegularExpression);
            }
        }
Exemple #15
0
        /// <summary>
        /// Retrieves a field from the project's assembly information.
        /// </summary>
        /// <param name="doc">The document object of the AssemblyInfo.cs file.</param>
        /// <param name="assemblyInfoKey">The AssemblyInfo key to get the data for.</param>
        /// <returns>The value of the field.</returns>
        private string RetrieveAssemblyInfoValue(TextDocument doc, string assemblyInfoKey)
        {
            string assemblyInfoValue = string.Empty;

            EditPoint  startPoint = doc.StartPoint.CreateEditPoint();
            EditPoint  blockPoint = startPoint.CreateEditPoint();
            TextRanges trs        = null;

            if (startPoint.FindPattern(string.Format(@"\[assembly\: {0}\("".*""\)\]", assemblyInfoKey), (int)vsFindOptions.vsFindOptionsRegularExpression, ref blockPoint, ref trs))
            {
                startPoint.StartOfLine();
                blockPoint.EndOfLine();
                assemblyInfoValue = startPoint.GetText(blockPoint).Trim();
            }

            return(Regex.Match(assemblyInfoValue, @""".*""").Value);
        }
        /// <summary>
        /// Substitutes all occurrences in the specified text document of
        /// the specified pattern string with the specified replacement string.
        /// </summary>
        /// <param name="textDocument">The text document.</param>
        /// <param name="patternString">The pattern string.</param>
        /// <param name="replacementString">The replacement string.</param>
        internal static void SubstituteAllStringMatches(this TextDocument textDocument, string patternString, string replacementString)
        {
            TextRanges dummy     = null;
            var        lastCount = -1;

            while (textDocument.ReplacePattern(patternString, replacementString, StandardFindOptions, ref dummy))
            {
                // it is possible that the replacements aren't actually being done.  In such a case, we can
                // detect the situation by seeing if the count always remains the same, and if so exiting early.
                if (lastCount == dummy.Count)
                {
                    OutputWindowHelper.WriteLine("EditorConfig had to force a break out of TextDocumentHelper's SubstituteAllStringMatches for a document.");
                    break;
                }
                lastCount = dummy.Count;
            }
        }
        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;
            }
        }
Exemple #18
0
        /// <summary>
        /// 查找代码
        /// </summary>
        /// <param name="win"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        public static string FindCode(Window win, string pattern)
        {
            var doc = (TextDocument)win.Document.Object("TextDocument");

            EditPoint  editPoint = doc.StartPoint.CreateEditPoint();
            EditPoint  endPoint  = null;
            TextRanges tags      = null;

            bool find = editPoint.FindPattern(pattern, (int)(vsFindOptions.vsFindOptionsFromStart |
                                                             vsFindOptions.vsFindOptionsRegularExpression), ref endPoint, ref tags);

            if (find && tags != null)
            {
                return(editPoint.GetText(endPoint));
            }

            return("");
        }
Exemple #19
0
        /// <summary>
        /// Substitutes all occurrences between the specified start and end points of the specified
        /// pattern string with the specified replacement string.
        /// </summary>
        /// <param name="startPoint">The start point.</param>
        /// <param name="endPoint">The end point.</param>
        /// <param name="patternString">The pattern string.</param>
        /// <param name="replacementString">The replacement string.</param>
        internal static void SubstituteAllStringMatches(EditPoint startPoint, EditPoint endPoint, string patternString, string replacementString)
        {
            TextRanges dummy     = null;
            int        lastCount = -1;

            while (startPoint.ReplacePattern(endPoint, patternString, replacementString, StandardFindOptions, ref dummy))
            {
                // it is possible that the replacements aren't actually being done. In such a case,
                // we can detect the situation by seeing if the count always remains the same, and
                // if so exiting early.
                if (lastCount == dummy.Count)
                {
                    OutputWindowHelper.WarningWriteLine("Forced a break out of TextDocumentHelper's SubstituteAllStringMatches for a pair of points.");
                    break;
                }
                lastCount = dummy.Count;
            }
        }
        public static void Execute(ProjectItem projectItem)
        {
            string textToInsert = string.Format(Text, projectItem.Name);

            var       objTextDoc = (TextDocument)projectItem.Document.Object("TextDocument");
            EditPoint editPoint  = objTextDoc.StartPoint.CreateEditPoint();

            while (string.IsNullOrWhiteSpace(editPoint.GetLineText()))
            {
                editPoint.DeleteCurrentLine();
            }

            if (projectItem.ReadAllText().TrimStart().StartsWith(textToInsert, StringComparison.InvariantCulture))
            {
                return;
            }

            var txtSel = (TextSelection)projectItem.Document.Selection;

            txtSel.MoveTo(0, 0);

            TextRanges ranges      = null;
            int        findOptions = (int)(vsFindOptions.vsFindOptionsRegularExpression | vsFindOptions.vsFindOptionsFromStart);

            if (txtSel.FindPattern(RegExText, findOptions, ref ranges))
            {
                var firstRange = ranges.OfType <TextRange>().FirstOrDefault();
                if (firstRange != null)
                {
                    var rangeText = firstRange.StartPoint.GetText(firstRange.EndPoint);
                    if (rangeText.Trim().Equals(textToInsert.Trim(), StringComparison.InvariantCulture))
                    {
                        return;
                    }
                    firstRange.StartPoint.Delete(firstRange.EndPoint);
                }
            }

            txtSel.GotoLine(1, true);
            txtSel.StartOfLine();
            txtSel.NewLine();
            txtSel.GotoLine(1, true);
            txtSel.Insert(textToInsert);
        }
Exemple #21
0
        private static void MoveCodeBlock(CodeElement parent, CodeElement block, EditPoint pastePoint)
        {
            EditPoint  blockStartPoint       = block.StartPoint.CreateEditPoint();
            EditPoint  previousblockEndPoint = blockStartPoint.CreateEditPoint();
            EditPoint  editPoint             = blockStartPoint.CreateEditPoint();
            TextRanges trs = null;

            if (editPoint.FindPattern("}", (int)vsFindOptions.vsFindOptionsBackwards, ref previousblockEndPoint, ref trs))
            {
                if (previousblockEndPoint.GreaterThan(parent.StartPoint))
                {
                    blockStartPoint = previousblockEndPoint;
                }
            }

            blockStartPoint.Cut(block.EndPoint, false);
            pastePoint.Paste();
            pastePoint.Insert("\r\n\r\n");
        }
Exemple #22
0
        /// <summary>mark the method and bring the Visual Studio on front</summary>
        /// <param term='codeFunction'>is the right codeFunction element to the searched method</param>
        /// <param name="methodString">name of the method</param>

        internal void markMethod(CodeFunction codeFunction)
        {
            dte.Documents.Open(codeFunction.ProjectItem.get_FileNames(0), "Auto", false);

            TextSelection textSelection = (TextSelection)dte.ActiveDocument.Selection;

            textSelection.MoveToLineAndOffset(codeFunction.StartPoint.Line, codeFunction.StartPoint.LineCharOffset, false);

            TextRanges textRanges = null;
            string     pattern    = @"[:b]<{" + codeFunction.Name + @"}>[:b(\n]";

            if (textSelection.FindPattern(pattern, (int)vsFindOptions.vsFindOptionsRegularExpression, ref textRanges))
            {
                TextRange r = textRanges.Item(2);
                textSelection.MoveToLineAndOffset(r.StartPoint.Line, r.StartPoint.LineCharOffset, false);
                textSelection.MoveToLineAndOffset(r.EndPoint.Line, r.EndPoint.LineCharOffset, true);
            }
            dte.MainWindow.Activate();
        }
Exemple #23
0
        /// <summary>
        /// 匹配方法
        /// </summary>
        /// <returns></returns>
        private bool toFunc(Window win)
        {
            // 匹配方法定义代码(vs的正则表达式有点特殊)
            string pattern = @":a_ \.\<\>\[\]\t\n";

            switch (_serviceFunc.ParamNum)
            {
            // -1不匹配参数个数
            case -1:
                pattern = string.Format(@"public :c+ {0}\([^\)]*\)", _serviceFunc.Func);
                break;

            case 0:
                pattern = string.Format(@"public :c+ {0}\(\)", _serviceFunc.Func);
                break;

            case 1:
                pattern = string.Format(@"public :c+ {1}\([{0}]+\)", pattern, _serviceFunc.Func);
                break;

            default:
                pattern = string.Format(@"public :c+ {1}\(([{0}]+,)^{2}[{0}]+\)", pattern, _serviceFunc.Func, _serviceFunc.ParamNum - 1);
                break;
            }

            var doc = (TextDocument)win.Document.Object("TextDocument");

            EditPoint  editPoint = doc.StartPoint.CreateEditPoint();
            EditPoint  endPoint  = null;
            TextRanges tags      = null;

            bool find = editPoint.FindPattern(pattern, (int)(vsFindOptions.vsFindOptionsFromStart |
                                                             vsFindOptions.vsFindOptionsRegularExpression), ref endPoint, ref tags);

            if (find && tags != null)
            {
                doc.Selection.MoveToPoint(endPoint, false);
                doc.Selection.MoveToPoint(editPoint, true);
            }

            return(find);
        }
Exemple #24
0
        /// <summary>
        /// Finds all matches of the specified pattern within the specified text selection.
        /// </summary>
        /// <param name="textSelection">The text selection.</param>
        /// <param name="patternString">The pattern string.</param>
        /// <returns>The set of matches.</returns>
        internal static IEnumerable <EditPoint> FindMatches(TextSelection textSelection, string patternString)
        {
            var        matches = new List <EditPoint>();
            var        cursor  = textSelection.TopPoint.CreateEditPoint();
            EditPoint  end     = null;
            TextRanges dummy   = null;

            while (cursor != null && cursor.FindPattern(patternString, StandardFindOptions, ref end, ref dummy))
            {
                if (end.AbsoluteCharOffset > textSelection.BottomPoint.AbsoluteCharOffset)
                {
                    break;
                }

                matches.Add(cursor.CreateEditPoint());
                cursor = end;
            }

            return(matches);
        }
Exemple #25
0
        /// <summary>
        /// Gets a list of insertion points.
        /// </summary>
        /// <param name="fileCodeModel">The code model to search.</param>
        /// <returns>A list of insertion points.</returns>
        private List <EditPoint> GetInsertionPoints(FileCodeModel fileCodeModel)
        {
            List <EditPoint> namespacePoints = new List <EditPoint>();

            for (int i = 1; i <= fileCodeModel.CodeElements.Count; i++)
            {
                if (fileCodeModel.CodeElements.Item(i).Kind == vsCMElement.vsCMElementNamespace)
                {
                    EditPoint  namespacePoint = fileCodeModel.CodeElements.Item(i).StartPoint.CreateEditPoint();
                    TextRanges trs            = null;

                    if (namespacePoint.FindPattern("{", (int)vsFindOptions.vsFindOptionsMatchCase, ref namespacePoint, ref trs))
                    {
                        namespacePoints.Add(namespacePoint);
                    }
                }
            }

            return(namespacePoints);
        }
Exemple #26
0
        /// <summary>
        /// Gets the code block for a given element, this includes any comments that come before the element,
        /// but after the previous element.
        /// </summary>
        /// <param name="parent">The current block's parent.</param>
        /// <param name="block">The current block.</param>
        /// <param name="newStartPoint">The starting point used to capture the beginning of the element.</param>
        /// <returns>The text of a given block.</returns>
        private string GetCodeBlockText(CodeElement parent, CodeElement block, out EditPoint newStartPoint)
        {
            EditPoint  blockStartPoint       = block.StartPoint.CreateEditPoint();
            EditPoint  previousblockEndPoint = blockStartPoint.CreateEditPoint();
            EditPoint  editPoint             = blockStartPoint.CreateEditPoint();
            TextRanges trs = null;

            if (editPoint.FindPattern("}", (int)vsFindOptions.vsFindOptionsBackwards, ref previousblockEndPoint, ref trs))
            {
                if (previousblockEndPoint.GreaterThan(parent.StartPoint))
                {
                    blockStartPoint = previousblockEndPoint;
                }
                else
                {
                    previousblockEndPoint = blockStartPoint.CreateEditPoint();
                    editPoint             = blockStartPoint.CreateEditPoint();
                    if (editPoint.FindPattern("{", (int)vsFindOptions.vsFindOptionsBackwards, ref previousblockEndPoint, ref trs))
                    {
                        if (previousblockEndPoint.GreaterThan(parent.StartPoint))
                        {
                            blockStartPoint = previousblockEndPoint;
                        }
                    }
                }
            }
            else
            {
                if (editPoint.FindPattern("{", (int)vsFindOptions.vsFindOptionsBackwards, ref previousblockEndPoint, ref trs))
                {
                    if (previousblockEndPoint.GreaterThan(parent.StartPoint))
                    {
                        blockStartPoint = previousblockEndPoint;
                    }
                }
            }

            newStartPoint = blockStartPoint.CreateEditPoint();

            return(blockStartPoint.GetText(block.EndPoint).Trim());
        }
Exemple #27
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"))
            {
                try
                {
                    TextDocument projectItemDoc = (TextDocument)ideWindow.Document.Object("TextDocument");
                    EditPoint    startPoint     = projectItemDoc.StartPoint.CreateEditPoint();
                    EditPoint    blockPoint     = startPoint.CreateEditPoint();
                    TextRanges   trs            = null;
                    bool         found          = blockPoint.FindPattern("<copyright", (int)vsFindOptions.vsFindOptionsMatchCase, ref blockPoint, ref trs);
                    if (!found || blockPoint.Line > 2)
                    {
                        Debug.WriteLine("Finding assembly info...");
                        ProjectItem  assemblyInfo = projectItem.DTE.Solution.FindProjectItem("AssemblyInfo.cs");
                        TextDocument objTextDoc   = (TextDocument)ideWindow.Document.Object("TextDocument");

                        assemblyInfo.Open(EnvDTE.Constants.vsViewKindTextView).Activate();
                        TextDocument assemblyDoc = (TextDocument)assemblyInfo.DTE.ActiveWindow.Document.Object("TextDocument");

                        string company   = RetrieveAssemblyInfoValue(assemblyDoc, "AssemblyCompany");
                        string copyright = RetrieveAssemblyInfoValue(assemblyDoc, "AssemblyCopyright");
                        string fileName  = projectItem.Name;

                        Debug.WriteLine("Adding Copyright to file: " + projectItem.Name);
                        AddCopyrightToFile(projectItemDoc, fileName, company, copyright);
                    }
                    else
                    {
                        Debug.WriteLine("Copyright detected, skipping copyright header.");
                    }
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc.ToString());
                    Debug.WriteLine("Format failed, skipping");
                }
            }
        }
Exemple #28
0
        /// <summary>
        /// Updates the #endregion directives to match the names of the matching #region directive
        /// and cleans up any unnecessary white space.
        /// </summary>
        /// <remarks>
        /// This code is very similar to the Common region retrieval function, but since it
        /// manipulates the cursors during processing the logic is different enough to warrant a
        /// separate copy of the code.
        /// </remarks>
        /// <param name="textDocument">The text document to cleanup.</param>
        internal void UpdateEndRegionDirectives(TextDocument textDocument)
        {
            if (!Settings.Default.Cleaning_UpdateEndRegionDirectives)
            {
                return;
            }

            var          regionStack     = new Stack <string>();
            EditPoint    cursor          = textDocument.StartPoint.CreateEditPoint();
            TextRanges   subGroupMatches = null; // Not used - required for FindPattern.
            const string pattern         = @"^[ \t]*#";

            // Keep pushing cursor forwards (note ref cursor parameter) until finished.
            while (cursor != null &&
                   cursor.FindPattern(pattern, TextDocumentHelper.StandardFindOptions, ref cursor, ref subGroupMatches))
            {
                // Create a pointer to capture the text for this line.
                EditPoint eolCursor = cursor.CreateEditPoint();
                eolCursor.EndOfLine();
                string regionText = cursor.GetText(eolCursor);

                if (regionText.StartsWith("region ")) // Space required by compiler.
                {
                    // Cleanup any whitespace in the region name.
                    string regionName        = regionText.Substring(7);
                    string regionNameTrimmed = regionName.Trim();
                    if (regionName != regionNameTrimmed)
                    {
                        cursor.CharRight(7);
                        cursor.Delete(eolCursor);
                        cursor.Insert(regionNameTrimmed);
                    }

                    // Push the parsed region name onto the top of the stack.
                    regionStack.Push(regionNameTrimmed);
                }
                else if (regionText.StartsWith("endregion")) // Space may or may not be present.
                {
                    if (regionStack.Count > 0)
                    {
                        // Do not trim the endRegionName in order to catch whitespace differences.
                        string endRegionName = regionText.Length > 9 ?
                                               regionText.Substring(10) : String.Empty;
                        string matchingRegion = regionStack.Pop();

                        // Update if the strings do not match.
                        if (matchingRegion != endRegionName)
                        {
                            cursor.CharRight(9);
                            cursor.Delete(eolCursor);
                            cursor.Insert(" " + matchingRegion);
                        }
                    }
                    else
                    {
                        // This document is improperly formatted, abort.
                        return;
                    }
                }

                // Note: eolCursor may be outdated now if changes have been made.
                cursor.EndOfLine();
            }
        }
 public bool ReplacePattern(string Pattern, string Replace, int vsFindOptionsValue, ref TextRanges Tags)
 {
     throw new NotImplementedException();
 }
Exemple #30
0
        void UpdateArguments()
        {
            Document doc = App().ActiveDocument;

            //whats the xml file's path?
            string xmlpath   = "";
            bool   available = UpdateXml(ref xmlpath);

            if (!available)
            {
                Arguments.Clear();
                return;
            }

            TextDocument text         = (TextDocument)doc.Object("");
            VirtualPoint currentpoint = text.Selection.ActivePoint;

            EditPoint point = currentpoint.CreateEditPoint();

            point.EndOfLine();

            EditPoint  endfound = null;
            TextRanges found    = null;

            Arguments.Clear();

            bool result = point.FindPattern("note[ \t]+{.*}\\({.*}\\)", (int)(vsFindOptions.vsFindOptionsBackwards | vsFindOptions.vsFindOptionsRegularExpression), ref endfound, ref found);

            if (result)
            {
                TextRange fullmatch = found.Item(1);
                TextRange pathmatch = found.Item(2);
                TextRange argmatch  = found.Item(3);

                //only want it if the point was in the range
                if (fullmatch.EndPoint.LessThan(currentpoint) ||
                    fullmatch.StartPoint.GreaterThan(currentpoint))
                {
                    return;
                }

                ArgumentEnd = argmatch.EndPoint;

                string arguments = argmatch.StartPoint.GetText(argmatch.EndPoint).Trim();

                NoteArguments = arguments.Split(',');

                string notepath = pathmatch.StartPoint.GetText(pathmatch.EndPoint).Trim();

                XmlNoteNode note = XmlFile.GetNote(notepath);

                if (note != null)
                {
                    Arguments = new List <string>();

                    foreach (XmlArgumentNode n in note.Arguments)
                    {
                        Arguments.Add(n.Name);
                    }
                }
            }
        }
Exemple #31
0
        protected bool AddSynchWrapperMember(CodeClass synch, CodeFunction cf)
        {
            if (cf != null && (cf.FunctionKind & FunctionsThatCantBeAnnotatedAsVirtual) == 0 &&
                cf.CanOverride == true && cf.IsShared == false)
            {
                //add prototype and parameters
                CodeFunction synchFunction = synch.AddFunction(cf.Name, cf.FunctionKind, cf.Type, -1, cf.Access, null);
                foreach (CodeParameter param in cf.Parameters)
                {
                    synchFunction.AddParameter(param.Name, param.Type, -1);
                }
                synchFunction.CanOverride = true;
                EditPoint  replaceVirtual = synchFunction.StartPoint.CreateEditPoint();
                TextRanges tr             = null;
                replaceVirtual.ReplacePattern(synchFunction.EndPoint, "virtual", "override",
                                              (int)EnvDTE.vsFindOptions.vsFindOptionsMatchWholeWord, ref tr);

                //remove default return
                EditPoint editPt = synchFunction.EndPoint.CreateEditPoint();
                editPt.LineUp(1);
                editPt.StartOfLine();
                string returnType = cf.Type.AsString;
                if (returnType != "void")
                {
                    EditPoint startOfLastLine = synchFunction.EndPoint.CreateEditPoint();
                    startOfLastLine.LineUp(1);
                    startOfLastLine.EndOfLine();
                    editPt.Delete(startOfLastLine);
                }

                //generate method body
                System.Text.StringBuilder methodBody = new System.Text.StringBuilder(100);
                if (returnType != "void")
                {
                    methodBody.Append(cf.Type.AsString + " ret;\n");
                }
                methodBody.Append(
                    "System.Threading.Monitor.Enter(_root);" +
                    "\ntry{");
                if (returnType != "void")
                {
                    methodBody.Append("\nret = _parent." + cf.Name + "(");
                }
                else
                {
                    methodBody.Append("\n_parent." + cf.Name + "(");
                }
                bool first = true;
                foreach (CodeParameter p in cf.Parameters)
                {
                    if (!first)
                    {
                        methodBody.Append(", ");
                    }
                    first = false;
                    int typeSpaceLocation = p.Type.AsString.IndexOf(' ');
                    if (typeSpaceLocation != -1)                    //append out or ref to parameter
                    {
                        methodBody.Append(p.Type.AsString.Substring(0, typeSpaceLocation + 1));
                    }
                    methodBody.Append(p.Name);
                }
                methodBody.Append(");");
                methodBody.Append(
                    "\n}" +
                    "\nfinally{System.Threading.Monitor.Exit(_root);}");
                if (returnType != "void")
                {
                    methodBody.Append("\nreturn ret;");
                }

                //add new body to method
                editPt.Insert(methodBody.ToString());
                editPt.MoveToPoint(synchFunction.StartPoint);
                editPt.SmartFormat(synchFunction.EndPoint);
            }
            return(true);
        }