public static string GetLineText(this EditPoint point)
        {
            point.StartOfLine();
            var start = point.CreateEditPoint();

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

            return(start.GetText(end));
        }
Пример #2
0
        private static string GetLineText(EditPoint sp)
        {
            var ep = sp.CreateEditPoint();

            ep.StartOfLine();
            var eol = sp.CreateEditPoint();

            eol.EndOfLine();
            return(ep.GetText(eol));
        }
Пример #3
0
        public string GetCurrentWord()
        {
            var selectedText = _dte.ActiveDocument.Selection as TextSelection;

            if (selectedText != null)
            {
                EditPoint topPoint    = selectedText.TopPoint.CreateEditPoint();
                string    currentLine = topPoint.GetLines(topPoint.Line, topPoint.Line + 1);

                if (IsBlank(currentLine))
                {
                    return(string.Empty);
                }

                string result;
                int    charIndex = topPoint.LineCharOffset - 1;

                if (topPoint.AtStartOfLine ||
                    (!char.IsWhiteSpace(currentLine[charIndex]) && char.IsWhiteSpace(currentLine[charIndex - 1])))
                {
                    EditPoint rightPoint = topPoint.CreateEditPoint();
                    rightPoint.WordRight();
                    result = currentLine.Substring(topPoint.LineCharOffset - 1,
                                                   rightPoint.LineCharOffset - topPoint.LineCharOffset).Trim();
                }
                else if (topPoint.AtEndOfLine ||
                         (!char.IsWhiteSpace(currentLine[charIndex - 1]) && char.IsWhiteSpace(currentLine[charIndex])))
                {
                    EditPoint leftPoint = topPoint.CreateEditPoint();
                    leftPoint.WordLeft();
                    result = currentLine.Substring(leftPoint.LineCharOffset - 1,
                                                   topPoint.LineCharOffset - leftPoint.LineCharOffset).Trim();
                }
                else if (char.IsLetterOrDigit(currentLine[charIndex - 1]) &&
                         char.IsLetterOrDigit(currentLine[charIndex + 1]))
                {
                    topPoint.WordLeft();
                    EditPoint rightPoint = topPoint.CreateEditPoint();
                    rightPoint.WordRight();
                    result = currentLine.Substring(topPoint.LineCharOffset - 1,
                                                   rightPoint.LineCharOffset - topPoint.LineCharOffset);
                }
                else
                {
                    result = GetSelectedText();
                }

                return(result);
            }
            return(string.Empty);
        }
        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);
        }
