예제 #1
0
        private void codeTemplateCmdEvent_Click(object CommandBarControl, ref bool Handled, ref bool CancelDefault)
        {
            CommandBarControl ctrl    = CommandBarControl as CommandBarControl;
            string            content = CodeTemplateManager.Instance.GetTemplateContent(ctrl.Caption);

            int  indexOfSelectedParam = CodeTemplateManager.Instance.IndexOfSelectedParam(content);
            bool surroundSelectedText = (indexOfSelectedParam >= 0);

            TextSelection selected    = _applicationObject.ActiveDocument.Selection as TextSelection;
            EditPoint     topPoint    = selected.TopPoint.CreateEditPoint();
            EditPoint     bottomPoint = selected.BottomPoint.CreateEditPoint();

            if (surroundSelectedText)
            {
                string beforeSelectedParam =
                    CodeTemplateManager.Instance.GetTextBeforeSelectedParam(content);
                string afterSelectedParam =
                    CodeTemplateManager.Instance.GetTextAfterSelectedParam(content);

                topPoint.LineUp(1);
                topPoint.EndOfLine();
                topPoint.Insert(Environment.NewLine);
                topPoint.Insert(beforeSelectedParam);

                bottomPoint.EndOfLine();
                bottomPoint.Insert(Environment.NewLine);
                bottomPoint.Insert(afterSelectedParam);
            }
            else
            {
                topPoint.Delete(bottomPoint);
                topPoint.Insert(content);
            }
        }
예제 #2
0
 private void update(int reset = 0)
 {
     if (reset == 1)
     {
         _data.Text          = "";
         _data.Line          = "";
         _data.Anchor        = 1;
         _data.Active        = 1;
         _data.LineBegOffset = 1;
         _data.LineEndOffset = 1;
     }
     else
     {
         TextSelection selection = App.ActiveDocument.Selection as TextSelection;
         VirtualPoint  active    = selection.ActivePoint;
         VirtualPoint  anchor    = selection.AnchorPoint;
         EditPoint     point0    = active.CreateEditPoint();
         EditPoint     point1    = active.CreateEditPoint();
         point0.StartOfLine();
         point1.EndOfLine();
         _data.Line          = point0.GetText(point1);
         _data.LineBegOffset = toPosition(point0.AbsoluteCharOffset);
         _data.LineEndOffset = toPosition(point1.AbsoluteCharOffset);
         point0.StartOfDocument();
         point1.EndOfDocument();
         _data.Text   = point0.GetText(point1);
         _data.Anchor = toPosition(anchor.AbsoluteCharOffset);
         _data.Active = toPosition(active.AbsoluteCharOffset);
     }
 }
예제 #3
0
        /// <summary>
        /// Expands a text point to the full comment.
        /// </summary>
        /// <param name="point">The original text point to expand from.</param>
        private void Expand(TextPoint point)
        {
            var i = point.CreateEditPoint();

            // Look up to find the start of the comment.
            _startPoint = Expand(point, p => p.LineUp());

            // If a valid start is found, look down to find the end of the comment.
            if (_startPoint != null)
            {
                _endPoint = Expand(point, p => p.LineDown());
            }

            // If both start and endpoint are valid, the comment is valid.
            if (_startPoint != null && _endPoint != null)
            {
                _startPoint.StartOfLine();
                _endPoint.EndOfLine();
                IsValid = true;
            }
            else
            {
                IsValid = false;
            }
        }
예제 #4
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);
                }
            }
        }
예제 #5
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);
                }
            }
        }
