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); } }
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); } } }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void Execute(object sender, EventArgs e) { // Verify the current thread is the UI thread. ThreadHelper.ThrowIfNotOnUIThread(); // This command will only work when there's an active document to examine. if (FormatCommentCommand.environment.ActiveDocument == null) { return; } // Get the selected text from the environment. TextSelection selection = FormatCommentCommand.environment.ActiveDocument.Selection as TextSelection; // Get the start end points (round down and up to the start of a line). EditPoint startPoint = selection.AnchorPoint.CreateEditPoint(); startPoint.StartOfLine(); // The initial endpoint is one line below the start. EditPoint endPoint = selection.ActivePoint.CreateEditPoint(); endPoint.StartOfLine(); endPoint.LineDown(1); // If nothing is selected, then figure out what needs to be formatted by the start point up and the end point down. As long as we // recognize a comment line we'll keep expanding the selection in both directions. if (selection.IsEmpty) { // Find the start of the block. while (!startPoint.AtStartOfDocument) { if (!FormatCommentCommand.IsCommentLine(startPoint)) { startPoint.LineDown(1); break; } startPoint.LineUp(1); } // Find the end of the block. while (!endPoint.AtEndOfDocument) { if (!FormatCommentCommand.IsCommentLine(endPoint)) { break; } endPoint.LineDown(1); } } // This will swap the old comment for the new right-margin justified and beautified comment. startPoint.ReplaceText( endPoint, FormatCommentCommand.FormatCommentstring(startPoint.GetText(endPoint)), (int)(vsEPReplaceTextOptions.vsEPReplaceTextNormalizeNewlines | vsEPReplaceTextOptions.vsEPReplaceTextTabsSpaces)); }
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); }
internal static void AddExpansionComment(CodeFunction codeFunction) { EditPoint edPoint = codeFunction.EndPoint.CreateEditPoint(); edPoint.LineUp(2); if (edPoint.GreaterThan(codeFunction.StartPoint)) { edPoint.Insert(GetComment(codeFunction.Language)); } }
public static void DeletePreviousLine(this EditPoint start) { start.LineUp(); start.StartOfLine(); var point = start.CreateEditPoint(); start.LineDown(); start.StartOfLine(); point.Delete(start); }
private Tuple <TextPoint, TextPoint> GetCodeRange() { // The C# and VB code models don't return comments with vsCMPartWholeWithAttributes // (even though some of the member types have Comment and DocComment properties // and the code model's RemoveMember will remove the comments). So we have to // grab any attached comment lines manually. TextPoint startPoint = this.element.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes); TextPoint endPoint = this.element.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes); Regex commentRegex; switch (this.language) { case Language.CSharp: // Look for lines starting with optional whitespace followed by //, /*, */, or *. commentRegex = new Regex(@"^\s*(//|/\*|\*/|\*)"); break; case Language.VB: // Look for lines starting with optional whitespace followed by '. commentRegex = new Regex(@"^\s*'"); break; default: throw new NotSupportedException("Unsupported language: " + this.language); } EditPoint startEdit = startPoint.CreateEditPoint(); startEdit.LineUp(); while (!startEdit.AtStartOfDocument && commentRegex.IsMatch(startEdit.GetLines(startEdit.Line, startEdit.Line + 1))) { startEdit.LineUp(); startEdit.StartOfLine(); } startEdit.LineDown(); startEdit.StartOfLine(); Tuple <TextPoint, TextPoint> result = Tuple.Create((TextPoint)startEdit, endPoint); return(result); }
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); } }
private void InsertGeneratedMethod(ProjectItem projectItem, string content) { projectItem.Open(Constants.vsViewKindCode); projectItem.Document.ActiveWindow.Activate(); TextDocument textDocument = (TextDocument)projectItem.Document.Object("TextDocument"); EditPoint editPoint = textDocument.EndPoint.CreateEditPoint(); editPoint.EndOfDocument(); editPoint.StartOfLine(); editPoint.LineUp(1); editPoint.Insert(content + "\n"); projectItem.Save(Helper.GetFilePath(projectItem)); }
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); } }
/// <summary> /// Helper method to modify commands.xml. /// </summary> /// <param name="projectItem"></param> private void ModifyCommandTable(ProjectItem projectItem) { Document activeDoc = projectItem.Document; projectItem.Open(); TextDocument editDoc = (TextDocument)activeDoc.Object("TextDocument"); EditPoint objEditPt = editDoc.CreateEditPoint(); EditPoint objMovePt = editDoc.EndPoint.CreateEditPoint(); objEditPt.StartOfDocument(); activeDoc.ReadOnly = false; objEditPt.FindPattern("</KeyinTable>"); objEditPt.Insert("\n"); objEditPt.LineUp(1); objEditPt.Indent(objEditPt, 1); objEditPt.Insert("<Keyword CommandWord=\"" + FunctionName + "\"></Keyword>"); objEditPt.LineDown(1); objEditPt.Indent(objEditPt, 2); objEditPt.FindPattern("</KeyinHandlers>"); objEditPt.Insert("\n"); objEditPt.LineUp(1); objEditPt.Indent(objEditPt, 1); objEditPt.Insert("<KeyinHandler Keyin=\"" + RootNamespace + " " + FunctionName + "\"\n"); objEditPt.Indent(objEditPt, 4); if (!IsVBProject) { objEditPt.Insert("Function=\"" + RootNamespace + ".KeyinCommands." + FunctionName + "Keyin\"/>"); } else { objEditPt.Insert("Function=\"" + RootNamespace + ".KeyinCommands." + FunctionName + "Keyin\"/>"); } }
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); }
/// <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); } }
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); }
private static string GetPadding(EditPoint startPoint, bool hasSelection) { string temp = startPoint.GetText(startPoint.LineLength); int tempLength = temp.Length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < tempLength; i++) { char ch = temp[i]; if (ch == ' ' || ch == '\t') { sb.Append(ch); } else { break; } } // If there was no selection and no padding was calculated // and the current temp is blank, then use the padding from // the line above it. string result = sb.ToString(); if (!hasSelection && result.Length == 0 && tempLength == 0) { EditPoint newStartPoint = startPoint.CreateEditPoint(); newStartPoint.LineUp(1); // Make sure we can still go up a line. if (newStartPoint.Line == startPoint.Line - 1) { result = GetPadding(newStartPoint, hasSelection); } } return(result); }
/// <summary> /// Generates the specified Source File in the received Project with the options /// provided and gets the Namespace ready to add code in it. /// </summary> /// <param name="targetProject">Project where the Source File is going to be placed.</param> /// <param name="targetProjectFolder">Project folder where the source file is going to be placed. /// Null indicates to place the source file as child of targetProject.</param> /// <param name="sourceFileName">Source File name to use.</param> /// <param name="sourceFileHeaderComment">Source File Header Comment (optional).</param> /// <param name="sourceNamespace">Namespace used in the Source File.</param> /// <param name="isServiceReady">Specifies if it is Service-Ready (serialization is going to be used).</param> /// <param name="sourceFileItem">(out parameter) Source File ProjectItem.</param> /// <returns></returns> public static CodeNamespace GenerateSourceAndGetNamespace(Project targetProject, ProjectItem targetProjectFolder, string sourceFileName, string sourceFileHeaderComment, string sourceNamespace, bool isServiceReady, out ProjectItem sourceFileItem) { // Validate source file name if (sourceFileName.EndsWith(Resources.CSharpFileExtension) == false) { sourceFileName += Resources.CSharpFileExtension; } // Validate source file header comment if (string.IsNullOrWhiteSpace(sourceFileHeaderComment) == false) { if (sourceFileHeaderComment.IndexOf("*/") >= 0) { throw new ApplicationException(Resources.Error_HeaderCommentInvalidChars); } } // ProjectItems collection where to place the source file ProjectItems projectItems = targetProject.ProjectItems; if (targetProjectFolder != null) { // Place inside received project folder projectItems = targetProjectFolder.ProjectItems; } // Properties collection of the target EnvDTE.Properties targetProperties = targetProject.Properties; if (targetProjectFolder != null) { targetProperties = targetProjectFolder.Properties; } // Source file sourceFileItem = null; #region If source file exists in the target, clear it and get the reference foreach (ProjectItem projItem in projectItems) { string projItemFileName = projItem.Properties.Item(Resources.ProjectItem_FileName).Value.ToString(); if (sourceFileName.ToLower() == projItemFileName.ToLower()) { // Source file already exists sourceFileItem = projItem; if (sourceFileItem.FileCodeModel.CodeElements != null && sourceFileItem.FileCodeModel.CodeElements.Count > 0) { // Clear source file CodeElement firstElement = sourceFileItem.FileCodeModel.CodeElements.Item(1); CodeElement lastElement = sourceFileItem.FileCodeModel.CodeElements.Item( sourceFileItem.FileCodeModel.CodeElements.Count); EditPoint startPoint = firstElement.StartPoint.CreateEditPoint(); EditPoint endPoint = lastElement.EndPoint.CreateEditPoint(); while (startPoint.AtStartOfDocument != true) { startPoint.LineUp(); } while (endPoint.AtEndOfDocument != true) { endPoint.LineDown(); } startPoint.Delete(endPoint); } break; } } #endregion #region If source file NOT exists in the target, create it and get the reference if (sourceFileItem == null) { // New source file, get target path string targetPath = targetProperties.Item(Resources.Properties_LocalPath).Value.ToString(); // Check if the new source file already exists in the file system (and it is not added to the solution) if (File.Exists(targetPath + sourceFileName)) { // Rename the existent source file string backupSourceFileName = (sourceFileName + Resources.BackupFileExtension); File.Move((targetPath + sourceFileName), (targetPath + backupSourceFileName)); // Add warning VisualStudioHelper.AddToErrorList(TaskErrorCategory.Warning, string.Format(Resources.Warning_SourceFileAlreadyExists, sourceFileName, backupSourceFileName), targetProject, sourceFileName, null, null); } // Add source file to target sourceFileItem = projectItems.AddFromTemplate(TemplateClass.FilePath, sourceFileName); } #endregion #region Generate imports var importList = new List <SourceCodeImport>(); importList.Add(new SourceCodeImport(Resources.NamespaceSystem)); importList.Add(new SourceCodeImport(Resources.NamespaceSystemCollectionsGeneric)); importList.Add(new SourceCodeImport(Resources.NamespaceSystemText)); if (isServiceReady) { importList.Add(new SourceCodeImport(Resources.NamespaceSystemRuntimeSerialization)); } importList = importList.OrderBy(d => d.ImportNamespace).ToList(); #endregion Generate imports // Add imports to the source code VisualStudioHelper.AddImportsToSourceCode(ref sourceFileItem, importList); // Get Source file code start EditPoint objEditPoint = sourceFileItem.FileCodeModel.CodeElements.Item(1).StartPoint.CreateEditPoint(); objEditPoint.StartOfDocument(); // Add header comment if (string.IsNullOrWhiteSpace(sourceFileHeaderComment) == false) { sourceFileHeaderComment = (Environment.NewLine + sourceFileHeaderComment + Environment.NewLine); objEditPoint.Insert( string.Format(Resources.CSharpCommentMultiline, sourceFileHeaderComment) + Environment.NewLine); } // Add EntitiesToDTOs signature string timestamp = DateTime.Now.ToString("yyyy/MM/dd - HH:mm:ss"); objEditPoint.Insert(string.Format(Resources.EntitiesToDTOsSignature, AssemblyHelper.Version, timestamp)); objEditPoint.Insert(Environment.NewLine); // Add blank line before source file namespace objEditPoint.EndOfDocument(); objEditPoint.Insert(Environment.NewLine); // Add namespace CodeNamespace objNamespace = sourceFileItem.FileCodeModel .AddNamespace(sourceNamespace, AppConstants.PLACE_AT_THE_END); return(objNamespace); }
/// <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); } }
/// <summary> /// Help method to modify KeyinCommands.cs or KeyinCommands.vb. /// </summary> /// <param name="projectItem"></param> /// <param name="keyinCommandFunctionCS"></param> /// <param name="keyinCommandFunctionvb"></param> private void ModifyKeyinsCommands(ProjectItem projectItem, string keyinCommandFunctionCS, string keyinCommandFunctionvb, string keyinCommandFunctionCPP) { Document activeDoc = projectItem.Document; if (activeDoc == null) { return; } ProjectItem activeDocumentProjectItem = activeDoc.ProjectItem; if (activeDocumentProjectItem == null) { return; } FileCodeModel fileCodeModel = activeDocumentProjectItem.FileCodeModel; if (fileCodeModel == null) { return; } CodeElements codeElements = fileCodeModel.CodeElements; CodeClass codeClass = null; // look for the namespace in the active document CodeNamespace codeNamespace = null; foreach (CodeElement codeElement in codeElements) { if (codeElement.Kind == vsCMElement.vsCMElementNamespace) { codeNamespace = codeElement as CodeNamespace; break; } } if (codeNamespace == null) { if (IsVBProject) { codeElements = fileCodeModel.CodeElements; } else { return; } } else { codeElements = codeNamespace.Members; } if (codeElements == null) { return; } // look for the first class foreach (CodeElement codeElement in codeElements) { if (codeElement.Kind == vsCMElement.vsCMElementClass) { codeClass = codeElement as CodeClass; break; } } if (codeClass == null) { return; } if (IsCSProject) { CodeFunction codeFunction = codeClass.AddFunction(FunctionName + "Keyin", vsCMFunction.vsCMFunctionFunction, vsCMTypeRef.vsCMTypeRefVoid, -1, vsCMAccess.vsCMAccessPublic); codeFunction.AddParameter("unparsed", vsCMTypeRef.vsCMTypeRefString, -1); TextPoint textPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartBody); EditPoint editPoint = textPoint.CreateEditPoint(); EditPoint objMovePt = textPoint.CreateEditPoint(); EditPoint UtilEditPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartHeader).CreateEditPoint(); UtilEditPoint.ReplaceText(6, "public static", 0); editPoint.Insert ( keyinCommandFunctionCS ); editPoint.StartOfDocument(); objMovePt.EndOfDocument(); editPoint.SmartFormat(objMovePt); } else if (IsVBProject) { CodeFunction codeFunction = codeClass.AddFunction(FunctionName + "Keyin", vsCMFunction.vsCMFunctionSub, vsCMTypeRef.vsCMTypeRefVoid, -1, vsCMAccess.vsCMAccessPublic); codeFunction.AddParameter("unparsed", vsCMTypeRef.vsCMTypeRefString, -1); TextPoint textPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartBody); EditPoint editPoint = textPoint.CreateEditPoint(); EditPoint objMovePt = textPoint.CreateEditPoint(); EditPoint UtilEditPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartHeader).CreateEditPoint(); UtilEditPoint.ReplaceText(6, "Public Shared", 0); editPoint.Insert ( keyinCommandFunctionvb ); editPoint.StartOfDocument(); objMovePt.EndOfDocument(); editPoint.SmartFormat(objMovePt); } else if (IsVCProject) { TextDocument editDoc = (TextDocument)activeDoc.Object("TextDocument"); EditPoint objEditPt = editDoc.CreateEditPoint(); EditPoint objMovePt = editDoc.EndPoint.CreateEditPoint(); objEditPt.StartOfDocument(); activeDoc.ReadOnly = false; if (objEditPt.FindPattern("#include")) { objEditPt.LineDown(1); objEditPt.Insert("#include \"" + FunctionName + ".h\"\n"); } else if ((objEditPt.FindPattern("#using"))) { objEditPt.LineUp(1); objEditPt.Insert("#include \"" + FunctionName + ".h\"\n"); } else { objEditPt.FindPattern("namespace"); objEditPt.LineUp(1); objEditPt.Insert("#include \"" + FunctionName + ".h\"\n"); } CodeFunction codeFunction = codeClass.AddFunction(FunctionName + "Keyin", vsCMFunction.vsCMFunctionFunction, vsCMTypeRef.vsCMTypeRefVoid, -1, vsCMAccess.vsCMAccessPublic); codeFunction.AddParameter("unparsed", "System::String^", -1); TextPoint textPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartBody); EditPoint editPoint = textPoint.CreateEditPoint(); objMovePt = textPoint.CreateEditPoint(); EditPoint UtilEditPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartHeader).CreateEditPoint(); UtilEditPoint.ReplaceText(4, "public:static", 0); editPoint.Insert(keyinCommandFunctionCPP); if (objEditPt.FindPattern("throw gcnew System::NotImplementedException();")) { editPoint.Delete(52); } editPoint.StartOfDocument(); objMovePt.EndOfDocument(); editPoint.SmartFormat(objMovePt); } }
/// <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> /// Sorts functions within a class. /// </summary> /// <param name="codeElement">The code element that represents the class.</param> private void SortFunctionsWithinClass(CodeElement codeElement) { EditPoint classPoint = codeElement.StartPoint.CreateEditPoint(); TextRanges trs = null; string classBackup = classPoint.GetText(codeElement.EndPoint); try { if (classPoint.FindPattern("{", (int)vsFindOptions.vsFindOptionsMatchCase, ref classPoint, ref trs)) { classPoint.Insert("\r\n"); List <CodeBlock> blocks = new List <CodeBlock>(); Array accessLevels = Enum.GetValues(typeof(vsCMAccess)); for (int i = 1; i <= codeElement.Children.Count; i++) { CodeElement element = codeElement.Children.Item(i); if (element.Kind != vsCMElement.vsCMElementAttribute) { EditPoint startBlock = element.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes).CreateEditPoint(); EditPoint newStartPoint = startBlock.CreateEditPoint(); CodeBlock block = EvaluateBlock(codeElement, element, ref newStartPoint); if (block != null) { blocks.Add(block); newStartPoint.Delete(element.EndPoint); newStartPoint.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); i--; } } } blocks.Sort(delegate(CodeBlock c1, CodeBlock c2) { int comparison = 0; if (c1.Placement != c2.Placement) { comparison = c1.Placement.CompareTo(c2.Placement); } else if (c1.Access != c2.Access) { comparison = c1.Access.CompareTo(c2.Access); } else if (c1.Name != c2.Name) { comparison = c1.Name.CompareTo(c2.Name); } else { comparison = c1.Weight.CompareTo(c2.Weight); } return(comparison); }); classPoint.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); classPoint.Insert("\r\n"); for (int i = 0; i < blocks.Count; i++) { classPoint.Insert(blocks[i].Body + "\r\n\r\n"); } classPoint.LineUp(1); classPoint.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); for (int i = 1; i <= codeElement.Children.Count; i++) { CodeElement element = codeElement.Children.Item(i); if (element.Kind == vsCMElement.vsCMElementClass || element.Kind == vsCMElement.vsCMElementInterface || element.Kind == vsCMElement.vsCMElementStruct) { SortFunctionsWithinClass(element); } } } } catch (Exception exc) { Debug.WriteLine(exc.ToString()); EditPoint startBackup = codeElement.StartPoint.CreateEditPoint(); startBackup.Delete(codeElement.EndPoint); startBackup.Insert(classBackup); Debug.WriteLine("-- Class Reverted --"); } }
protected int ShowEventHandler(string document, string codeBehind, string codeBehindFile, string className, string objectTypeName, string eventName, string eventHandlerName) { var projectItem = GetProjectItem(document, codeBehind, codeBehindFile); var binder = GetBinder(projectItem); if (binder == null) { return(NativeMethods.E_FAIL); } projectItem.Open(EnvDTE.Constants.vsViewKindCode); var function = binder.FindEventHandler(className, objectTypeName, eventName, eventHandlerName); if (function != null) { bool prevLineIsEmpty = true; EditPoint point = function.EndPoint.CreateEditPoint(); point.LineUp(1); string lines = point.GetLines(point.Line, (int)(point.Line + 1)); for (int i = 0; i < lines.Length; i++) { if (!char.IsWhiteSpace(lines[i])) { prevLineIsEmpty = false; break; } } Document document2 = projectItem.Document; if (document2 != null) { Window activeWindow = document2.ActiveWindow; if (activeWindow != null) { TextSelection selection = activeWindow.Selection as TextSelection; if (selection != null) { selection.MoveToPoint(function.EndPoint, false); if (prevLineIsEmpty) { selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false); int virtualCharOffset = selection.AnchorPoint.VirtualCharOffset; selection.LineUp(false, 1); if (selection.AnchorPoint.VirtualCharOffset <= virtualCharOffset) { int indentSize = 4; TextDocument document3 = document2 as TextDocument; if (document3 != null) { indentSize = document3.IndentSize; } selection.MoveToLineAndOffset(selection.AnchorPoint.Line, (int)(virtualCharOffset + indentSize), false); } } else { selection.LineUp(false, 1); //selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn, false); selection.EndOfLine(false); } } } } } return(NativeMethods.S_OK); }
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); }