Пример #5
0
            /// <summary>
            /// Find tagged segment within GenInfo.SearchStart and GenInfo.SearchEnd
            /// </summary>
            /// <returns></returns>
            /// <remarks>
            /// Not using EditPoint.FindPattern because it can only search from startpoint to end of doc, no way to limit to selection
            /// Not using DTE Find because it has to change params of current find dialog, might screw up normal find usage
            ///  </remarks>
            static public GeneratedSegment[] FindSegments(Writer writer)
            {
                var regex = _regexDict[writer.TagFormat][writer.SegmentType];
                //Using regex in FindPattern does
                var text     = writer.GetSearchText();
                var matches  = regex.Matches(text);
                var segments = new List <GeneratedSegment>();

                foreach (var m in matches.Cast <Match>())
                {
                    EditPoint matchStart = null;
                    EditPoint matchEnd   = null;

                    if (m.Success)
                    {
                        //Convert match into start and end TextPoints
                        matchStart = writer.SearchStart.CreateEditPoint();
                        matchStart.CharRightExact(m.Index);
                        matchEnd = matchStart.CreateEditPoint();
                        matchEnd.CharRightExact(m.Length);
                    }

                    var range = new TextRange(matchStart, matchEnd);
                    if (range.IsValid)
                    {
                        var tag = ParseTextRange(range, writer.Manager.TagFormat);
                        segments.Add(tag);
                    }
                }
                return(segments.ToArray());
            }
        private static async Task RemoveCommentsAsync(EditPoint objEditPt)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            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]))
                {
                    var newPoint = objEditPt.CreateEditPoint();
                    newPoint.LineDown();
                    if (!newPoint.AtEndOfDocument)
                    {
                        newPoint.StartOfLine();
                    }
                    objEditPt.Delete(newPoint);
                    index++;
                }
                else
                {
                    break;
                }
            }
        }
        /// <summary>
        /// Find tagged segment within GenInfo.SearchStart and GenInfo.SearchEnd
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// Not using EditPoint.FindPattern because it can only search from startpoint to end of doc, no way to limit to selection
        /// Not using DTE Find because it has to change params of current find dialog, might screw up normal find usage
        ///  </remarks>
        public FoundSegment[] FindSegments(Writer info)
        {
            var regex = GetRegexByType(info.SegmentType);

            //Using regex in FindPattern does
            var text     = info.GetSearchText();
            var matches  = regex.Matches(text);
            var segments = new List <FoundSegment>();

            foreach (var m in matches.Cast <Match>())
            {
                EditPoint matchStart = null;
                EditPoint matchEnd   = null;

                if (m.Success)
                {
                    //Convert match into start and end TextPoints
                    matchStart = info.SearchStart.CreateEditPoint();
                    matchStart.CharRightExact(m.Index);
                    matchEnd = matchStart.CreateEditPoint();
                    matchEnd.CharRightExact(m.Length);
                }

                var segment = new FoundSegment(this, info.GenAttribute, matchStart, matchEnd);
                if (segment.IsValid)
                {
                    segments.Add(segment);
                }
            }
            return(segments.ToArray());
        }
Пример #8
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);
        }
Пример #9
0
        /// <summary>
        /// Inserts a #region tag for the specified region preceding the specified start point.
        /// </summary>
        /// <param name="region">The region to start.</param>
        /// <param name="startPoint">The starting point.</param>
        /// <returns>The updated cursor.</returns>
        public EditPoint InsertRegionTag(CodeItemRegion region, EditPoint startPoint)
        {
            var cursor = startPoint.CreateEditPoint();

            // If the cursor is not preceeded only by whitespace, insert a new line.
            var firstNonWhitespaceIndex = cursor.GetLine().TakeWhile(char.IsWhiteSpace).Count();

            if (cursor.DisplayColumn > firstNonWhitespaceIndex + 1)
            {
                cursor.Insert(Environment.NewLine);
            }

            cursor.Insert($"{RegionHelper.GetRegionTagText(cursor, region.Name)}{Environment.NewLine}");

            startPoint.SmartFormat(cursor);

            region.StartPoint = cursor.CreateEditPoint();
            region.StartPoint.LineUp();
            region.StartPoint.StartOfLine();

            var regionWrapper = new[] { region };

            _insertBlankLinePaddingLogic.InsertPaddingBeforeRegionTags(regionWrapper);
            _insertBlankLinePaddingLogic.InsertPaddingAfterRegionTags(regionWrapper);

            return(cursor);
        }
Пример #10
0
        /// <summary>
        /// Removes Blank lines after the opening of a block, or right before the closing of a block.
        /// </summary>
        /// <param name="element">The current code element</param>
        private void FormatBlockSpacing(CodeElement element)
        {
            if (element.Kind != vsCMElement.vsCMElementImportStmt &&
                element.Kind != vsCMElement.vsCMElementVariable &&
                element.Kind != vsCMElement.vsCMElementEvent &&
                element.Kind != vsCMElement.vsCMElementParameter &&
                element.Kind != vsCMElement.vsCMElementAttribute &&
                element.Kind != vsCMElement.vsCMElementOther)
            {
                RemoveInternalBlockPadding(element);
                CheckBlockStart(element);
            }

            if (element.Kind != vsCMElement.vsCMElementParameter)
            {
                CheckBlockEnd(element);

                foreach (CodeElement childElement in element.Children)
                {
                    if (childElement.Kind == vsCMElement.vsCMElementFunction)
                    {
                        EditPoint headerStart = childElement.GetStartPoint(vsCMPart.vsCMPartHeader).CreateEditPoint();
                        EditPoint headerEnd   = headerStart.CreateEditPoint();
                        headerEnd.EndOfLine();
                        string header = headerStart.GetText(headerEnd).Trim();
                        if (header.StartsWith("partial"))
                        {
                            continue;
                        }
                    }

                    FormatBlockSpacing(childElement);
                }
            }
        }