예제 #6
0
        public bool ImpInterface(string intType, Project intPrj, CodeInterface intObj, ref CodeClass intCla)
        {
            Project prjObj = null;

            if (!prjCreate(intType, ref prjObj))
            {
                return(false);
            }
            // add the necessary references
            VSProject vsPrj = (VSProject)prjObj.Object;
            Reference vsref = vsPrj.References.AddProject(intPrj);



            string claName;

            claName = intObj.Name;
            CodeInterface[] Ints = new CodeInterface[1];
            Ints[0] = intObj;

            prjObj.ProjectItems.AddFromTemplate("C:\\Program Files\\Microsoft Visual Studio .NET\\VC#\\CSharpProjectItems\\NewCSharpFile.cs", claName + ".cs");


            ProjectItem   pi = prjObj.ProjectItems.Item(claName + ".cs");
            CodeNamespace cn = pi.FileCodeModel.AddNamespace(intType, 0);
            TextPoint     tp = cn.GetStartPoint(EnvDTE.vsCMPart.vsCMPartHeader);
            EditPoint     ep = tp.CreateEditPoint();

            ep.StartOfDocument();
            ep.Insert("using " + intObj.Namespace.FullName + ";\n");
            CodeClass cc = cn.AddClass(intObj.Name, 0, null, null, EnvDTE.vsCMAccess.vsCMAccessPublic);

            tp = cc.GetStartPoint(EnvDTE.vsCMPart.vsCMPartName);
            ep = tp.CreateEditPoint();
            ep.EndOfLine();
            ep.Insert(" : " + intObj.FullName);
            cc.Comment = intObj.Comment;
            foreach (CodeElement ce in intObj.Members)
            {
                if (ce.Kind == EnvDTE.vsCMElement.vsCMElementFunction)
                {
                    CodeFunction  cf   = (CodeFunction)ce;
                    CodeFunction  cf1  = cc.AddFunction(cf.Name, cf.FunctionKind, cf.Type, 0, cf.Access, 0);
                    CodeParameter cep1 = null;
                    foreach (CodeElement cep in cf.Parameters)
                    {
                        CodeParameter cp = (CodeParameter)cep;
                        cep1 = cf1.AddParameter(cp.Name, cp.Type, -1);
                    }
                }
            }


            intCla = cc;
            return(true);
        }
        public static string GetLineText(this EditPoint point)
        {
            point.StartOfLine();
            var start = point.CreateEditPoint();

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

            return(start.GetText(end));
        }
예제 #8
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)));
        }
        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);
        }
예제 #10
0
        internal static void InsertBlankLineBeforePoint(EditPoint point)
        {
            if (point.Line <= 1) return;

            point.LineUp(1);
            point.StartOfLine();

            string text = point.GetLines(point.Line, point.Line + 1);
            if (Regex.IsMatch(text, @"^\s*[^\s\{]"))
            {
                point.EndOfLine();
                point.Insert(Environment.NewLine);
            }
        }
        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);
        }
예제 #12
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);
        }
예제 #13
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));
        }
예제 #14
0
        public bool CreateSynchClass()
        {
            CodeClass synchClass = _cc.AddClass("Synch" + _cc.Name, -1, 0,
                                                0, EnvDTE.vsCMAccess.vsCMAccessPrivate);

            synchClass.AddBase(_cc, -1);

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

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

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

            EditPoint editPt = synchClass.StartPoint.CreateEditPoint();

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

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

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

            return(true);
        }
예제 #15
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);
        }
예제 #16
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);
        }
예제 #17
0
        /// <summary>
        /// Extends selection the the beginning and end of the lines.
        /// </summary>
        public void SelectFullLines(vsStartOfLineOptions startOptions, out EditPoint topPoint, out EditPoint bottomPoint)
        {
            topPoint = selection.TopPoint.CreateEditPoint();
            topPoint.StartOfLine();

            // move to the first word on the right:
            if (startOptions == vsStartOfLineOptions.vsStartOfLineOptionsFirstText)
            {
                topPoint.WordRight(1);
            }

            bottomPoint = selection.BottomPoint.CreateEditPoint();
            bottomPoint.EndOfLine();

            selection.MoveToPoint(topPoint, false);
            selection.MoveToPoint(bottomPoint, true);
        }
