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); } }
/// <summary> /// Adds the property. /// </summary> /// <param name="codeClass">The code class.</param> /// <param name="var">The var.</param> /// <returns></returns> public static CodeProperty AddProperty(CodeClass codeClass, CodeVariable var) { CodeProperty prop = null; try { prop = codeClass.AddProperty( FormatPropertyName(var.Name), FormatPropertyName(var.Name), var.Type.AsFullName, -1, vsCMAccess.vsCMAccessPublic, null); EditPoint editPoint = prop.Getter.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); //Delete return default(int); added by codeClass.AddProperty editPoint.Delete(editPoint.LineLength); editPoint.Indent(null, 4); editPoint.Insert(string.Format(CultureInfo.InvariantCulture, "return {0};", var.Name)); editPoint = prop.Setter.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); editPoint.Indent(null, 1); editPoint.Insert(string.Format(CultureInfo.InvariantCulture, "{0} = value;", var.Name)); editPoint.SmartFormat(editPoint); return(prop); } catch { //Property already exists return(null); } }
} // end of function - Process /*----------------------- InsertParamComment ----------------------------*/ /// <summary> /// /// </summary> /// <param name="ep"></param> protected virtual void InsertParamComment(EditPoint ep, int offset) { var f = Context.CodeElement as CodeFunction; Debug.WriteLine("CodeFunction.DocComment (initially): " + f.DocComment); if (f != null) { ep.InsertLine(""); ep.PadToColumn(offset); ep.InsertLine("/// <summary>"); ep.PadToColumn(offset); ep.InsertLine("/// "); ep.PadToColumn(offset); ep.Insert("/// </summary>"); foreach (var parm in f.Parameters) { CodeParameter codeParam = parm as CodeParameter; ep.InsertLine(""); ep.PadToColumn(offset); ep.Insert("/// <param name=\"" + codeParam.Name + "\"></param>"); } Debug.WriteLine("CodeFunction.DocComment: " + f.DocComment); } return; } // end of function - InsertParamComment
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> /// Inserts the routes. /// </summary> /// <param name="utilFolder">The util folder.</param> /// <param name="mvcCodeFilePath">The MVC code file path.</param> /// <param name="isConnectToQuickBookAlreadyThere">if set to <c>true</c> [is connect to quick book already there].</param> /// <param name="isLoginAlreadyThere">if set to <c>true</c> [is login already there].</param> /// <param name="isBlueDotMenyAlreadyThere">if set to <c>true</c> [is blue dot meny already there].</param> /// <param name="isDisconnetThere">if set to <c>true</c> [is disconnet there].</param> internal static void InsertRoutes(ProjectItem utilFolder, string mvcCodeFilePath, bool isConnectToQuickBookAlreadyThere, bool isLoginAlreadyThere, bool isBlueDotMenyAlreadyThere, bool isDisconnetThere, bool isLogoutThere) { ProjectItem fileProjectItem; if (Common.IsProjectItemExist(utilFolder.ProjectItems, "IntuitRegisterRoutes.cs", out fileProjectItem)) { CodeElement registerIntuitAnywhereRoutes = null; foreach (CodeElement codeElement in fileProjectItem.FileCodeModel.CodeElements) { if (codeElement.Kind == vsCMElement.vsCMElementClass) { foreach (CodeElement classChildElelement in codeElement.Children) { if (classChildElelement.Kind == vsCMElement.vsCMElementFunction && classChildElelement.Name == "RegisterIntuitAnywhereRoutes") { registerIntuitAnywhereRoutes = classChildElelement; break; } } } } if (registerIntuitAnywhereRoutes != null) { EditPoint ep = registerIntuitAnywhereRoutes.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); if (isConnectToQuickBookAlreadyThere == true) { string oauth = File.ReadAllText(mvcCodeFilePath + "oAuth.txt"); ep.Insert(oauth); } if (isLoginAlreadyThere) { string openId = File.ReadAllText(mvcCodeFilePath + "openID.txt"); ep.Insert(openId); } if (isBlueDotMenyAlreadyThere) { string blueDot = File.ReadAllText(mvcCodeFilePath + "blueDot.txt"); ep.Insert(blueDot); } if (isDisconnetThere) { string blueDot = File.ReadAllText(mvcCodeFilePath + "disconnect.txt"); ep.Insert(blueDot); } if (isLogoutThere) { string logout = File.ReadAllText(mvcCodeFilePath + "logout.txt"); ep.Insert(logout); } } } }
public override void UiBtnCommandAction(Object param) { if (string.IsNullOrWhiteSpace(UiCommandProppertyName)) { return; } if (SelectedCodeElement == null) { return; } if (SelectedCodeElement.CodeElementRef == null) { return; } CodeClass cc = SelectedCodeElement.CodeElementRef as CodeClass; if (SelectedViewModel != null) { SolutionProject prj = ComboItemsSourceProjects.Where(p => string.Equals(p.ProjectUniqueName, SelectedViewModel.RootNodeProjectName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (prj != null) { if (!string.Equals(SelectedProject.ProjectUniqueName, prj.ProjectUniqueName, StringComparison.OrdinalIgnoreCase)) { if (SelectedProject.ProjectRef.Object is VSProject) { (SelectedProject.ProjectRef.Object as VSProject).References.AddProject(prj.ProjectRef); SelectedProject.ProjectRef.Save(); } } } } //cc.AddProperty(UiCommandProppertyName , UiCommandProppertyName, "System.Data.Entity.DbSet<" + SelectedViewModelRootClass + ">", -1, vsCMAccess.vsCMAccessPublic, null); CodeProperty codeProperty = cc.AddProperty(UiCommandProppertyName, UiCommandProppertyName, "DbSet<" + SelectedViewModelRootClass + ">", -1, vsCMAccess.vsCMAccessPublic, null); EditPoint editPoint = codeProperty.Getter.StartPoint.CreateEditPoint(); editPoint.Delete(codeProperty.Getter.EndPoint); editPoint.Insert("get ;"); editPoint = codeProperty.Setter.StartPoint.CreateEditPoint(); editPoint.Delete(codeProperty.Setter.EndPoint); editPoint.Insert("set ;"); if (cc.ProjectItem != null) { if (cc.ProjectItem.IsDirty) { cc.ProjectItem.Save(); } } DoAnaliseDbContext(); }
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); }
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 void AddCodeSite(this CodeFunction codeFunction) { if (codeFunction.HasExpressionBody()) {//展开表达式主体为程序块主体,不做逆向处理 var addReturn = !(codeFunction.Type.TypeKind == vsCMTypeRef.vsCMTypeRefVoid || codeFunction.Parent is CodeProperty codeProperty && codeFunction.EqualsOffset(codeProperty.Setter)); if (codeFunction.HasBody()) { var epFind = codeFunction.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); var epEEnd = codeFunction.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); epFind.FindPattern("=>", (int)vsFindOptions.vsFindOptionsBackwards); epFind.Delete(2); epFind.Insert("{get{"); if (addReturn) { epFind.Insert("return "); } epEEnd.CharRight(); epEEnd.Insert("}}"); } else { var epFind = codeFunction.GetStartPoint().CreateEditPoint(); var epEEnd = codeFunction.GetEndPoint().CreateEditPoint(); epFind.FindPattern("=>"); epFind.Delete(2); epFind.Insert("{"); if (addReturn) { epFind.Insert("return "); } epEEnd.Insert("}"); } } if (codeFunction.ExistsCodeSite()) { codeFunction.DeleteCodeSite(); } EditPoint epStart = codeFunction.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); EditPoint epEnd = codeFunction.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); if (epStart.Line == epEnd.Line) { epEnd.Insert(Environment.NewLine); } epStart.Insert(codeFunction.CSEnterText()); if (Properties.Settings.Default.IncludeCatch) { epEnd.Insert(codeFunction.CSCatchText()); } epEnd.Insert(codeFunction.CSExitText()); //格式化指定范围内的文本 codeFunction.StartPoint.CreateEditPoint().SmartFormat(codeFunction.EndPoint.CreateEditPoint()); }
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> /// Sorts all using statements in ascending order, with System using statements on top. /// </summary> /// <param name="usingStatementsItems">List of using Statement codeItems</param> /// <param name="namespaceItems">List of namespace codeItems</param> internal void MoveUsingStatementsWithinNamespace(List <CodeItemUsingStatement> usingStatementsItems, List <CodeItemNamespace> namespaceItems) { if (namespaceItems.Count != 1) { //We return back as is, if multiple namespaces are found. return; } CodeItemNamespace theOnlyNamespace = namespaceItems.First(); EditPoint namespaceInsertCursor = theOnlyNamespace.StartPoint; // Setting the start point where we will start inserting using statements. namespaceInsertCursor.LineDown(); namespaceInsertCursor.CharRight(); namespaceInsertCursor.Insert(Environment.NewLine); //Sort the using code items in ascending string order, with system usings on top. usingStatementsItems.Sort((usingStatement1Item, usingStatement2Item) => { string textOfUsingStatement1 = usingStatement1Item.StartPoint.GetText(usingStatement1Item.EndPoint); string textOfUsingStatement2 = usingStatement2Item.StartPoint.GetText(usingStatement2Item.EndPoint); var referenceNameOfStatement1 = ExtractUsingStatementReferenceName(textOfUsingStatement1); var referenceNameOfStatement2 = ExtractUsingStatementReferenceName(textOfUsingStatement2); if (IsSystemReference(referenceNameOfStatement1) && !IsSystemReference(referenceNameOfStatement2)) { return(-1); } else if (!IsSystemReference(referenceNameOfStatement1) && IsSystemReference(referenceNameOfStatement2)) { return(1); } else { return(string.Compare(referenceNameOfStatement1, referenceNameOfStatement2)); } }); foreach (var usingStatement in usingStatementsItems) { var startPoint = usingStatement.StartPoint; var endPoint = usingStatement.EndPoint; string text = startPoint.GetText(usingStatement.EndPoint); startPoint.Delete(usingStatement.EndPoint); namespaceInsertCursor.Insert(text); namespaceInsertCursor.Indent(Count: 1); namespaceInsertCursor.Insert(Environment.NewLine); } }
private static async Task AddCommentsAsync(EditPoint objEditPt) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); objEditPt.StartOfLine(); var template = GetTemplate(); int index = 0; while (index < template.Count) { var line = string.Empty; if (!objEditPt.AtEndOfDocument) { line = objEditPt.GetText(objEditPt.LineLength); } if (!string.Equals(line, template[index])) { objEditPt.Insert($"{template[index]}{Environment.NewLine}"); //objEditPt.LineDown(); objEditPt.StartOfLine(); } else { objEditPt.LineDown(); } index++; } }
/// <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") && !projectItem.Name.EndsWith("Designer.cs")) { Debug.WriteLine("Moving Usings on: " + projectItem.Name); TextDocument objTextDoc = (TextDocument)ideWindow.Document.Object("TextDocument"); EditPoint startPoint = objTextDoc.StartPoint.CreateEditPoint(); string backupText = startPoint.GetText(objTextDoc.EndPoint); try { List <EditPoint> namespaceInsertionPoints = GetInsertionPoints(projectItem.FileCodeModel); if (namespaceInsertionPoints != null && namespaceInsertionPoints.Count > 0) { MoveUsingStatements(projectItem.FileCodeModel, namespaceInsertionPoints); } } catch (Exception exc) { Debug.WriteLine(exc.ToString()); Debug.WriteLine("Attempting to Revert..."); startPoint.Delete(objTextDoc.EndPoint); startPoint.Insert(backupText); Debug.WriteLine("Reverted."); } } }
public void SetContent(string content) { EditPoint start = _document.CreateEditPoint(_document.StartPoint); start.Delete(_document.EndPoint); start.Insert(content); }
public bool AddInterface(string intName, string intNotes, string intType, ref CodeInterface intObj) { Project prjObj = null; if (!prjCreate(intType, ref prjObj)) { return(false); } prjObj.ProjectItems.AddFromTemplate("C:\\Program Files\\Microsoft Visual Studio .NET\\VC#\\CSharpProjectItems\\NewCSharpFile.cs", intName + ".cs"); ProjectItem pi = prjObj.ProjectItems.Item(intName + ".cs"); CodeNamespace cn = pi.FileCodeModel.AddNamespace(intType, 0); TextPoint tp = cn.GetStartPoint(EnvDTE.vsCMPart.vsCMPartHeader); EditPoint ep = tp.CreateEditPoint(); ep.StartOfDocument(); ep.Insert("using System;\n"); CodeInterface ci = cn.AddInterface(intName, 0, null, EnvDTE.vsCMAccess.vsCMAccessPublic); ci.Comment = intNotes; appOb.Solution.SolutionBuild.Build(false); intObj = ci; return(true); }
/// <summary> /// Inserts the method at end of class. /// </summary> /// <param name="instance">The instance.</param> /// <param name="snippetPath">The snippet path.</param> public static void InsertMethod( this ProjectItem instance, string snippetPath) { CodeClass codeClass = instance.GetFirstClass(); if (codeClass != null) { CodeFunction codeFunction = codeClass.AddFunction("temp", vsCMFunction.vsCMFunctionFunction, vsCMTypeRef.vsCMTypeRefVoid, -1, vsCMAccess.vsCMAccessPublic, null); TextPoint startPoint = codeFunction.StartPoint; EditPoint editPoint = startPoint.CreateEditPoint(); codeClass.RemoveMember(codeFunction); editPoint.Insert("\n\n"); editPoint.InsertFromFile(snippetPath); } }
/// <summary> /// Inserts text at current cursor location or replaces the one that is currently selected. /// Undo will be used to name the action in Visual Studio's UndoRedo editor. /// </summary> public void InsertTextOrReplaceSelection(string undoContextName, string newText, bool detectStringCharsInSelection) { try { // open the undo-context to combine all the modifications of the source code into one: application.UndoContext.Open(undoContextName, true); if (IsSelected) { // paste into selected text: if (detectStringCharsInSelection) { InsertAsSelectionWithStringChars(newText); } else { selection.Insert(newText, (int)vsInsertFlags.vsInsertFlagsContainNewText); } } else { // just insert text: EditPoint.Insert(newText); } } finally { // close the undo-context, so all the changes will be threated as one: application.UndoContext.Close(); } }
/// <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("Removing Unnecessary Blank Lines: " + projectItem.Name); try { TextDocument objTextDoc = (TextDocument)ideWindow.Document.Object("TextDocument"); EditPoint objEditPoint = objTextDoc.CreateEditPoint(objTextDoc.StartPoint); while (!objEditPoint.AtEndOfDocument) { int secondFarthestLine = objEditPoint.Line + 2; if (secondFarthestLine > objTextDoc.EndPoint.Line) { secondFarthestLine = objEditPoint.Line + 1; } if (objEditPoint.GetLines(objEditPoint.Line, secondFarthestLine).Trim() == string.Empty) { objEditPoint.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); objEditPoint.Insert("\r\n"); } objEditPoint.LineDown(1); } } catch (Exception exc) { Debug.WriteLine(exc.ToString()); Debug.WriteLine("Removing Unnecessary Blank Lines failed, skipping"); } } }
/// <summary> /// 根据注释生成Display(Name = "注释" ) /// </summary> public static void GenerateDisplayNameByPropertyComment(DTE dte) { var clazz = Utility.GetCodeClass2(dte); if (clazz != null) { string functionContent = clazz.StartPoint.CreateEditPoint().GetText(clazz.EndPoint); var properties = Utility.GetCodeProperty2s(clazz); foreach (var p in properties) { //如果已经包含了Display特性,则不添加 var attrs = Utility.GetCodeAttribute2s(p); if (attrs.Any(t => t.Name == "Display")) { continue; } TextPoint pStart = p.StartPoint; string comment = Utility.GetCommentFromXMLString(p.DocComment); string displayText = "[Display(Name = \"" + comment + "\")]" + Environment.NewLine; EditPoint editPoint = pStart.CreateEditPoint(); editPoint.MoveToLineAndOffset(pStart.Line, pStart.DisplayColumn); editPoint.Insert(displayText); //格式化代码 editPoint.SmartFormat(pStart); } } }
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> /// Inserts the code line. /// </summary> /// <param name="instance">The instance.</param> /// <param name="code">The code.</param> public static void InsertCodeLine( this EditPoint instance, string code) { string insertCode = string.Format(" {0}{1}", code, Environment.NewLine); instance.Insert(insertCode); }
} // end of function - XmlFileCommentProvider /************************ Methods ****************************************/ /************************ Fields *****************************************/ /************************ Static *****************************************/ /*======================= PROTECTED =====================================*/ /************************ Events *****************************************/ /************************ Properties *************************************/ /************************ Construction ***********************************/ /************************ Methods ****************************************/ /*----------------------- ProcessFoot -----------------------------------*/ /// <summary> /// Writes footer comments into the document /// </summary> /// <param name="endEditPoint"></param> protected override void ProcessFoot(EditPoint endEditPoint) { InsertLineIntoDoc(endEditPoint, ""); endEditPoint.Insert( Context.State .MacroExpander .Expand("<!-- End of document - {FILENAME} -->")); } // end of function - ProcessFoot
/// <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); } } }
/// <summary> /// Pour éviter un bug de Visual studio TOUJOURS appeler AddPostCode AVANT addPreCode /// </summary> /// <param name="code">The code.</param> public void AddPostCode(string code) { TextPoint pt = _codeElement.GetEndPoint(vsCMPart.vsCMPartBody); EditPoint editPoint = pt.CreateEditPoint(); editPoint.Insert(code + "\r\n"); editPoint.SmartFormat(pt); }
public sealed override void Undo() { EditPoint ep = _codeMethod.StartPoint.CreateEditPoint(); ep.LineDown(1); ep.Delete(_codeMethod.EndPoint); ep.Insert("{\r\n}"); }
/// <summary> /// Inserts the code line. /// </summary> /// <param name="instance">The instance.</param> /// <param name="code">The code.</param> public static void InsertCodeLine( this EditPoint instance, string code) { string insertCode = string.Format(" {0}\r\n", code); instance.Insert(insertCode); }
/// <summary> /// 在指定位置插入文本从(0,0)开始 /// </summary> /// <param name="text"></param> /// <param name="line"></param> /// <param name="col"></param> public void InsertText(string text, int line, int col) { EditPoint editPoint = GetEditPoint(line, col); if (editPoint != null) { editPoint.Insert(text); } }
/// <summary> /// Inserts the element of a collection into the buffer /// at the specified index. /// </summary> /// <param name="start">Index of inserting.</param> /// <param name="lines">Code lines.</param> public void InsertRange(int start, IList <string> lines) { EditPoint ep = Document.CreateEditPoint(new LuaTextPoint(Document, 1, start + 1)); for (int i = 0; i < lines.Count; i++) { ep.Insert(lines[i] + "\r\n"); } }
private void Execute(object sender, EventArgs args) { ThreadHelper.ThrowIfNotOnUIThread(); var ide = _package.GetService(typeof(DTE)) as DTE2; Assumes.Present(ide); var document = ide?.ActiveDocument?.Object("TextDocument") as TextDocument; Assumes.Present(document); TextSelection selection = document.Selection; int originalPosition = selection.ActivePoint.AbsoluteCharOffset; // Make sure that we have selected lines that need to be sorted. if (selection.IsEmpty) { SelectInnerDefinition(selection, document); } var start = selection.TopPoint.CreateEditPoint(); var end = selection.BottomPoint.CreateEditPoint(); start.StartOfLine(); end.EndOfLine(); string selectedText = start.GetText(end); // Sort selected lines of text. string[] splitText = selectedText.Split( new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries); string sortedText = string.Join("\n", splitText.OrderBy(x => x)); // If the selected and sorted text do not match, delete and insert the replacement. if (!selectedText.Equals(sortedText, StringComparison.CurrentCulture)) { if (!ide.UndoContext.IsOpen) { ide.UndoContext.Open(Vsix.Name); } try { start.Delete(end); EditPoint insertCursor = start.CreateEditPoint(); insertCursor.Insert(sortedText); } finally { ide.UndoContext.Close(); } } selection.MoveToAbsoluteOffset(originalPosition); }
internal static void AddExpansionComment(CodeFunction codeFunction) { EditPoint edPoint = codeFunction.EndPoint.CreateEditPoint(); edPoint.LineUp(2); if (edPoint.GreaterThan(codeFunction.StartPoint)) { edPoint.Insert(GetComment(codeFunction.Language)); } }
internal static void InsertBlankLineAfterPoint(EditPoint point) { if (point.AtEndOfDocument) return; point.LineDown(1); point.StartOfLine(); string text = point.GetLines(point.Line, point.Line + 1); if (Regex.IsMatch(text, @"^\s*[^\s\}]")) { point.Insert(Environment.NewLine); } }
public void PasteCode(EditPoint objEditPt, string code, PasteOptions pasteOption) { switch (pasteOption) { case PasteOptions.Overwrite: objEditPt.Delete(code.Length); break; case PasteOptions.Append: objEditPt.EndOfDocument(); break; } objEditPt.Insert(code); }
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> /// 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); } }