Пример #11
0
        /// <summary>
        /// Inserts an #endregion tag for the specified region following the specified end point.
        /// </summary>
        /// <param name="region">The region to end.</param>
        /// <param name="endPoint">The end point.</param>
        /// <returns>The updated cursor.</returns>
        private EditPoint InsertEndRegionTag(CodeItemRegion region, EditPoint endPoint)
        {
            var cursor = endPoint.CreateEditPoint();

            // If the cursor is not preceeded only by whitespace, insert a new line.
            var firstNonWhitespaceIndex = cursor.GetLine().TakeWhile(char.IsWhiteSpace).Count();

            if (cursor.DisplayColumn > firstNonWhitespaceIndex + 1)
            {
                cursor.Insert(Environment.NewLine);
            }

            cursor.Insert("#endregion " + region.Name);

            // If the cursor is not followed only by whitespace, insert a new line.
            var lastNonWhitespaceIndex = cursor.GetLine().TrimEnd().Length;

            if (cursor.DisplayColumn < lastNonWhitespaceIndex + 1)
            {
                cursor.Insert(Environment.NewLine);
                cursor.LineUp();
                cursor.EndOfLine();
            }

            endPoint.SmartFormat(cursor);

            region.EndPoint = cursor.CreateEditPoint();

            var regionWrapper = new[] { region };

            _insertBlankLinePaddingLogic.InsertPaddingBeforeEndRegionTags(regionWrapper);
            _insertBlankLinePaddingLogic.InsertPaddingAfterEndRegionTags(regionWrapper);

            return(cursor);
        }
        private void ReorderMembers(CodeElement2 type, IEnumerable <CodeMember> members, string orderedCode, TextPoint startPoint)
        {
            // Removing members will shift the startPoint back one line.
            // So we'll use the absolute offset to jump back to that insert point.
            int startPointOffset = 0;

            if (startPoint != null)
            {
                startPointOffset = startPoint.AbsoluteCharOffset;
            }

            FileCodeModel2 codeModel = this.textHandler.Document.ProjectItem.FileCodeModel as FileCodeModel2;

            codeModel.BeginBatch();
            try
            {
                foreach (CodeMember member in members)
                {
                    member.Remove();
                }
            }
            finally
            {
                codeModel.EndBatch();
            }

            if (startPoint != null)
            {
                EditPoint startEdit = startPoint.CreateEditPoint();
                startEdit.MoveToAbsoluteOffset(startPointOffset);
                startEdit.StartOfLine();

                // If the line above startEdit isn't empty and isn't the start of the class/struct/interface/enum,
                // then insert a blank line so the sortedCode will be separated from the code above it.
                EditPoint lineAboveEdit = startEdit.CreateEditPoint();
                lineAboveEdit.LineUp();
                lineAboveEdit.StartOfLine();
                string lineText = lineAboveEdit.GetText(lineAboveEdit.LineLength).Trim();
                if (lineText.Length != 0 &&
                    lineAboveEdit.Line > type.StartPoint.Line &&
                    (this.language != Language.CSharp || lineText != "{"))
                {
                    startEdit.Insert(Environment.NewLine);
                }

                startEdit.Insert(orderedCode);

                // If the line after startEdit isn't empty and isn't the end of the class/struct/interface/enum,
                // then insert a blank line so the sortedCode will be separated from the code below it.
                startEdit.StartOfLine();
                lineText = startEdit.GetText(startEdit.LineLength).Trim();
                if (lineText.Length != 0 &&
                    startEdit.Line < type.EndPoint.Line &&
                    (this.language != Language.CSharp || lineText != "}"))
                {
                    startEdit.Insert(Environment.NewLine);
                }
            }
        }