예제 #18
0
        /// <summary>
        /// Inserts a blank line before the specified point except where adjacent to a brace.
        /// </summary>
        /// <param name="point">The point.</param>
        internal static void InsertBlankLineBeforePoint(EditPoint point)
        {
            if (point.Line <= 1)
            {
                return;
            }

            point.LineUp(1);
            point.StartOfLine();

            string text = point.GetLine();

            if (RegexNullSafe.IsMatch(text, @"^\s*[^\s\{]")) // If it is not a scope boundary, insert newline.
            {
                point.EndOfLine();
                point.Insert(Environment.NewLine);
            }
        }
        public override void Execute()
        {
            _codeMethod.CanOverride = true;
            _codeMethod.Access      = vsCMAccess.vsCMAccessProtected;
            if (Utility.IsSealedOrStatic((CodeClass)_codeMethod.Parent))
            {
                _codeMethod.CanOverride = false;
                _codeMethod.Access      = vsCMAccess.vsCMAccessPrivate;
            }

            if (_eventTopic != null)
            {
                string    _fireMethodPattern = (_codeMethod.Language == CodeModelLanguageConstants.vsCMLanguageCSharp) ? _fireMethodPatternCS : _fireMethodPatternVB;
                string    codeText           = String.Format(_fireMethodPattern, _eventTopic);
                EditPoint sp = _codeMethod.StartPoint.CreateEditPoint();
                sp.EndOfLine();
                sp.ReplaceText(_codeMethod.EndPoint, codeText, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);
            }
        }
예제 #20
0
        protected void AddOneLineImpl(string NewLine, CodeFunction Target, bool ReplaceExisingLine)
        {
            //Target.GetEndPoint(EnvDTE.vsCMPart.vsCMPartBody);
            EditPoint startOfLastLine = Target.GetEndPoint(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter).CreateEditPoint();

            startOfLastLine.LineUp(1);
            startOfLastLine.StartOfLine();
            EditPoint endOfLastLine = Target.GetEndPoint(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter).CreateEditPoint();

            endOfLastLine.LineUp(1);
            endOfLastLine.EndOfLine();
            if (ReplaceExisingLine)
            {
                startOfLastLine.Delete(endOfLastLine);
            }
            else
            {
                startOfLastLine.EndOfLine();
            }
            startOfLastLine.Insert(NewLine);
        }
예제 #21
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);
                }
            }
        }
예제 #22
0
        /// <summary>
        /// Returns an adjusted CodeElement. Walks comments 'down' to the next real element.
        /// From Rick Strahl's Weblog
        /// </summary>
        /// <returns></returns>
        static public CodeElement GetCodeElementFromActivePoint()
        {
            EditPoint selPoint = GetActiveEditPoint();

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

            selPoint.StartOfLine();

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

            return(GetActiveCodeElement());
        }
