private bool Evaluate(out object newValue) { newValue = null; CodeClass currentDSAClass = ExpressionEvaluationHelper.EvaluateExpression((IDictionaryService)GetService(typeof(IDictionaryService)), currentDSAClassExpression) as CodeClass; if (currentDSAClass != null) { CodeProperty onlineProxyTypeProperty = CodeModelHelper.GetProperty(currentDSAClass, "OnlineProxyType", vsCMAccess.vsCMAccessPublic); if (onlineProxyTypeProperty != null) { CodeFunction getMethod = onlineProxyTypeProperty.Getter; EditPoint edit = getMethod.StartPoint.CreateEditPoint(); EditPoint endpoint = null; TextRanges tags = null; if (edit.FindPattern(@"(typeof|GetType)\((.+)\)", (int)vsFindOptions.vsFindOptionsRegularExpression, ref endpoint, ref tags)) { EditPoint begin = edit.CreateEditPoint(); string proxyTypeName = begin.GetText(endpoint); Regex extractRegex = new Regex(@"(typeof|GetType)\((.+)\)"); if (extractRegex.IsMatch(proxyTypeName) && extractRegex.Match(proxyTypeName).Groups.Count == 3) { proxyTypeName = extractRegex.Match(proxyTypeName).Groups[2].Value; newValue = proxyTypeName; return(true); } } } } return(false); }
/// <summary>Finds all instances of a text in the document object for the provided item.</summary> /// <param name="item">Project item to search texts</param> /// <param name="text">Text to look for</param> /// <returns>A collection of BaseHardCodedString objects that references to text</returns> public static ReadOnlyCollection <BaseHardCodedString> FindAllInstancesInDocument(ProjectItem item, string text) { TextDocument doc = GetDocumentForItem(item); Collection <BaseHardCodedString> instances = new Collection <BaseHardCodedString>(); EditPoint start = doc.StartPoint.CreateEditPoint(); start.MoveToAbsoluteOffset(1); EditPoint end = null; // Unused object for FindPattern method. TextRanges ranges = null; System.Collections.IEnumerator comments = null; Match currentMatch = null; BaseHardCodedString instance = BaseHardCodedString.GetHardCodedString(item.Document); while (start.FindPattern(text, (int)(vsFindOptions.vsFindOptionsMatchCase), ref end, ref ranges)) { if (instance != null) { if (comments == null) { comments = instance.FindCommentsInDocument(item).GetEnumerator(); } bool inComment = false; while (currentMatch != null || (comments.MoveNext())) { currentMatch = (Match)(comments.Current); // If this match appears earlier then current text skip if (currentMatch.Index + currentMatch.Length <= (start.AbsoluteCharOffset - 1)) { currentMatch = null; } // If this comment is later then current text stop processing comments else if (currentMatch.Index >= (end.AbsoluteCharOffset - 1)) { break; } // At this point current text must be part of a comment block else { inComment = true; break; } } if (!inComment) { instance = instance.CreateInstance(item, start.AbsoluteCharOffset - 1, end.AbsoluteCharOffset - 1); instances.Add(instance); } } start = end; } return(new ReadOnlyCollection <BaseHardCodedString>(instances)); }
private EditPoint FindFirstMatch(EditPoint startPoint, string pattern) { EditPoint endPoint = null; TextRanges tags = null; if (startPoint != null && startPoint.FindPattern(pattern, (int)(vsFindOptions.vsFindOptionsRegularExpression | vsFindOptions.vsFindOptionsMatchInHiddenText), ref endPoint, ref tags)) { return(startPoint.CreateEditPoint()); } return(null); }
/// <summary> /// Gets the code block for a given element, this includes any comments that come before the element, /// but after the previous element. /// </summary> /// <param name="parent">The current block's parent.</param> /// <param name="block">The current block.</param> /// <param name="newStartPoint">The starting point used to capture the beginning of the element.</param> /// <returns>The text of a given block.</returns> private string GetCodeBlockText(CodeElement parent, CodeElement block, out EditPoint newStartPoint) { EditPoint blockStartPoint = block.StartPoint.CreateEditPoint(); EditPoint previousblockEndPoint = blockStartPoint.CreateEditPoint(); EditPoint editPoint = blockStartPoint.CreateEditPoint(); TextRanges trs = null; if (editPoint.FindPattern("}", (int)vsFindOptions.vsFindOptionsBackwards, ref previousblockEndPoint, ref trs)) { if (previousblockEndPoint.GreaterThan(parent.StartPoint)) { blockStartPoint = previousblockEndPoint; } else { previousblockEndPoint = blockStartPoint.CreateEditPoint(); editPoint = blockStartPoint.CreateEditPoint(); if (editPoint.FindPattern("{", (int)vsFindOptions.vsFindOptionsBackwards, ref previousblockEndPoint, ref trs)) { if (previousblockEndPoint.GreaterThan(parent.StartPoint)) { blockStartPoint = previousblockEndPoint; } } } } else { if (editPoint.FindPattern("{", (int)vsFindOptions.vsFindOptionsBackwards, ref previousblockEndPoint, ref trs)) { if (previousblockEndPoint.GreaterThan(parent.StartPoint)) { blockStartPoint = previousblockEndPoint; } } } newStartPoint = blockStartPoint.CreateEditPoint(); return(blockStartPoint.GetText(block.EndPoint).Trim()); }
/// <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\"/>"); } }
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); }
/// <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); }
public void FindBracket() { EditPoint EndPoint = null; TextRanges dummy = null; EditPoint StartPoint = Start.CreateEditPoint(); StartPoint.LineDown(); //FindPattern 不能指定结束位置 while (StartPoint.FindPattern(MaximumBracketPattern, StandardFindOptions, ref EndPoint, ref dummy)) { //所以,需要 判读匹配的开始位置是否在,被包含的区间外 if (StartPoint.Line >= End.Line) { break;//在外面,则跳出,转入数组的下一个 } if (StartPoint != null && EndPoint != null) { IndentSquareBracket Child = new IndentSquareBracket(StartPoint, EndPoint, this); StartPoint.StartOfLine(); int LineIndentCount; //当父节区间为空时,取父区间的缩进,否则在父区间的基础上+1,逐级实现缩进 if (Parent == null) { string LineText = StartPoint.GetText(StartPoint.LineLength); string textTemp = LineText.TrimStart('\t'); LineIndentCount = LineText.Length - textTemp.Length;//获取当前的缩进深度 } else { LineIndentCount = IndentCount + 1; } Child.IndentCount = LineIndentCount; Children.Add(Child); //子Bracket递归查找 Child.FindBracket(); } //再从区间的结束位置向后在下一个最大的包含区间 StartPoint = EndPoint; } }
/// <summary> /// 查找代码 /// </summary> /// <param name="win"></param> /// <param name="pattern"></param> /// <returns></returns> public static string FindCode(Window win, string pattern) { var doc = (TextDocument)win.Document.Object("TextDocument"); EditPoint editPoint = doc.StartPoint.CreateEditPoint(); EditPoint endPoint = null; TextRanges tags = null; bool find = editPoint.FindPattern(pattern, (int)(vsFindOptions.vsFindOptionsFromStart | vsFindOptions.vsFindOptionsRegularExpression), ref endPoint, ref tags); if (find && tags != null) { return(editPoint.GetText(endPoint)); } return(""); }
private VCCodeFunction GetMethodFromFilePos(CodeElement codeElem, int lineNum, int linePos) { if (codeElem.Kind == vsCMElement.vsCMElementFunction) { VCCodeFunction targetFunc = codeElem as VCCodeFunction; if (targetFunc != null) { TextPoint startFuncBody = targetFunc.StartPointOf[vsCMPart.vsCMPartBody, vsCMWhere.vsCMWhereDefinition]; TextPoint endFuncBody = targetFunc.EndPointOf[vsCMPart.vsCMPartBody, vsCMWhere.vsCMWhereDefinition]; EditPoint startPnt = startFuncBody.CreateEditPoint(); EditPoint endPnt = endFuncBody.CreateEditPoint(); startPnt.FindPattern("{", (int)vsFindOptions.vsFindOptionsBackwards); endPnt.FindPattern("}"); if ((lineNum > startPnt.Line && lineNum < endPnt.Line) || (lineNum == startPnt.Line && linePos >= startPnt.LineCharOffset) || (lineNum == endPnt.Line && linePos <= endPnt.LineCharOffset)) { return(targetFunc); } } //if ((lineNum > codeElem.StartPoint.Line && lineNum < codeElem.EndPoint.Line) || // (lineNum == codeElem.StartPoint.Line && linePos >= codeElem.StartPoint.LineCharOffset) || // (lineNum == codeElem.EndPoint.Line && linePos <= codeElem.EndPoint.LineCharOffset)) //{ // VCCodeFunction targetFunc = (VCCodeFunction)codeElem; // if (targetFunc != null) // return targetFunc; //} } else { foreach (CodeElement classCodeElem in codeElem.Children) { VCCodeFunction theMethod = GetMethodFromFilePos(classCodeElem, lineNum, linePos); if (theMethod != null) { return(theMethod); } } } return(null); }
private static void MoveCodeBlock(CodeElement parent, CodeElement block, EditPoint pastePoint) { EditPoint blockStartPoint = block.StartPoint.CreateEditPoint(); EditPoint previousblockEndPoint = blockStartPoint.CreateEditPoint(); EditPoint editPoint = blockStartPoint.CreateEditPoint(); TextRanges trs = null; if (editPoint.FindPattern("}", (int)vsFindOptions.vsFindOptionsBackwards, ref previousblockEndPoint, ref trs)) { if (previousblockEndPoint.GreaterThan(parent.StartPoint)) { blockStartPoint = previousblockEndPoint; } } blockStartPoint.Cut(block.EndPoint, false); pastePoint.Paste(); pastePoint.Insert("\r\n\r\n"); }
/// <summary> /// 匹配方法 /// </summary> /// <returns></returns> private bool toFunc(Window win) { // 匹配方法定义代码(vs的正则表达式有点特殊) string pattern = @":a_ \.\<\>\[\]\t\n"; switch (_serviceFunc.ParamNum) { // -1不匹配参数个数 case -1: pattern = string.Format(@"public :c+ {0}\([^\)]*\)", _serviceFunc.Func); break; case 0: pattern = string.Format(@"public :c+ {0}\(\)", _serviceFunc.Func); break; case 1: pattern = string.Format(@"public :c+ {1}\([{0}]+\)", pattern, _serviceFunc.Func); break; default: pattern = string.Format(@"public :c+ {1}\(([{0}]+,)^{2}[{0}]+\)", pattern, _serviceFunc.Func, _serviceFunc.ParamNum - 1); break; } var doc = (TextDocument)win.Document.Object("TextDocument"); EditPoint editPoint = doc.StartPoint.CreateEditPoint(); EditPoint endPoint = null; TextRanges tags = null; bool find = editPoint.FindPattern(pattern, (int)(vsFindOptions.vsFindOptionsFromStart | vsFindOptions.vsFindOptionsRegularExpression), ref endPoint, ref tags); if (find && tags != null) { doc.Selection.MoveToPoint(endPoint, false); doc.Selection.MoveToPoint(editPoint, true); } return(find); }
/// <summary> /// Gets a list of insertion points. /// </summary> /// <param name="fileCodeModel">The code model to search.</param> /// <returns>A list of insertion points.</returns> private List <EditPoint> GetInsertionPoints(FileCodeModel fileCodeModel) { List <EditPoint> namespacePoints = new List <EditPoint>(); for (int i = 1; i <= fileCodeModel.CodeElements.Count; i++) { if (fileCodeModel.CodeElements.Item(i).Kind == vsCMElement.vsCMElementNamespace) { EditPoint namespacePoint = fileCodeModel.CodeElements.Item(i).StartPoint.CreateEditPoint(); TextRanges trs = null; if (namespacePoint.FindPattern("{", (int)vsFindOptions.vsFindOptionsMatchCase, ref namespacePoint, ref trs)) { namespacePoints.Add(namespacePoint); } } } return(namespacePoints); }
public static bool HasExpressionBody(this CodeFunction codeFunction) { try { if (codeFunction.HasBody())//public string 只读表达式属性 => "只读表达式属性"; { try { codeFunction.GetStartPoint(); } catch { return(true); } } else { EditPoint editPointFind = codeFunction.StartPoint.CreateEditPoint(); if (editPointFind.FindPattern("=>") && editPointFind.LessThan(codeFunction.EndPoint)) { return(true); } } } catch { } return(false); }
/// <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")) { try { TextDocument projectItemDoc = (TextDocument)ideWindow.Document.Object("TextDocument"); EditPoint startPoint = projectItemDoc.StartPoint.CreateEditPoint(); EditPoint blockPoint = startPoint.CreateEditPoint(); TextRanges trs = null; bool found = blockPoint.FindPattern("<copyright", (int)vsFindOptions.vsFindOptionsMatchCase, ref blockPoint, ref trs); if (!found || blockPoint.Line > 2) { Debug.WriteLine("Finding assembly info..."); ProjectItem assemblyInfo = projectItem.DTE.Solution.FindProjectItem("AssemblyInfo.cs"); TextDocument objTextDoc = (TextDocument)ideWindow.Document.Object("TextDocument"); assemblyInfo.Open(EnvDTE.Constants.vsViewKindTextView).Activate(); TextDocument assemblyDoc = (TextDocument)assemblyInfo.DTE.ActiveWindow.Document.Object("TextDocument"); string company = RetrieveAssemblyInfoValue(assemblyDoc, "AssemblyCompany"); string copyright = RetrieveAssemblyInfoValue(assemblyDoc, "AssemblyCopyright"); string fileName = projectItem.Name; Debug.WriteLine("Adding Copyright to file: " + projectItem.Name); AddCopyrightToFile(projectItemDoc, fileName, company, copyright); } else { Debug.WriteLine("Copyright detected, skipping copyright header."); } } catch (Exception exc) { Debug.WriteLine(exc.ToString()); Debug.WriteLine("Format failed, skipping"); } } }
public void CalcInjectionPoints(CPClassLayout cpClassLayout, CPTraceVar traceVar, bool needDeclare) { if (needDeclare) { // find all places, where this file included CodeElement theFunc = null; // find & store all constructors init points of this class foreach (CodeElement _func in ent.Functions) { if (_func.Name == ent.Name) { theFunc = _func; VCCodeFunction vcFunc = (VCCodeFunction)_func; EditPoint pnt = _func.StartPoint.CreateEditPoint(); if (pnt.FindPattern("{")) { traceVar.traceVarInitPos.Add(new FilePosPnt() { fileName = _func.ProjectItem.Name, pos = { lineNum = pnt.Line - 1, linePos = pnt.LineCharOffset } }); } } } // if no constructor found add default one if (traceVar.traceVarInitPos.Count == 0) { EditPoint pnt = ent.StartPoint.CreateEditPoint(); if (pnt.FindPattern("{")) { traceVar.injConstructorPos = new FilePosPnt() { fileName = ent.ProjectItem.Name, pos = { lineNum = pnt.Line - 1, linePos = pnt.LineCharOffset } }; } } } }
/// <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(); } }
/// <summary> /// Inserts the method call in global ASAX file. /// </summary> /// <param name="selProject">The sel project.</param> internal static void InsertMethodCallInGlobalASAXFile(Project selProject) { ProjectItem fileProjectItem; bool registerRootsFound = false; bool registerGlobalFiltersFound = false; if (Common.IsProjectItemExist(selProject.ProjectItems, "Global.asax", out fileProjectItem)) { CodeElement registerRoutes = null; CodeElement registerGlobalFilters = null; FileCodeModel codeModel = fileProjectItem.ProjectItems.Item(1).FileCodeModel; foreach (CodeElement codeElement in codeModel.CodeElements) { if (codeElement.Kind == vsCMElement.vsCMElementNamespace) { foreach (CodeElement namespacechildElement in codeElement.Children) { if (namespacechildElement.Kind == vsCMElement.vsCMElementClass) { foreach (CodeElement functionElement in namespacechildElement.Children) { if (functionElement.Kind == vsCMElement.vsCMElementFunction && (functionElement.Name == "RegisterRoutes" || functionElement.Name == "RegisterGlobalFilters")) { if (functionElement.Name == "RegisterRoutes") { registerRoutes = functionElement; registerRootsFound = true; } if (functionElement.Name == "RegisterGlobalFilters") { registerGlobalFilters = functionElement; registerGlobalFiltersFound = true; } if (registerRootsFound && registerGlobalFiltersFound) { break; } } } } } } } if (registerRoutes != null) { EditPoint startEp = registerRoutes.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); if (!startEp.FindPattern("IntuitRegisterRoutes.RegisterIntuitAnywhereRoutes(routes);")) { EditPoint endEP = registerRoutes.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); endEP.Insert(Environment.NewLine + Environment.NewLine + "IntuitRegisterRoutes.RegisterIntuitAnywhereRoutes(routes);"); } } if (registerGlobalFilters != null) { EditPoint startEp = registerGlobalFilters.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); if (!startEp.FindPattern("filters.Add(new IntuitSampleMVC.utils.IppTag());")) { EditPoint endEP = registerGlobalFilters.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); endEP.Insert(Environment.NewLine + Environment.NewLine + "filters.Add(new IntuitSampleMVC.utils.IppTag());"); } } } }
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); } } } }
public ICheckCPPoint CheckCursorPos() { ICheckCPPoint checkPnt = null; Document activeDoc = ChartPoints.Globals.dte.ActiveDocument; string projName = activeDoc.ProjectItem.ContainingProject.Name; TextSelection sel = (TextSelection)activeDoc.Selection; TextPoint caretPnt = (TextPoint)sel.ActivePoint; VCCodeElement targetClassElem; for (;;) { // checks if we are in text document if (activeDoc == null) { break; } var textDoc = activeDoc.Object() as TextDocument; if (textDoc == null) { break; } // we work only with project items ProjectItem projItem = activeDoc.ProjectItem; if (projItem == null) { break; } // only c++ items FileCodeModel fcModel = projItem.FileCodeModel; if (fcModel == null) { break; } if (fcModel.Language != CodeModelLanguageConstants.vsCMLanguageVC) { break; } vcCodeModel.Synchronize();// !!! MOVE TO METHOD ??? // chartpoint allowed only in class methods CodeElement elem = fcModel.CodeElementFromPoint(caretPnt, vsCMElement.vsCMElementFunction); if (elem == null) { break; } if (elem.Kind != vsCMElement.vsCMElementFunction) { break; } VCCodeFunction targetFunc = (VCCodeFunction)elem; if (targetFunc == null) { break; } // check that we are in method definition (not declaration) in case of declaration in one file & definition in other if (!targetFunc.File.Equals(activeDoc.FullName, StringComparison.OrdinalIgnoreCase)) { break; } // we are working only with class methods not global function targetFunc.CodeModel.Synchronize(); targetFunc.CodeModel.SynchronizeFiles(); foreach (CodeElement _cl in targetFunc.CodeModel.Classes) { foreach (CodeElement _f in _cl.Children) { if (targetFunc.FullName.Equals(_f.FullName, StringComparison.OrdinalIgnoreCase)) { targetFunc = (VCCodeFunction)_f; break; } } } targetClassElem = (VCCodeElement)targetFunc.Parent; if (targetClassElem == null) { break; } if (targetClassElem.Kind != vsCMElement.vsCMElementClass) { targetClassElem = null; break; } VCCodeClass ownerClass = (VCCodeClass)targetClassElem; TextPoint startFuncBody = targetFunc.StartPointOf[vsCMPart.vsCMPartBody, vsCMWhere.vsCMWhereDefinition]; TextPoint endFuncBody = targetFunc.EndPointOf[vsCMPart.vsCMPartBody, vsCMWhere.vsCMWhereDefinition]; EditPoint startPnt = startFuncBody.CreateEditPoint(); EditPoint endPnt = endFuncBody.CreateEditPoint(); startPnt.FindPattern("{", (int)vsFindOptions.vsFindOptionsBackwards); endPnt.FindPattern("}"); if ((caretPnt.Line > startPnt.Line && caretPnt.Line < endPnt.Line) || (caretPnt.Line == startPnt.Line && caretPnt.LineCharOffset >= startPnt.LineCharOffset) || (caretPnt.Line == endPnt.Line && caretPnt.LineCharOffset <= endPnt.LineCharOffset)) { // Oh, oh you're in the body, now.. (c) int linePos = (caretPnt.Line == startPnt.Line ? startPnt.LineCharOffset + 1 : 1 /*0*/); checkPnt = new CheckCPPoint(ownerClass, projName, activeDoc.Name, System.IO.Path.GetFullPath(activeDoc.FullName).ToLower(), caretPnt.Line, linePos); return(checkPnt); } break; } return(checkPnt); }
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); }
//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); }
/// <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); } }
public void GenerateClass() { if (classFile == null) { return; } ImportModelSourceToContentProject(); StringBuilder sb = new StringBuilder(); string variable = sb. Append("Camera camera;\r\n"). Append("Terrain terrain;\r\n"). Append("Texture2D heightMap;\r\n"). Append("World world;\r\n"). Append("Grid grid;\r\n"). ToString(); sb.Clear(); Vector3 cameraPos = mapModel.MainCamera.Position; Vector3 cameraRot = mapModel.MainCamera.EulerRotation; sb. Append("CollisionSystem collisionSystem = new CollisionSystemPersistentSAP();\r\n"). Append("world = new World(collisionSystem);\r\n"). Append("world.AllowDeactivation = true;\r\n"). Append("world.Gravity = new JVector(0, ").Append(mapModel.PhysicsWorld.Gravity).Append("f, 0);\r\n"). Append("world.ContactSettings.MaterialCoefficientMixing = ContactSettings.MaterialCoefficientMixingType.").Append(mapModel.PhysicsWorld.MaterialCoefficientMixing.ToString()).Append(";\r\n"). Append("collisionSystem.CollisionDetected += new CollisionDetectedHandler(collisionSystem_CollisionDetected);\r\n\r\n"). Append("camera = new Camera(this);\r\n"). Append("camera.Name = \"camera\";\r\n"). Append("camera.Position = new Vector3(").Append(cameraPos.X).Append("f, ").Append(cameraPos.Y).Append("f, ").Append(cameraPos.Z).Append("f);\r\n"). Append("camera.EulerRotation = new Vector3(").Append(cameraRot.X).Append("f, ").Append(cameraRot.Y).Append("f, ").Append(cameraRot.Z).Append("f);\r\n"); foreach (EditorModel.PropertyModel.Script script in mapModel.MainCamera.Scripts) { sb.Append("camera.AddScript(new ").Append(System.IO.Path.GetFileNameWithoutExtension(script.Name)).Append("());\r\n"); } sb.Append("Components.Add(camera);\r\n\r\n"); string constructor = sb.ToString(); sb.Clear(); sb. Append("heightMap = Content.Load<Texture2D>(\"" + heightMapAsset + "\");\r\n"). Append("terrain = new Terrain(GraphicsDevice, camera, heightMap, this, world);\r\n"). Append("terrain.Texture = Content.Load<Texture2D>(\"" + textureAsset + "\");\r\n"). Append("Components.Add(terrain);\r\n\r\n"). Append("grid = new Grid(this, terrain, 8, camera, GraphicsDevice, new BasicEffect(GraphicsDevice), world);\r\n"). Append("grid.RoadModel = Content.Load<Model>(\"jalan_raya\");\r\n"). Append("grid.RoadModel_belok = Content.Load<Model>(\"jalan_raya_belok\");\r\n"). Append("grid.GridMap = Content.Load<Texture2D>(\"gridmap_Game2\");\r\n"). Append("grid.ImportGridMap();\r\n\r\n"); string loadContent = sb.ToString(); sb.Clear(); string update = sb. Append("float step = (float)gameTime.ElapsedGameTime.TotalSeconds;\r\n"). Append("if (step > 1.0f / 100.0f) step = 1.0f / 100.0f;\r\n"). Append("world.Step(step, true);\r\n"). ToString(); sb.Clear(); string draw = sb. ToString(); sb.Clear(); foreach (CodeLines codeLines in codeLinesList) { variable += codeLines.Code[CodeLines.CodePosition.Variable] + ((codeLines.Code[CodeLines.CodePosition.Variable] != "") ? "\r\n" : ""); constructor += codeLines.Code[CodeLines.CodePosition.Constructor] + ((codeLines.Code[CodeLines.CodePosition.Constructor] != "") ? "\r\n" : ""); loadContent += codeLines.Code[CodeLines.CodePosition.LoadContent] + ((codeLines.Code[CodeLines.CodePosition.LoadContent] != "") ? "\r\n" : ""); draw += codeLines.Code[CodeLines.CodePosition.Draw] + ((codeLines.Code[CodeLines.CodePosition.Draw] != "") ? "\r\n" : ""); } EditPoint editPoint = null; EditPoint movePoint = null; string startPattern = "#region XnaLevelEditor"; string endPattern = "#endregion"; if (codeClass != null) { editPoint = codeClass.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); editPoint.FindPattern(startPattern, (int)vsFindOptions.vsFindOptionsNone, ref editPoint); movePoint = editPoint.CreateEditPoint(); movePoint.FindPattern(endPattern, (int)vsFindOptions.vsFindOptionsNone); editPoint.ReplaceText(movePoint, "\r\n" + variable, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat); movePoint.SmartFormat(movePoint); } if (constructorFunction != null) { editPoint = constructorFunction.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); editPoint.FindPattern(startPattern, (int)vsFindOptions.vsFindOptionsNone, ref editPoint); movePoint = editPoint.CreateEditPoint(); movePoint.FindPattern(endPattern, (int)vsFindOptions.vsFindOptionsNone); editPoint.ReplaceText(movePoint, "\r\n" + constructor, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat); movePoint.SmartFormat(movePoint); } if (loadContentFunction != null) { editPoint = loadContentFunction.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); editPoint.FindPattern(startPattern, (int)vsFindOptions.vsFindOptionsNone, ref editPoint); movePoint = editPoint.CreateEditPoint(); movePoint.FindPattern(endPattern, (int)vsFindOptions.vsFindOptionsNone); editPoint.ReplaceText(movePoint, "\r\n" + loadContent, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat); movePoint.SmartFormat(movePoint); } if (updateFunction != null) { editPoint = updateFunction.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); editPoint.FindPattern(startPattern, (int)vsFindOptions.vsFindOptionsNone, ref editPoint); movePoint = editPoint.CreateEditPoint(); movePoint.FindPattern(endPattern, (int)vsFindOptions.vsFindOptionsNone); editPoint.ReplaceText(movePoint, "\r\n" + update, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat); movePoint.SmartFormat(movePoint); } if (drawFunction != null) { editPoint = drawFunction.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); editPoint.FindPattern(startPattern, (int)vsFindOptions.vsFindOptionsNone, ref editPoint); movePoint = editPoint.CreateEditPoint(); movePoint.FindPattern(endPattern, (int)vsFindOptions.vsFindOptionsNone); editPoint.ReplaceText(movePoint, "\r\n" + draw, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat); movePoint.SmartFormat(movePoint); } }
private void SortFunctionsWithinClass(CodeElement codeElement) { EditPoint fieldInsertionPoint; EditPoint constructorInsertionPoint; EditPoint finalizerInsertionPoint; EditPoint delegateInsertionPoint; EditPoint eventInsertionPoint; EditPoint enumInsertionPoint; EditPoint interfaceInsertionPoint; EditPoint propertyInsertionPoint; EditPoint methodInsertionPoint; EditPoint structInsertionPoint; EditPoint classInsertionPoint; EditPoint origin = codeElement.StartPoint.CreateEditPoint(); EditPoint classPoint = codeElement.StartPoint.CreateEditPoint(); TextRanges trs = null; if (origin.FindPattern("{", (int)vsFindOptions.vsFindOptionsMatchCase, ref classPoint, ref trs)) { classPoint.Insert("\r\n"); origin = classPoint.CreateEditPoint(); fieldInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); constructorInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); finalizerInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); delegateInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); eventInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); enumInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); interfaceInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); propertyInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); methodInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); structInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); classInsertionPoint = classPoint.CreateEditPoint(); classPoint.Insert("\r\n\r\n"); Array accessLevels = Enum.GetValues(typeof(vsCMAccess)); foreach (vsCMAccess accessLevel in accessLevels) { for (int i = 1; i <= codeElement.Children.Count; i++) { CodeElement element = codeElement.Children.Item(i); EditPoint elementStartPoint = element.StartPoint.CreateEditPoint(); switch (element.Kind) { case vsCMElement.vsCMElementVariable: CodeVariable variable = element as CodeVariable; if (variable != null) { if (variable.Access == accessLevel) { MoveCodeBlock(codeElement, element, fieldInsertionPoint); } } else { Debug.WriteLine("CodeVariable " + element.Name + " null"); } break; case vsCMElement.vsCMElementFunction: // method, constructor, or finalizer CodeFunction function = element as CodeFunction; if (function != null) { if (function.Access == accessLevel) { if (function.FunctionKind == vsCMFunction.vsCMFunctionConstructor) { MoveCodeBlock(codeElement, element, constructorInsertionPoint); } else if (function.FunctionKind == vsCMFunction.vsCMFunctionDestructor) { MoveCodeBlock(codeElement, element, finalizerInsertionPoint); } else { MoveCodeBlock(codeElement, element, methodInsertionPoint); } } } else { Debug.WriteLine("CodeFunction " + element.Name + " null"); } break; case vsCMElement.vsCMElementDelegate: CodeDelegate delegateElement = element as CodeDelegate; if (delegateElement != null) { if (delegateElement.Access == accessLevel) { MoveCodeBlock(codeElement, element, delegateInsertionPoint); } } else { Debug.WriteLine("CodeDelegate " + element.Name + " null"); } break; case vsCMElement.vsCMElementEvent: MoveCodeBlock(codeElement, element, eventInsertionPoint); break; case vsCMElement.vsCMElementEnum: CodeEnum enumElement = element as CodeEnum; if (enumElement != null) { if (enumElement.Access == accessLevel) { MoveCodeBlock(codeElement, element, enumInsertionPoint); } } else { Debug.WriteLine("CodeEnum " + element.Name + " null"); } break; case vsCMElement.vsCMElementInterface: CodeInterface interfaceElement = element as CodeInterface; if (interfaceElement != null) { if (interfaceElement.Access == accessLevel) { MoveCodeBlock(codeElement, element, interfaceInsertionPoint); } } else { Debug.WriteLine("CodeInterface " + element.Name + " null"); } break; case vsCMElement.vsCMElementProperty: CodeProperty propertyElement = element as CodeProperty; if (propertyElement != null) { if (propertyElement.Access == accessLevel) { MoveCodeBlock(codeElement, element, propertyInsertionPoint); } } else { Debug.WriteLine("CodeProperty " + element.Name + " null"); } break; case vsCMElement.vsCMElementStruct: CodeStruct structElement = element as CodeStruct; if (structElement != null) { if (structElement.Access == accessLevel) { MoveCodeBlock(codeElement, element, structInsertionPoint); } } else { Debug.WriteLine("CodeStruct " + element.Name + " null"); } break; case vsCMElement.vsCMElementClass: CodeClass classElement = element as CodeClass; if (classElement != null) { if (classElement.Access == accessLevel) { MoveCodeBlock(codeElement, element, classInsertionPoint); } } else { Debug.WriteLine("CodeStruct " + element.Name + " null"); } break; default: Debug.WriteLine("unknown element: " + element.Name + " - " + element.Kind); break; } } 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); } } } origin.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); classInsertionPoint.CreateEditPoint().DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); } }
public Dictionary <string, BaseObject> ReadCodeLines() { EditPoint editPoint = null; EditPoint movePoint = null; string startPattern = "#region XnaLevelEditor"; string endPattern = "#endregion"; #region var declaration regex /* reference http://stackoverflow.com/questions/585853/regex-for-variable-declaration-and-initialization-in-c-sharp * tested at http://rubular.com/ * * (a line can start with some spaces) followed by, * (Type) followed by * (at least one space) * (variable_1) * (optionally * (comma // next var | | '='number // initialization | ) ...` * * ^ \s* \w+ \s+ \w+ ? (',' | '=' \d+ ) ... * line some type at least var optionally more or init some * start spaces (some chars) one space (some chars) vars val digits * * * variable <variable> * [a-zA-Z_][a-zA-Z0-9_]* * simple declaration of DrawingObject * \s*(DrawingObject|Camera)\s+<variable>\s* * instantiation DrawingObject * \s*<variable>\s*=\s*new\s+DrawingObject\(\s*this\s*,\s*camera\s*,\s*\"\w+\"\s*,\s*world\s*\)\s* * declaration (and instantiationon) of DrawingObject * \s*DrawingObject\s+<variable>(\s*=\s*new\s+DrawingObject\(\))?(,\s*<variable>\s*(=\s*new\s+DrawingObject\(\))))* * integer or float <integerFloat> * \-\d+(\.\d+)?f? * variable, integer, or float <variableIntegerFloat> * (<integerFloat>|<variable>) * Content load * ^\s*<variable>\s*\.\s*DrawingModel\s*=\s*Content\s*.\s*Load\s*<\s*Model\s*>\s*\(\s*\"\w+\"\s*\)\s*$ * instantiation Vector3 <instantiationVector3> * \s*new\s+Vector3\s*\((\s*(<variableIntegerFloat>)\s*,\s*(<variableIntegerFloat>)\s*,\s*(<variableIntegerFloat>)\s*)?\)\s* * set a DrawingObject's Position value * \s*<variable>\s*\.\s*Position\s*=<instantiationVector3> * set a DrawingObject's Rotation value * \s*<variable>\s*\.\s*Rotation\s*=<instantiationVector3> * * set a DrawingObject's Scale value * \s*<variable>\s*\.\s*Scale\s*=<instantiationVector3> * set PhysicsEnabled * \s*<variable>\s*\.\s*PhysicsEnabled\s*=\s*(true|false)\s* * set IsActive * \s*<variable>\s*\.\s*PhysicsAdapter\s*.\s*Body\s*.\s*IsActive\s*=\s*(true|false)\s* * set IsStatic * \s*<variable>\s*\.\s*PhysicsAdapter\s*.\s*Body\s*.\s*IsStatic\s*=\s*(true|false)\s* * set CharacterControllerEnabled * \s*<variable>\s*\.\s*PhysicsAdapter\s*.\s*EnableCharacterController\s*\(\s*\)\s* * change PhysicsAdapter * \s*<variable>\s*\.\s*ChangePhysicsAdapter\s*\(\s*typeof\s*\(\s*[a-zA-Z_][a-zA-Z0-9_]*\s*\)\s*,\s*new\s*object\s*\[\s*\]\s*{[\s\w\,\(\)\-\d\.]*}\s*\)\s* * add script * \s*<variable>\s*\.AddScript\s*\(new\s*<variable>\s*\(\s*\)\s*\)\s* * */ #endregion const string variableRegex = "[a-zA-Z_][a-zA-Z0-9_]*"; const string integerOrFloatRegex = "\\-?\\d+(.\\d+)?f?"; const string variableIntegerFloatRegex = integerOrFloatRegex + "|" + variableRegex; const string declarationRegex = "^\\s*(DrawingObject|Camera)\\s+" + variableRegex + "\\s*$"; const string instantiationRegex = "^\\s*" + variableRegex + "\\s*=\\s*new\\s+DrawingObject\\(\\s*this\\s*,\\s*camera\\s*,\\s*\\\"\\w+\\\"\\s*,\\s*world\\s*\\)\\s*$"; //const string loadContentRegex = "^\\s*" + variableRegex + "\\s*.\\s*DrawingModel\\s*=\\s*Content\\s*.\\s*Load\\s*<\\s*Model\\s*>\\s*\\(\\s*\\\"\\w+\\\"\\s*\\)\\s*$"; const string instantiationVector3Regex = "\\s*new\\s+Vector3\\s*\\((\\s*(" + variableIntegerFloatRegex + ")\\s*,\\s*(" + variableIntegerFloatRegex + ")\\s*,\\s*(" + variableIntegerFloatRegex + ")\\s*)?\\)\\s*"; const string setPositionRegex = "^\\s*" + variableRegex + "\\s*\\.\\s*Position\\s*=" + instantiationVector3Regex + "$"; const string setRotationRegex = "^\\s*" + variableRegex + "\\s*\\.\\s*EulerRotation\\s*=" + instantiationVector3Regex + "$"; const string setScaleRegex = "^\\s*" + variableRegex + "\\s*\\.\\s*Scale\\s*=" + instantiationVector3Regex + "$"; const string setPhysicsEnabledRegex = "^\\s*" + variableRegex + "\\s*\\.\\s*PhysicsEnabled\\s*=\\s*(true|false)\\s*$"; const string setIsActiveRegex = "^\\s*" + variableRegex + "\\s*\\.\\s*PhysicsAdapter\\s*.\\s*Body\\s*.\\s*IsActive\\s*=\\s*(true|false)\\s*$"; const string setIsStaticRegex = "^\\s*" + variableRegex + "\\s*\\.\\s*PhysicsAdapter\\s*.\\s*Body\\s*.\\s*IsStatic\\s*=\\s*(true|false)\\s*$"; const string enableCharacterControllerRegex = "^\\s*" + variableRegex + "\\s*\\.\\s*PhysicsAdapter\\s*.\\s*EnableCharacterController\\s*\\(\\s*\\)\\s*$"; const string changePhysicsAdapterRegex = "^\\s*" + variableRegex + "\\s*\\.\\s*ChangePhysicsAdapter\\s*\\(\\s*typeof\\s*\\(\\s*[a-zA-Z_][a-zA-Z0-9_]*\\s*\\)\\s*,\\s*new\\s*object\\s*\\[\\s*\\]\\s*{.*}\\s*\\)\\s*$"; const string addScriptRegex = "^\\s*" + variableRegex + "\\s*\\.AddScript\\s*\\(new\\s*" + variableRegex + "\\s*\\(\\s*\\)\\s*\\)\\s*$"; Dictionary <string, BaseObject> objects = new Dictionary <string, BaseObject>(); if (codeClass != null) { editPoint = codeClass.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); editPoint.FindPattern(startPattern, (int)vsFindOptions.vsFindOptionsNone, ref editPoint); movePoint = editPoint.CreateEditPoint(); movePoint.FindPattern(endPattern, (int)vsFindOptions.vsFindOptionsNone); string lines = editPoint.GetText(movePoint); foreach (string line in lines.Split(';')) { if (Regex.IsMatch(line, declarationRegex)) { ParseDeclaration(objects, line); } } } if (constructorFunction != null) { editPoint = constructorFunction.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); editPoint.FindPattern(startPattern, (int)vsFindOptions.vsFindOptionsNone, ref editPoint); movePoint = editPoint.CreateEditPoint(); movePoint.FindPattern(endPattern, (int)vsFindOptions.vsFindOptionsNone); string lines = editPoint.GetText(movePoint); foreach (string line in lines.Split(';')) { if (Regex.IsMatch(line, instantiationRegex)) { ParseInstantiation(variableRegex, objects, line, contentProject); } if (Regex.IsMatch(line, setPositionRegex)) { ParseSetPosition(variableRegex, objects, line); } if (Regex.IsMatch(line, setRotationRegex)) { ParseSetRotation(variableRegex, objects, line); } if (Regex.IsMatch(line, setScaleRegex)) { ParseSetScale(variableRegex, objects, line); } if (Regex.IsMatch(line, setPhysicsEnabledRegex)) { ParseSetPhysicsEnabled(variableRegex, objects, line); } if (Regex.IsMatch(line, setIsActiveRegex)) { ParseSetIsActiveRegex(variableRegex, objects, line); } if (Regex.IsMatch(line, setIsStaticRegex)) { ParseSetIsStaticRegex(variableRegex, objects, line); } if (Regex.IsMatch(line, enableCharacterControllerRegex)) { ParseEnableCharacterController(variableRegex, objects, line); } if (Regex.IsMatch(line, changePhysicsAdapterRegex)) { ParseChangePhysicsAdapter(variableRegex, integerOrFloatRegex, instantiationVector3Regex, objects, line); } if (Regex.IsMatch(line, addScriptRegex)) { string varName = Regex.Match(line, "^\\s*" + variableRegex).Value.Trim(); if (objects.Keys.Contains(varName)) { string scriptName = Regex.Match(line, "new\\s*" + variableRegex).Value.Replace("new", "").Trim() + ".cs"; string scriptsFolderPath = Path.GetDirectoryName(currentProject.FullName) + "\\Scripts"; objects[varName].Scripts.Add(new EditorModel.PropertyModel.Script() { Name = scriptName, Path = scriptsFolderPath + "\\" + scriptName }); } } } } return(objects); }
/// <summary> /// 匹配代码模型 /// </summary> /// <param name="win"></param> /// <param name="funcInfo"></param> /// <returns></returns> public static bool ToCode(Window win, FuncInfo funcInfo) { // 查找命名空间 Func <CodeElements, CodeNamespace> findNamespace = source => { if (source == null) { return(null); } for (int i = 1; i <= source.Count; i++) { CodeElement elem = source.Item(i); if (elem.Kind != vsCMElement.vsCMElementNamespace) { continue; } var target = (CodeNamespace)elem; if (!target.Name.Equals(funcInfo.Namespace, StringComparison.OrdinalIgnoreCase)) { continue; } return(target); } return(null); }; // 查找类 Func <CodeElements, CodeClass> findClass = source => { if (source == null) { return(null); } for (int i = 1; i <= source.Count; i++) { CodeElement elem = source.Item(i); if (elem.Kind != vsCMElement.vsCMElementClass) { continue; } var target = (CodeClass)elem; if (!target.Name.Equals(funcInfo.Class, StringComparison.OrdinalIgnoreCase)) { continue; } return(target); } return(null); }; // 查找方法 Func <CodeElements, CodeFunction> findFunc = source => { if (source == null) { return(null); } for (int i = 1; i <= source.Count; i++) { CodeElement elem = source.Item(i); if (elem.Kind != vsCMElement.vsCMElementFunction) { continue; } var target = (CodeFunction)elem; if (target.Name.Equals(funcInfo.Func, StringComparison.OrdinalIgnoreCase) && (funcInfo.ParamNum == -1 || target.Parameters.Count == funcInfo.ParamNum)) { return(target); } } return(null); }; // 获取目标方法 FileCodeModel codeModel = win.Document.ProjectItem.FileCodeModel; CodeNamespace namesp = findNamespace(codeModel?.CodeElements); CodeClass cls = findClass(namesp?.Children); CodeFunction func = findFunc(cls?.Children); if (func == null) { return(false); } // 选中 EditPoint startPoint = func.StartPoint.CreateEditPoint(); EditPoint endPoint = null; bool find = startPoint.FindPattern($@"\b{funcInfo.Func}\b", (int)(vsFindOptions.vsFindOptionsNone | vsFindOptions.vsFindOptionsRegularExpression), ref endPoint); if (find) { var doc = (TextDocument)win.Document.Object("TextDocument"); doc.Selection.MoveToPoint(endPoint, false); doc.Selection.MoveToPoint(startPoint, true); } return(find); }
/// <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(); // Don't attempt to insert a header if there's no active document. if (InsertConstructorHeaderCommand.environment.ActiveDocument == null) { return; } // Get the selected text from the editor environment. TextSelection selection = InsertConstructorHeaderCommand.environment.ActiveDocument.Selection as TextSelection; // Create an edit point for the current location in the document. The general idea here is to look backward from the current cursor // location until we find a class or structure declaration. We'll then extract the name of the class (or structure) and look for the // constructor. Once we find it, we'll replace the existing summary with the new boilerplate version that Style COP wants to see. EditPoint startPoint = selection.AnchorPoint.CreateEditPoint(); // The 'FindPattern' will return a collection of found sub-tags in this collection. The function seems to be a little brain damaged or // else it isn't documented clearly. If you have two sub-tags in your pattern, three text ranges are returned. It appears that one of // the ranges is the entire match, though it shows up in no particular order. TextRanges textRanges = null; // This starts the process by finding the class or structure declaration. if (startPoint.FindPattern( InsertConstructorHeaderCommand.ClassDeclarationPattern, (int)(vsFindOptions.vsFindOptionsRegularExpression | vsFindOptions.vsFindOptionsBackwards), null, ref textRanges)) { // Whether the object is a class or a structure will be used when constructing the boilerplate summary comment. The name of the // class is also used to create the summary. The 'index' to the 'Item' indexer is a little brain damaged as well. It turns out that // the COM class will only work with floating point numbers (go figure) and starts counting at 1.0. var objectTypeRange = textRanges.Item(3.0); string objectType = objectTypeRange.StartPoint.GetText(objectTypeRange.EndPoint); var classNameRange = textRanges.Item(4.0); string className = classNameRange.StartPoint.GetText(classNameRange.EndPoint); TextRanges modifierRanges = null; // This will find the constructor for the class or structure. if (startPoint.FindPattern( string.Format(CultureInfo.InvariantCulture, InsertConstructorHeaderCommand.ConstructorDeclarationPattern, className), (int)vsFindOptions.vsFindOptionsRegularExpression, null, ref modifierRanges)) { var modifierRange = modifierRanges.Item(1.0); string modifier = modifierRange.StartPoint.GetText(modifierRange.EndPoint); bool isStatic = modifier.StartsWith("static", StringComparison.Ordinal); // This will find the summary comment and return the entire range of the comment from the first line to the end of the line // containing the ending tag. This covers comments that have been compressed onto a single line as well as the more common // multi-line 'summary' comment. EditPoint endPoint = null; if (startPoint.FindPattern( InsertConstructorHeaderCommand.ConstructorSummaryPattern, (int)(vsFindOptions.vsFindOptionsRegularExpression | vsFindOptions.vsFindOptionsBackwards), ref endPoint, ref textRanges)) { // Extract the prefix of the comment. This tells us how many tabs (or spaces) there are in the comment delimiter. var prefixRange = textRanges.Item(1.0); string prefix = prefixRange.StartPoint.GetText(prefixRange.EndPoint); // Static and instance constructors have different formats. This will chose a header template that is appropriate. string constructorHeader = isStatic ? Resources.StaticConstructorHeaderTemplate : Resources.InstanceConstructorHeaderTemplate; // Replace the existing summary comment with a boilerplate constructed from the information collected about the class. This // boilerplate comment will pass mustard in Style COP. string replacementText = string.Format( CultureInfo.InvariantCulture, constructorHeader, prefix, className, objectType); startPoint.ReplaceText( endPoint, replacementText, (int)(vsEPReplaceTextOptions.vsEPReplaceTextNormalizeNewlines | vsEPReplaceTextOptions.vsEPReplaceTextTabsSpaces)); } } } }
/// <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 --"); } }