Пример #13
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);
                }
            }
        }
Пример #14
0
        /// <summary>
        /// Expand a textpoint to the full comment, in the direction specified by the <paramref name="foundAction"/>.
        /// </summary>
        /// <param name="point">The initial starting point for the expansion.</param>
        /// <param name="foundAction">An action which advances the search either up or down.</param>
        /// <returns>
        /// The endpoint of the comment, or <c>null</c> if the expansion did not find a valid comment.
        /// </returns>
        private EditPoint Expand(TextPoint point, Action <EditPoint> foundAction)
        {
            EditPoint current = point.CreateEditPoint();
            EditPoint result  = null;
            string    prefix  = null;

            do
            {
                var line = current.Line;
                var text = current.GetLine();

                var match = _commentLineRegex.Match(text);
                if (match.Success)
                {
                    // Cancel the expansion if the prefix does not match. This takes priority over
                    // the initial spacer check to allow formatting comments adjacent to Stylecop
                    // SA1626 style commented code.
                    var currentPrefix = match.Groups["prefix"].Value.TrimStart();
                    if (prefix != null && !string.Equals(prefix, currentPrefix))
                    {
                        break;
                    }
                    else
                    {
                        prefix = currentPrefix;
                    }

                    // The initial spacer is required, otherwise we assume this is commented out
                    // code and do not format.
                    if (match.Groups["initialspacer"].Success)
                    {
                        result = current.CreateEditPoint();
                        foundAction(current);

                        // If result and iterator line are the same, the found action (move line up or
                        // down) did nothing. This means we're at the start or end of the file, and
                        // there is no point to keep searching, it would create an infinite loop.
                        if (result.Line == current.Line)
                        {
                            break;
                        }
                    }
                    else
                    {
                        // Did not succesfully match the intial spacer, we have to assume this is
                        // code and cancel all formatting.
                        result  = null;
                        current = null;
                    }
                }
                else
                {
                    current = null;
                }
            } while (current != null);

            return(result);
        }
        public static void DeleteCurrentLine(this EditPoint start)
        {
            start.StartOfLine();
            var point = start.CreateEditPoint();

            start.LineDown();
            start.StartOfLine();
            point.Delete(start);
        }
        public static string GetActiveDocumentText(this DTE dte)
        {
            TextDocument objTextDoc = (TextDocument)dte.ActiveDocument.Object("TextDocument");
            EditPoint    endPoint   = objTextDoc.EndPoint.CreateEditPoint();
            EditPoint    startPoint = objTextDoc.StartPoint.CreateEditPoint();
            string       message    = startPoint.CreateEditPoint().GetText(endPoint);

            return(message);
        }
Пример #17
0
        private EditPoint Expand(TextPoint point, Action <EditPoint> foundAction)
        {
            EditPoint current = point.CreateEditPoint();
            EditPoint result  = null;
            string    prefix  = null;

            do
            {
                var line = current.Line;
                var text = current.GetLine();

                var match = _commentLineRegex.Match(text);
                if (match.Success)
                {
                    // The initial spacer is required, otherwise we assume this is commented out
                    // code and do not format.
                    if (match.Groups["initialspacer"].Success)
                    {
                        // Get the comment prefix for the current line.
                        var currentPrefix = match.Groups["prefix"].Value.TrimStart();
                        if (prefix == null)
                        {
                            prefix = currentPrefix;
                        }

                        // Cancel the expanding if the prefix does not match.
                        if (prefix != currentPrefix)
                        {
                            break;
                        }

                        result = current.CreateEditPoint();
                        foundAction(current);

                        // If result and iterator line are the same, the found action (move line up or
                        // down) did nothing. This means we're at the start or end of the file, and
                        // there is no point to keep searching, it would create an infinite loop.
                        if (result.Line == current.Line)
                        {
                            break;
                        }
                    }
                    else
                    {
                        // This is code! Set to null to abandon loop.
                        result  = null;
                        current = null;
                    }
                }
                else
                {
                    current = null;
                }
            } while (current != null);

            return(result);
        }