예제 #23
0
        /// <summary>
        /// Performs the style task.
        /// </summary>
        /// <param name="projectItem">The project Item</param>
        /// <param name="ideWindow">The IDE window.</param>
        protected override void DoWork(ProjectItem projectItem, EnvDTE.Window ideWindow)
        {
            if (projectItem.Name.EndsWith(".cs"))
            {
                Debug.WriteLine("Formatting Spacing Around Comments: " + projectItem.Name);
                try
                {
                    TextDocument objTextDoc   = (TextDocument)ideWindow.Document.Object("TextDocument");
                    EditPoint    objEditPoint = objTextDoc.CreateEditPoint(objTextDoc.StartPoint);
                    EditPoint    commentPoint = objEditPoint.CreateEditPoint();
                    TextRanges   trs          = null;

                    while (objEditPoint.FindPattern("//", (int)vsFindOptions.vsFindOptionsMatchCase, ref commentPoint, ref trs))
                    {
                        bool      previousBlank          = false;
                        bool      isNotInline            = true;
                        EditPoint beginningLineEditPoint = objEditPoint.CreateEditPoint();
                        beginningLineEditPoint.StartOfLine();
                        if (beginningLineEditPoint.GetText(objEditPoint).Trim() != string.Empty)
                        {
                            isNotInline = false;
                        }

                        if (isNotInline)
                        {
                            EditPoint previousCheckPoint = objEditPoint.CreateEditPoint();
                            previousCheckPoint.LineUp(1);
                            if (previousCheckPoint.GetText(objEditPoint).Trim() == string.Empty)
                            {
                                previousBlank = true;
                            }

                            commentPoint.CharRight(1);
                            string comment = objEditPoint.GetText(commentPoint);
                            while (!comment.EndsWith(" ") && !commentPoint.AtEndOfLine)
                            {
                                if (comment.EndsWith("/"))
                                {
                                    commentPoint.CharRight(1);
                                }
                                else
                                {
                                    commentPoint.CharLeft(1);
                                    commentPoint.Insert(" ");
                                }

                                comment = objEditPoint.GetText(commentPoint);
                            }

                            commentPoint.CharRight(1);
                            comment = objEditPoint.GetText(commentPoint);
                            if (comment.EndsWith("  "))
                            {
                                commentPoint.CharLeft(1);
                                commentPoint.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsHorizontal);
                                commentPoint.Insert(" ");
                            }

                            if (commentPoint.Line > objEditPoint.Line)
                            {
                                commentPoint.LineUp(1);
                                commentPoint.EndOfLine();
                            }

                            if (commentPoint.AtEndOfLine)
                            {
                                objEditPoint.Delete(commentPoint);
                            }
                            else
                            {
                                EditPoint endComment = commentPoint.CreateEditPoint();
                                endComment.EndOfLine();
                                if (commentPoint.GetText(endComment).Trim() == string.Empty)
                                {
                                    objEditPoint.Delete(endComment);
                                }
                                else
                                {
                                    objEditPoint.LineDown(1);
                                    previousBlank = false;
                                }
                            }

                            objEditPoint.StartOfLine();
                            commentPoint = objEditPoint.CreateEditPoint();
                            commentPoint.EndOfLine();
                            if (objEditPoint.GetText(commentPoint).Trim() == string.Empty)
                            {
                                objEditPoint.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical);
                                if (previousBlank)
                                {
                                    objEditPoint.Insert("\r\n");
                                }
                            }
                        }

                        objEditPoint.EndOfLine();
                    }
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc.ToString());
                    Debug.WriteLine("Formatting Spacing Around Comments failed, skipping");
                }
            }
        }
