private static bool ProcessClassGuidAttribute(CodeEditPoint editorEditPoint, string guid) { CodeFunction currentFunction = editorEditPoint.GetCurrentCodeElement <CodeFunction>(vsCMElement.vsCMElementFunction); // if inside the function, then applying of an attribute to class/struct is prohibited: if (currentFunction != null) { return(false); } // if the current place is inside string characters: "" // then don't jump to the class definition: EditPoint startString = editorEditPoint.EditPoint.CreateEditPoint(); startString.CharLeft(1); string s = startString.GetText(2); if (s == "\"\"" || editorEditPoint.IsSelected) { return(false); } CodeClass currentClass = editorEditPoint.GetCurrentCodeElement <CodeClass>(vsCMElement.vsCMElementClass); CodeStruct currentStruct = editorEditPoint.GetCurrentCodeElement <CodeStruct>(vsCMElement.vsCMElementStruct); EditPoint start = null; CodeModelLanguages language = CodeModelLanguages.Unknown; // find the start location of current class: if (currentClass != null) { start = currentClass.GetStartPoint(vsCMPart.vsCMPartHeader).CreateEditPoint(); language = CodeHelper.GetCodeLanguage(currentClass.Language); } // find the start location of current structure: if (currentStruct != null) { start = currentStruct.GetStartPoint(vsCMPart.vsCMPartHeader).CreateEditPoint(); language = CodeHelper.GetCodeLanguage(currentStruct.Language); } // append attributes at the 'start' location: if (start != null) { string sourceCodeSnippet = CodeHelper.GenerateFromAttribute(language, VariableHelper.GetGuidAttribute(guid)); if (language == CodeModelLanguages.VisualBasic) { sourceCodeSnippet += Environment.NewLine; } start.ReplaceText(start, sourceCodeSnippet, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat); return(true); } // nothing special found... just insert the Guid string... return(false); }
public override void Execute() { foreach (CodeElement element in CodeClass.Members) { if (element is CodeVariable && element.Name == FieldName) { return; } } switch (base.CodeClass.Language) { case CodeModelLanguageConstants.vsCMLanguageCSharp: base.Execute(); break; case CodeModelLanguageConstants.vsCMLanguageVB: base.Field = base.CodeClass.AddVariable(FieldName, FieldType, System.Reflection.Missing.Value, vsCMAccess.vsCMAccessPublic, System.Reflection.Missing.Value); break; } if (_fieldValue != null) { Field.IsConstant = true; EditPoint ep = Field.EndPoint.CreateEditPoint(); if (base.CodeClass.Language == CodeModelLanguageConstants.vsCMLanguageCSharp) { ep.CharLeft(1); } ep.Insert(String.Format(" = \"{0}\"", _fieldValue)); } }
/// <summary> /// Moves cursor/editpoint exactly. /// </summary> /// <param name="point"></param> /// <param name="count"></param> /// <param name="direction"></param> /// <returns></returns> /// <remarks> /// DTE functions that moves editpoint counts newline as single character, /// since we get the character count from regular regex not the DTE find, the char count is slightly off /// </remarks> public static EditPoint CharMoveExact(EditPoint point, int count, int direction) { while (count > 0) { if (direction > 1) { direction = 1; } else { if (direction < 0) { direction = -1; } } if (point.GetText(direction).Length == 2) { count--; } if (direction < 0) { point.CharLeft(); } else { point.CharRight(); } count--; } return point; }
/// <summary> /// Moves cursor/editpoint exactly. /// </summary> /// <param name="point"></param> /// <param name="count"></param> /// <param name="direction"></param> /// <returns></returns> /// <remarks> /// DTE functions that moves editpoint counts newline as single character, /// since we get the character count from regular regex not the DTE find, the char count is slightly off /// </remarks> public static EditPoint CharMoveExact(EditPoint point, int count, int direction) { while (count > 0) { //Normalize if (direction > 1) { direction = 1; } else if (direction < 0) { direction = -1; } //If we are asking 1 and getting 2, its a newline. This is a quirk/feature of EnvDTE where all its functions treats newline as single character if (point.GetText(direction).Length == 2) { count -= 1; } if (direction < 0) { point.CharLeft(1); } else { point.CharRight(1); } count -= 1; } return point; }
/// <summary> /// Moves cursor/editpoint exactly. /// </summary> /// <param name="point"></param> /// <param name="count"></param> /// <param name="direction"></param> /// <returns></returns> /// <remarks> /// DTE functions that moves editpoint counts newline as single character, /// since we get the character count from regular regex not the DTE find, the char count is slightly off /// </remarks> public static EditPoint CharMoveExact(EditPoint point, int count, int direction) { while (count > 0) { //Normalize if (direction > 1) { direction = 1; } else if (direction < 0) { direction = -1; } //If we are asking 1 and getting 2, its a newline. This is a quirk/feature of EnvDTE where all its functions treats newline as single character if (point.GetText(direction).Length == 2) { count -= 1; } if (direction < 0) { point.CharLeft(); } else { point.CharRight(); } count -= 1; } return(point); }
private void AddInTheEnd(CodeElement codeElement, string content) { EditPoint editPoint = codeElement.EndPoint.CreateEditPoint(); editPoint.CharLeft(1); editPoint.Insert("\r\n\r\n"); editPoint.LineUp(1); editPoint.Insert(content); }
private void AddInTheEnd(CodeFunction codeElement, string content) { if (codeElement != null) { EditPoint editPoint = codeElement.EndPoint.CreateEditPoint(); editPoint.CharLeft(GetMethodEndString().Length); editPoint.Insert("\r\n\r\n"); editPoint.LineUp(1); editPoint.Insert(content); } }
/// <summary> /// Removes whitespace immediately inside a block /// </summary> /// <param name="element">The current code element</param> private void RemoveInternalBlockPadding(CodeElement element) { EditPoint start = element.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); EditPoint end = element.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); end.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); end.CharLeft(1); start.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); end.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); }
private void HandleExpandDelegateTemplate(TextSelection selection) { if (!_options.UseDelegateInference) { return; } var editPoint = selection.TopPoint.CreateEditPoint(); editPoint.StartOfLine(); string previousLine = editPoint.GetText(selection.TopPoint); Match matchExpandingEventHandler = Regex.Match(previousLine, @"\.\w+\s*\+=\s*new\s+[a-zA-Z0-9_\.]+\s*\((\w*)$"); _isExpandingCandidate = matchExpandingEventHandler.Success; if (_isExpandingCandidate) { StartUndoOperation(); _delegateStart = selection.TopPoint.CreateEditPoint(); _delegateStart.CharLeft(matchExpandingEventHandler.Groups[1].Value.Length); //We are now right after the ( } }
/// <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()); }
private void HandleExpandDelegateTemplate(TextSelection selection) { if (!_options.UseDelegateInference) { return; } var editPoint = selection.TopPoint.CreateEditPoint(); editPoint.StartOfLine(); string previousLine = editPoint.GetText(selection.TopPoint); Match matchExpandingEventHandler = Regex.Match(previousLine, @"\.\w+\s*\+=\s*new\s+[a-zA-Z0-9_\.]+\s*\((\w*)$"); _isExpandingCandidate = matchExpandingEventHandler.Success; if (_isExpandingCandidate) { StartUndoOperation(); _delegateStart = selection.TopPoint.CreateEditPoint(); _delegateStart.CharLeft(matchExpandingEventHandler.Groups[1].Value.Length); //We are now right after the ( } }
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) { } }
/// <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"); } } }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void MenuItemCallback(object sender, EventArgs e) { //string message = string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.GetType().FullName); //string title = "Custom Watch"; //// Show a message box to prove we were here //VsShellUtilities.ShowMessageBox( // this.ServiceProvider, // message, // title, // OLEMSGICON.OLEMSGICON_INFO, // OLEMSGBUTTON.OLEMSGBUTTON_OK, // OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); if (m_dte == null) { return; } Document doc = m_dte.ActiveDocument; if (doc == null) { return; } if (doc.Type != "Text") { return; } //select text TextSelection selection = (TextSelection)doc.Selection; string strSelectText = selection.Text; strSelectText.Trim(); // invalid selection if (strSelectText.Length == 0) { EditPoint pt = (EditPoint)selection.ActivePoint.CreateEditPoint(); EditPoint ptLeft = pt.CreateEditPoint(); EditPoint ptRight = pt.CreateEditPoint(); for (ptLeft.CharLeft(); !ptLeft.AtStartOfLine; ptLeft.CharLeft()) { if (!IsValidCharOfName(ptLeft.GetText(pt)[0])) { break; } } ptLeft.CharRight(); for (ptRight.CharRight(); !ptRight.AtEndOfLine; ptRight.CharRight()) { var strText = ptRight.GetText(pt); if (!IsValidCharOfName(strText[strText.Length - 1])) { break; } } ptRight.CharLeft(); strSelectText = ptLeft.GetText(ptRight); if (!IsValidStartCharOfName(strSelectText[0])) { return; } } if (strSelectText.Length == 0) { return; } if (m_watchPane != null) { m_watchPane.Clear(); } string strRetValue = ""; string strErrorMsg = ""; if (m_procEvent.CalcExpression(strSelectText, out strErrorMsg, out strRetValue)) { if (strRetValue != "" && strRetValue.IndexOf("Error") == -1 && strRetValue.IndexOf("error") == -1) { Clipboard.SetText(strRetValue); OutputStr("(Inform: Already copy the data below to clipborad)"); } OutputStr(strRetValue); OutputStr("\n"); } else { OutputStr("Error Occur: " + strErrorMsg + "\n"); } }
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); }