Пример #18
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");
        }
Пример #19
0
        /// <summary>
        /// Indicates whether the current point is on a line with only a comment.
        /// </summary>
        /// <param name="point">The current point of the document.</param>
        /// <returns>True if the line contains only a comment.</returns>
        private static bool IsCommentLine(EditPoint point)
        {
            // Verify the current thread is the UI thread.
            ThreadHelper.ThrowIfNotOnUIThread();

            // This will extract the current line from the given point and determine if it passes the sniff test for a comment.
            EditPoint endOfLine = point.CreateEditPoint();

            endOfLine.EndOfLine();
            return(FormatCommentCommand.commentRegex.IsMatch(point.GetText(endOfLine)));
        }
Пример #20
0
        /// <summary>
        /// Evaluates whether elements within a class have been sorted already or not.
        /// </summary>
        /// <param name="codeElement">The code element representing the class.</param>
        /// <returns>True if the class has already been sorted.</returns>
        private bool EvaluateElementsWithinClassSorted(CodeElement codeElement)
        {
            try
            {
                CodeBlock lastBlock    = null;
                CodeBlock currentBlock = null;
                Array     accessLevels = Enum.GetValues(typeof(vsCMAccess));
                for (int i = 1; i <= codeElement.Children.Count; i++)
                {
                    CodeElement element           = codeElement.Children.Item(i);
                    EditPoint   elementStartPoint = element.StartPoint.CreateEditPoint();
                    EditPoint   newStartPoint     = elementStartPoint.CreateEditPoint();

                    currentBlock = null;
                    if (CodeElementBlockTypes.ContainsKey(element.Kind))
                    {
                        currentBlock = EvaluateBlock(codeElement, element, ref newStartPoint);
                    }

                    if (currentBlock != null)
                    {
                        if (lastBlock != null)
                        {
                            if (lastBlock.Placement != currentBlock.Placement)
                            {
                                if (lastBlock.Placement.CompareTo(currentBlock.Placement) > 0)
                                {
                                    Debug.WriteLine(currentBlock.Placement + " - " + currentBlock.Access + " belongs before " + lastBlock.Placement + " - " + lastBlock.Access + "; Sorting Required.");
                                    return(false);
                                }
                            }
                            else
                            {
                                if (lastBlock.Access.CompareTo(currentBlock.Access) > 0)
                                {
                                    Debug.WriteLine(currentBlock.Placement + " - " + currentBlock.Access + " belongs before " + lastBlock.Placement + " - " + lastBlock.Access + "; Sorting Required.");
                                    return(false);
                                }
                            }
                        }

                        lastBlock = currentBlock;
                    }
                }
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc.ToString());
                Debug.WriteLine("-- Class Reverted --");
            }

            Debug.WriteLine("Class is already sorted, returning");
            return(true);
        }
        private static bool IsAtVisibleEndOfLine(TextPoint point)
        {
            EditPoint startEdit = point.CreateEditPoint();
            EditPoint endEdit   = startEdit.CreateEditPoint();

            endEdit.EndOfLine();
            string text   = startEdit.GetText(endEdit);
            bool   result = string.IsNullOrEmpty((text ?? string.Empty).Trim());

            return(result);
        }
        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);
        }
Пример #23
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());
        }