예제 #24
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private async void Execute(object sender, EventArgs e)
        {
            // Switch to UI thread
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken);

            // Get the Development Tools Extensibility service
            DTE dte = await ServiceProvider.GetServiceAsync(typeof(DTE)) as DTE;

            if (dte != null && dte.ActiveDocument != null)
            {
                // Operation succeeded
                bool success = false;

                // Get the text selection
                var selection = dte.ActiveDocument.Selection as TextSelection;
                if (selection is null)
                {
                    return;
                }

                // Find the start and end of the line
                EditPoint startPoint = selection.AnchorPoint.CreateEditPoint();
                EditPoint endPoint   = selection.AnchorPoint.CreateEditPoint();
                startPoint.StartOfLine();
                endPoint.EndOfLine();

                // Denote insertion location
                EditPoint insertPoint = startPoint.CreateEditPoint();

                // Get the line as a string
                string line = startPoint.GetText(endPoint);

                // Check if string is a function signature, if it is insert the header
                success = ValidateAndInsert(line, insertPoint);

                // If a function header wasn't inserted, check if the
                // function signature is spread across multiple lines
                if (!success && startOfFunction.Match(line).Success)
                {
                    // Count all parentheses on the starting line
                    int openingCount = line.Length - line.Replace("(", "").Length;
                    int closingCount = line.Length - line.Replace(")", "").Length;
                    int parenDiff    = openingCount - closingCount;

                    // Copy starting position
                    string multiLine = line;

                    // Move the active point to the anchor point
                    selection.MoveToPoint(selection.ActivePoint);
                    while (true)
                    {
                        // Move down the document concatenating the lines onto the starting line
                        selection.LineDown();
                        startPoint = selection.AnchorPoint.CreateEditPoint();
                        endPoint   = selection.AnchorPoint.CreateEditPoint();
                        startPoint.StartOfLine();
                        endPoint.EndOfLine();
                        string nextLine = startPoint.GetText(endPoint).Trim();
                        multiLine += nextLine;

                        // Count all parentheses on this line, and add them to the diff
                        openingCount = nextLine.Length - nextLine.Replace("(", "").Length;
                        closingCount = nextLine.Length - nextLine.Replace(")", "").Length;
                        parenDiff   += openingCount - closingCount;

                        // Exit if there are more closing parentheses than opening, or if there is a matching set
                        // This will cause the while loop to exit if an opening parenthesis is not detected within
                        // one line after the line we start on
                        if (parenDiff <= 0)
                        {
                            break;
                        }

                        // Exit if we reached the end of the document
                        if (endPoint.AtEndOfDocument)
                        {
                            break;
                        }
                    }

                    // Check if string is a function signature, if it is insert the header
                    success = ValidateAndInsert(multiLine, insertPoint);
                }

                // The selected line wasn't a function header, notify user in output
                if (!success)
                {
                    // Get the debug output pane
                    IVsOutputWindow     outputWindow = Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow;
                    Guid                paneGuid     = VSConstants.GUID_OutWindowDebugPane;
                    IVsOutputWindowPane pane;
                    outputWindow.GetPane(ref paneGuid, out pane);
                    if (pane is null)
                    {
                        return;
                    }

                    // Print the line that the was not a function signature, and then show the debug output
                    pane.OutputString(String.Format("The following line is not a function signature:\n\t{0}\n", line));
                    pane.Activate();
                }
            }
        }
예제 #25
0
        /// <summary>
        /// Inserts a blank line before the specified point except where adjacent to a brace.
        /// </summary>
        /// <param name="point">The point.</param>
        internal static void InsertBlankLineBeforePoint(EditPoint point)
        {
            if (point.Line <= 1) return;

            point.LineUp(1);
            point.StartOfLine();

            string text = point.GetLine();
            if (Regex.IsMatch(text, @"^\s*[^\s\{]")) // If it is not a scope boundary, insert newline.
            {
                point.EndOfLine();
                point.Insert(Environment.NewLine);
            }
        }