Пример #24
0
        /// <summary>
        /// 文字列の終了位置を作成します。
        /// </summary>
        private static EditPoint CreateEndPoint(VirtualPoint point, EditPoint startPoint)
        {
            var result = point.CreateEditPoint();

            if (point.AtEndOfLine || result.GetText(1) == " ")
            {
                return(result);
            }

            result = startPoint.CreateEditPoint();
            result.WordRight();
            return(result);
        }
Пример #25
0
        /// <summary>
        /// Checks to see if there should be additional blank lines immediately after starting a block
        /// </summary>
        /// <param name="element">The current element to check</param>
        private void CheckBlockStart(CodeElement element)
        {
            EditPoint start = element.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();
            EditPoint end   = element.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

            EditPoint beginStart = start.CreateEditPoint();

            beginStart.StartOfLine();

            string beginningStartText = beginStart.GetText(start).Trim();

            if (beginningStartText != string.Empty)
            {
                EditPoint endStart = start.CreateEditPoint();
                endStart.EndOfLine();
                string restofStartText = start.GetText(endStart).Trim();
                if (!restofStartText.StartsWith("get;"))
                {
                    start.Insert(Environment.NewLine);
                    start.SmartFormat(endStart);
                }
            }
        }
Пример #26
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));
        }
Пример #27
0
        /// <summary>
        /// Retrieves code regions based on the specified edit points.
        /// </summary>
        /// <param name="editPoints">The edit points to walk.</param>
        /// <returns>An enumerable collection of regions.</returns>
        private static IEnumerable <CodeItemRegion> RetrieveCodeRegions(IEnumerable <EditPoint> editPoints)
        {
            var regionStack = new Stack <CodeItemRegion>();
            var codeItems   = new List <CodeItemRegion>();

            foreach (var cursor in editPoints)
            {
                // Create a pointer to capture the text for this line.
                EditPoint eolCursor = cursor.CreateEditPoint();
                eolCursor.EndOfLine();
                string regionText = cursor.GetText(eolCursor).TrimStart(new[] { ' ', '\t' });

                if (regionText.StartsWith("#region ")) // Space required by compiler.
                {
                    // Get the region name.
                    string regionName = regionText.Substring(8).Trim();

                    // Push the parsed region info onto the top of the stack.
                    regionStack.Push(new CodeItemRegion
                    {
                        Name        = regionName,
                        StartLine   = cursor.Line,
                        StartOffset = cursor.AbsoluteCharOffset,
                        StartPoint  = cursor.CreateEditPoint()
                    });
                }
                else if (regionText.StartsWith("#endregion"))
                {
                    if (regionStack.Count > 0)
                    {
                        CodeItemRegion region = regionStack.Pop();
                        region.EndLine   = eolCursor.Line;
                        region.EndOffset = eolCursor.AbsoluteCharOffset;
                        region.EndPoint  = eolCursor.CreateEditPoint();

                        codeItems.Add(region);
                    }
                    else
                    {
                        // This document is improperly formatted, abort.
                        return(Enumerable.Empty <CodeItemRegion>());
                    }
                }
            }

            return(codeItems);
        }
Пример #28
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);
        }
Пример #29
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;
            }
        }
Пример #30
0
        /// <summary>
        /// Inserts an #endregion tag for the specified region following the specified end point.
        /// </summary>
        /// <param name="region">The region to end.</param>
        /// <param name="endPoint">The end point.</param>
        /// <returns>The updated cursor.</returns>
        public EditPoint InsertEndRegionTag(CodeItemRegion region, EditPoint endPoint)
        {
            var cursor = endPoint.CreateEditPoint();

            // If the cursor is not preceeded only by whitespace, insert a new line.
            var firstNonWhitespaceIndex = cursor.GetLine().TakeWhile(char.IsWhiteSpace).Count();

            if (cursor.DisplayColumn > firstNonWhitespaceIndex + 1)
            {
                cursor.Insert(Environment.NewLine);
            }

            cursor.Insert(RegionHelper.GetEndRegionTagText(cursor));

            if (Settings.Default.Cleaning_UpdateEndRegionDirectives &&
                RegionHelper.LanguageSupportsUpdatingEndRegionDirectives(cursor))
            {
                cursor.Insert(" " + region.Name);
            }

            // If the cursor is not followed only by whitespace, insert a new line.
            var lastNonWhitespaceIndex = cursor.GetLine().TrimEnd().Length;

            if (cursor.DisplayColumn < lastNonWhitespaceIndex + 1)
            {
                cursor.Insert(Environment.NewLine);
                cursor.LineUp();
                cursor.EndOfLine();
            }

            endPoint.SmartFormat(cursor);

            region.EndPoint = cursor.CreateEditPoint();

            var regionWrapper = new[] { region };

            _insertBlankLinePaddingLogic.InsertPaddingBeforeEndRegionTags(regionWrapper);
            _insertBlankLinePaddingLogic.InsertPaddingAfterEndRegionTags(regionWrapper);

            return(cursor);
        }
Пример #31
0
        /// <summary>
        /// Inserts an #endregion tag for the specified region following the specified end point.
        /// </summary>
        /// <param name="region">The region to end.</param>
        /// <param name="endPoint">The end point.</param>
        /// <returns>The updated cursor.</returns>
        public EditPoint InsertEndRegionTag(CodeItemRegion region, EditPoint endPoint)
        {
            var cursor = endPoint.CreateEditPoint();

            // If the cursor is not preceeded only by whitespace, insert a new line.
            var firstNonWhitespaceIndex = cursor.GetLine().TakeWhile(char.IsWhiteSpace).Count();
            if (cursor.DisplayColumn > firstNonWhitespaceIndex + 1)
            {
                cursor.Insert(Environment.NewLine);
            }

            cursor.Insert("#endregion");

            if (Settings.Default.Cleaning_UpdateEndRegionDirectives)
            {
                cursor.Insert(" " + region.Name);
            }

            // If the cursor is not followed only by whitespace, insert a new line.
            var lastNonWhitespaceIndex = cursor.GetLine().TrimEnd().Length;
            if (cursor.DisplayColumn < lastNonWhitespaceIndex + 1)
            {
                cursor.Insert(Environment.NewLine);
                cursor.LineUp();
                cursor.EndOfLine();
            }

            endPoint.SmartFormat(cursor);

            region.EndPoint = cursor.CreateEditPoint();

            var regionWrapper = new[] { region };
            _insertBlankLinePaddingLogic.InsertPaddingBeforeEndRegionTags(regionWrapper);
            _insertBlankLinePaddingLogic.InsertPaddingAfterEndRegionTags(regionWrapper);

            return cursor;
        }
        private void ToggleCommentsAboveMember(EditPoint editPoint, string commentPrefix)
        {
            try {
                int? firstLineOfComment = null;
                editPoint.StartOfLine();
                editPoint.CharLeft();
                while(!editPoint.AtStartOfDocument) {
                    String line = editPoint.GetLines(editPoint.Line, editPoint.Line + 1).Trim();
                    if(line.Length == 0 || line.StartsWith(commentPrefix)) {
                        if(line.Length > 0) {
                            firstLineOfComment = editPoint.Line;
                        } else if(firstLineOfComment.HasValue) {
                            ToggleExpansionAtLine(editPoint.CreateEditPoint(), firstLineOfComment.Value, commentPrefix);
                            firstLineOfComment = null;
                        }

                        editPoint.StartOfLine();
                        editPoint.CharLeft();
                    } else {
                        break;
                    }

                }

                if(firstLineOfComment.HasValue) {
                    ToggleExpansionAtLine(editPoint.CreateEditPoint(), firstLineOfComment.Value, commentPrefix);
                }

            }
            catch(Exception) { }
        }