예제 #26
0
        //NOTE: should not check the file for existance...
        private bool GetGotoInfo(ref string actualfile, ref int actualline, ref int originalline, ref int gendepth, ref int filedepth)
        {
            //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;

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

                EditPoint  endfound = null;
                TextRanges found    = null;
                bool       result   = point.FindPattern("\\#line{.*}\\\"{.*}\\\"//\\[{.*}\\]", (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;

                    TextRange linematch     = found.Item(2);
                    string    linematchtext = linematch.StartPoint.GetText(linematch.EndPoint);

                    TextRange filematch     = found.Item(3);
                    string    filematchtext = filematch.StartPoint.GetText(filematch.EndPoint);

                    TextRange optionmatch = found.Item(4);
                    string    optionstext = optionmatch.StartPoint.GetText(optionmatch.EndPoint);

                    //parse the line directive
                    int    redirectedline = Convert.ToInt32(linematchtext);
                    string redirectedfile = filematchtext;

                    //parse the additional information
                    string[] options = optionstext.Split(',');

                    gendepth     = 0;
                    originalline = -1;
                    filedepth    = 0;

                    //first number: the depth of the generated path
                    if (options.Length > 0)
                    {
                        string generatedDepth = options[0];
                        gendepth = Convert.ToInt32(generatedDepth);
                    }

                    //second number: the depth of the file path (relative to the generated?)
                    if (options.Length > 1)
                    {
                        string fileDepth = options[1];
                        filedepth = Convert.ToInt32(fileDepth);
                    }

                    //third number: the original line number
                    if (options.Length > 2)
                    {
                        string originline = options[2];
                        originalline = Convert.ToInt32(originline);
                    }

                    if (offset == -1)
                    {
                        offset = 0;
                    }

                    if (offset >= 0)
                    {
                        string dots = "";

                        for (int i = 0; i < gendepth; i++)
                        {
                            dots += "..\\";
                        }

                        string myfile = StringUtility.RLeft(doc.FullName, "\\");

                        if (!System.IO.Path.IsPathRooted(redirectedfile))
                        {
                            actualfile = myfile + "\\" + dots + redirectedfile;
                        }
                        else
                        {
                            actualfile = redirectedfile;
                        }

                        actualfile = System.IO.Path.GetFullPath(actualfile);

                        actualline = redirectedline + offset;

                        return(true);
                    }
                }
            }

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

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

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

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

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

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

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

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

            //格式化指定范围内的文本
            value.StartPoint.CreateEditPoint().SmartFormat(value.EndPoint);
            return(true);
        }
예제 #28
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);
                    }
                }
            }
        }
예제 #29
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);
        }
예제 #30
0
파일: UpdateLogic.cs 프로젝트: waodng/VSIX
        /// <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();
            }
        }
예제 #31
0
        public static CodeElement GetCodeElement(DTE dte, vsCMElement[] searchScopes)
        {
            if (dte.ActiveDocument == null)
            {
                return(null);
            }
            if (dte.ActiveDocument.ProjectItem == null)
            {
                return(null);
            }
            if (dte.ActiveDocument.ProjectItem.FileCodeModel == null)
            {
                return(null);
            }
            TextSelection selection = (TextSelection)dte.ActiveWindow.Selection;

            if (selection == null || selection.ActivePoint == null)
            {
                return(null);
            }
            EditPoint    selPoint    = selection.ActivePoint.CreateEditPoint();
            CodeLanguage currentLang = CodeLanguage.CSharp;

            selPoint.StartOfLine();
            while (true)
            {
                string BlockText = selPoint.GetText(selPoint.LineLength).Trim();
                // *** Skip over any XML Doc comments and Attributes
                if (currentLang == CodeLanguage.CSharp && BlockText.StartsWith("/// ") ||
                    currentLang == CodeLanguage.CSharp && BlockText.StartsWith("[") ||
                    currentLang == CodeLanguage.VB && BlockText.StartsWith("''' ") ||
                    currentLang == CodeLanguage.VB && BlockText.StartsWith("<"))
                {
                    selPoint.LineDown(1);
                    selPoint.StartOfLine();
                }
                else
                {
                    break;
                }
            }

            // *** Make sure the cursor is placed inside of the definition always
            // *** Especially required for single line methods/fields/events etc.
            selPoint.EndOfLine();
            selPoint.CharLeft(1);              // Force into the text

            string xBlockText = selPoint.GetText(selPoint.LineLength).Trim();

            // get the element under the cursor
            CodeElement    element   = null;
            FileCodeModel2 CodeModel = dte.ActiveDocument.ProjectItem.FileCodeModel as FileCodeModel2;

            // *** Supported scopes - set up here in the right parsing order
            // *** from lowest level to highest level
            // *** NOTE: Must be adjusted to match any CodeElements supported

            foreach (vsCMElement scope in searchScopes)
            {
                try
                {
                    element = CodeModel.CodeElementFromPoint(selPoint, scope);
                    if (element != null)
                    {
                        break;                         // if no exception - break
                    }
                }
                catch {; }
            }
            if (element == null)
            {
                return(null);
            }
            return(element);
        }