Пример #33
0
        /// <summary>
        /// Inserts regions per user settings.
        /// </summary>
        /// <param name="codeItems">The code items.</param>
        /// <param name="insertPoint">The default insertion point.</param>
        public void InsertRegions(IEnumerable<BaseCodeItem> codeItems, EditPoint insertPoint)
        {
            // Refresh and sort the code items.
            foreach (var codeItem in codeItems)
            {
                codeItem.RefreshCachedPositionAndName();
            }

            codeItems = codeItems.OrderBy(x => x.StartOffset).ToList();

            var regions = ComposeRegionsList(codeItems);
            var codeItemEnumerator = codeItems.GetEnumerator();
            codeItemEnumerator.MoveNext();
            EditPoint cursor = insertPoint.CreateEditPoint();

            foreach (var region in regions)
            {
                // While the current code item is a region not in the list, advance to the next code item.
                var currentCodeItemAsRegion = codeItemEnumerator.Current as CodeItemRegion;
                while (currentCodeItemAsRegion != null && !regions.Contains(currentCodeItemAsRegion, _regionComparerByName))
                {
                    cursor = codeItemEnumerator.Current.EndPoint;
                    codeItemEnumerator.MoveNext();
                    currentCodeItemAsRegion = codeItemEnumerator.Current as CodeItemRegion;
                }

                // If the current code item is this region, advance to the next code item and end this iteration.
                if (_regionComparerByName.Equals(currentCodeItemAsRegion, region))
                {
                    cursor = codeItemEnumerator.Current.EndPoint;
                    codeItemEnumerator.MoveNext();
                    continue;
                }

                // Update the cursor position to the current code item.
                if (codeItemEnumerator.Current != null)
                {
                    cursor = codeItemEnumerator.Current.StartPoint;
                }

                // If the current code item is a region, offset the position by 1 to workaround points not tracking for region types.
                if (currentCodeItemAsRegion != null)
                {
                    cursor = cursor.CreateEditPoint();
                    currentCodeItemAsRegion.StartPoint.CharRight();
                    currentCodeItemAsRegion.EndPoint.CharRight();
                }

                // Insert the #region tag
                cursor = InsertRegionTag(region, cursor);

                // Keep jumping forwards in code items as long as there's matches.
                while (CodeItemBelongsInRegion(codeItemEnumerator.Current, region))
                {
                    cursor = codeItemEnumerator.Current.EndPoint;
                    codeItemEnumerator.MoveNext();
                }

                // Insert the #endregion tag
                cursor = InsertEndRegionTag(region, cursor);

                // If the current code item is a region, reverse offset of the position.
                if (currentCodeItemAsRegion != null)
                {
                    currentCodeItemAsRegion.StartPoint.CharLeft();
                    currentCodeItemAsRegion.EndPoint.CharLeft();
                }
            }
        }
Пример #34
0
        /// <summary>
        /// Inserts a #region tag for the specified region preceding the specified start point.
        /// </summary>
        /// <param name="region">The region to start.</param>
        /// <param name="startPoint">The starting point.</param>
        /// <returns>The updated cursor.</returns>
        private EditPoint InsertRegionTag(CodeItemRegion region, EditPoint startPoint)
        {
            var cursor = startPoint.CreateEditPoint();

            // If the cursor is not preceeded only by whitespace, insert a new line.
            var firstNonWhitespaceIndex = cursor.GetLine().TakeWhile(char.IsWhiteSpace).Count();
            if (cursor.DisplayColumn > firstNonWhitespaceIndex + 1)
            {
                cursor.Insert(Environment.NewLine);
            }

            cursor.Insert(string.Format("#region {0}{1}", region.Name, Environment.NewLine));

            startPoint.SmartFormat(cursor);

            region.StartPoint = cursor.CreateEditPoint();
            region.StartPoint.LineUp();
            region.StartPoint.StartOfLine();

            var regionWrapper = new[] { region };
            _insertBlankLinePaddingLogic.InsertPaddingBeforeRegionTags(regionWrapper);
            _insertBlankLinePaddingLogic.InsertPaddingAfterRegionTags(regionWrapper);

            return cursor;
        }