/// <summary> /// Moves cursor/editpoint exactly. /// </summary> /// <param name="point"></param> /// <param name="count"></param> /// <param name="direction"></param> /// <returns></returns> /// <remarks> /// DTE functions that moves editpoint counts newline as single character, /// since we get the character count from regular regex not the DTE find, the char count is slightly off /// </remarks> public static EditPoint CharMoveExact(EditPoint point, int count, int direction) { while (count > 0) { //Normalize if (direction > 1) { direction = 1; } else if (direction < 0) { direction = -1; } //If we are asking 1 and getting 2, its a newline. This is a quirk/feature of EnvDTE where all its functions treats newline as single character if (point.GetText(direction).Length == 2) { count -= 1; } if (direction < 0) { point.CharLeft(1); } else { point.CharRight(1); } count -= 1; } return point; }
/// <summary> /// Reformat all comments between the specified start and end point. Comments that start /// within the range, even if they overlap the end are included. /// </summary> /// <param name="textDocument">The text document.</param> /// <param name="start">The start point.</param> /// <param name="end">The end point.</param> public bool FormatComments(TextDocument textDocument, EditPoint start, EditPoint end) { bool foundComments = false; int tabSize = CodeCommentHelper.GetTabSize(_package, textDocument); while (start.Line <= end.Line) { if (CodeCommentHelper.IsCommentLine(start)) { var comment = new CodeComment(start, tabSize); if (comment.IsValid) { comment.Format(); foundComments = true; } if (comment.EndPoint != null) { start = comment.EndPoint.CreateEditPoint(); } } if (start.Line == textDocument.EndPoint.Line) { break; } start.LineDown(); start.StartOfLine(); } return foundComments; }
/// <summary> /// Moves cursor/editpoint exactly. /// </summary> /// <param name="point"></param> /// <param name="count"></param> /// <param name="direction"></param> /// <returns></returns> /// <remarks> /// DTE functions that moves editpoint counts newline as single character, /// since we get the character count from regular regex not the DTE find, the char count is slightly off /// </remarks> public static EditPoint CharMoveExact(EditPoint point, int count, int direction) { while (count > 0) { if (direction > 1) { direction = 1; } else { if (direction < 0) { direction = -1; } } if (point.GetText(direction).Length == 2) { count--; } if (direction < 0) { point.CharLeft(); } else { point.CharRight(); } count--; } return point; }
/// <summary> /// Reformat all comments between the specified start and end point. Comments that start /// within the range, even if they overlap the end are included. /// </summary> /// <param name="textDocument">The text document.</param> /// <param name="start">The start point.</param> /// <param name="end">The end point.</param> public bool FormatComments(TextDocument textDocument, EditPoint start, EditPoint end) { var options = new CodeCommentOptions(Settings.Default, _package, textDocument); bool foundComments = false; while (start.Line <= end.Line) { if (CodeCommentHelper.IsCommentLine(start)) { var comment = new CodeComment(start); if (comment.IsValid) { comment.Format(options); foundComments = true; } if (comment.EndPoint != null) { start = comment.EndPoint.CreateEditPoint(); } } if (start.Line == textDocument.EndPoint.Line) { break; } start.LineDown(); start.StartOfLine(); } return foundComments; }
private void ToggleCommentsAboveMember(EditPoint editPoint, string commentPrefix) { try { int? firstLineOfComment = null; editPoint.StartOfLine(); editPoint.CharLeft(); while(!editPoint.AtStartOfDocument) { String line = editPoint.GetLines(editPoint.Line, editPoint.Line + 1).Trim(); if(line.Length == 0 || line.StartsWith(commentPrefix)) { if(line.Length > 0) { firstLineOfComment = editPoint.Line; } else if(firstLineOfComment.HasValue) { ToggleExpansionAtLine(editPoint.CreateEditPoint(), firstLineOfComment.Value, commentPrefix); firstLineOfComment = null; } editPoint.StartOfLine(); editPoint.CharLeft(); } else { break; } } if(firstLineOfComment.HasValue) { ToggleExpansionAtLine(editPoint.CreateEditPoint(), firstLineOfComment.Value, commentPrefix); } } catch(Exception) { } }
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 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); } }
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); } }
private void AddEditPoints(EditPoint.EditPointTypes editPointType) { if (editPointType == EditPoint.EditPointTypes.ConnectionEditPoint) { if ((this.editPoints.Count == 0) || !this.editPoints[0].EditedConnectionPoint.Equals(this.Source)) { this.editPoints.Insert(0, new EditPoint(this, this.Source)); } if ((this.editPoints.Count < 2) || !this.editPoints[this.editPoints.Count - 1].EditedConnectionPoint.Equals(this.Target)) { this.editPoints.Add(new EditPoint(this, this.Target)); } } else if (editPointType == EditPoint.EditPointTypes.MidSegmentEditPoint) { int num = this.Source.Bounds.Width * 4; for (int i = 0; i < (this.editPoints.Count - 1); i++) { if ((this.editPoints[i].Type != EditPoint.EditPointTypes.MidSegmentEditPoint) && (this.editPoints[i + 1].Type != EditPoint.EditPointTypes.MidSegmentEditPoint)) { Point[] segments = new Point[] { this.editPoints[i].Location, this.editPoints[i + 1].Location }; if (DesignerGeometryHelper.DistanceOfLineSegments(segments) > num) { Point point = DesignerGeometryHelper.MidPointOfLineSegment(this.editPoints[i].Location, this.editPoints[i + 1].Location); this.editPoints.Insert(i + 1, new EditPoint(this, EditPoint.EditPointTypes.MidSegmentEditPoint, point)); } } } } else if ((editPointType == EditPoint.EditPointTypes.MultiSegmentEditPoint) && (this.editPoints.Count == 2)) { List<Point> list = new List<Point>(this.editedConnector.ConnectorSegments); if ((list.Count > 0) && (list[0] == this.Source.Location)) { list.RemoveAt(0); } if ((list.Count > 0) && (list[list.Count - 1] == this.Target.Location)) { list.RemoveAt(list.Count - 1); } List<EditPoint> list2 = new List<EditPoint>(); for (int j = 0; j < list.Count; j++) { list2.Add(new EditPoint(this, EditPoint.EditPointTypes.MultiSegmentEditPoint, list[j])); } this.editPoints.InsertRange(this.editPoints.Count - 1, list2.ToArray()); } }
public ConnectorEditor(FreeFormPanel panel, Connector connector) { if (panel == null) { throw FxTrace.Exception.AsError(new ArgumentNullException("panel")); } if (connector == null) { throw FxTrace.Exception.AsError(new ArgumentNullException("connector")); } this.editPoints = new List<EditPoint>(); this.parentPanel = panel; this.editedConnector = connector; this.activeEditPoint = null; connector.IsSelected = true; // When the ConnectorEditor is active, we allow reconnecting the start point of the Connector instead // of creating a new transition that shares the same trigger. So we need to disable tooltips and // highlighting effects for all overlapping start dots. this.SetIsHitTestVisibleForOverlappingStartDots(false); DisplayEditPoints(); }
/// <summary> /// Inserts an #endregion tag for the specified region following the specified end point. /// </summary> /// <param name="region">The region to end.</param> /// <param name="endPoint">The end point.</param> /// <returns>The updated cursor.</returns> public EditPoint InsertEndRegionTag(CodeItemRegion region, EditPoint endPoint) { var cursor = endPoint.CreateEditPoint(); // If the cursor is not preceeded only by whitespace, insert a new line. var firstNonWhitespaceIndex = cursor.GetLine().TakeWhile(char.IsWhiteSpace).Count(); if (cursor.DisplayColumn > firstNonWhitespaceIndex + 1) { cursor.Insert(Environment.NewLine); } cursor.Insert("#endregion"); if (Settings.Default.Cleaning_UpdateEndRegionDirectives) { cursor.Insert(" " + region.Name); } // If the cursor is not followed only by whitespace, insert a new line. var lastNonWhitespaceIndex = cursor.GetLine().TrimEnd().Length; if (cursor.DisplayColumn < lastNonWhitespaceIndex + 1) { cursor.Insert(Environment.NewLine); cursor.LineUp(); cursor.EndOfLine(); } endPoint.SmartFormat(cursor); region.EndPoint = cursor.CreateEditPoint(); var regionWrapper = new[] { region }; _insertBlankLinePaddingLogic.InsertPaddingBeforeEndRegionTags(regionWrapper); _insertBlankLinePaddingLogic.InsertPaddingAfterEndRegionTags(regionWrapper); return cursor; }
/// <summary> /// Formats the comment. /// </summary> /// <param name="options">The options to be used for formatting.</param> public TextPoint Format(CodeCommentOptions options) { if (!IsValid) { throw new InvalidOperationException("Cannot format comment, the comment is not valid."); } var originalText = _startPoint.GetText(_endPoint); var matches = _commentLineRegex.Matches(originalText).OfType<Match>().ToArray(); var commentPrefix = matches.First(m => m.Success).Groups["prefix"].Value; // Concatenate the comment lines without comment prefixes and see if the resulting bit // can be parsed as XML. ICommentLine line = null; var lineTexts = matches.Select(m => m.Groups["line"].Value).ToArray(); var commentText = string.Join(Environment.NewLine, lineTexts); if (commentText.Contains('<')) { try { var xml = XElement.Parse(string.Format("<doc>{0}</doc>", commentText)); line = new CommentLineXml(xml, options); } catch (System.Xml.XmlException) { // If XML cannot be parsed, comment will be handled as a normal text comment. } } if (line == null) { line = new CommentLine(commentText); } var formatter = new CommentFormatter( line, commentPrefix, options, CodeCommentHelper.GetCommentRegex(_document.Language, false)); if (!formatter.Equals(originalText)) { var cursor = StartPoint.CreateEditPoint(); cursor.Delete(EndPoint); cursor.Insert(formatter.ToString()); _endPoint = cursor.CreateEditPoint(); } return EndPoint; }
/// <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>Parses for strings by iterating through the FileCodeModel.</summary> /// <param name="startPoint">The start point.</param> /// <param name="endPoint">The end point.</param> /// <param name="lastDocumentLength">Last length of the document.</param> private void ParseForStrings(TextPoint startPoint, TextPoint endPoint, int lastDocumentLength) { //0.35-0.06 seconds (threaded: 2.47-1.77 seconds) List <StringResource> stringResources = new List <StringResource>(); bool isFullDocument = startPoint.AtStartOfDocument && endPoint.AtEndOfDocument, isTextWithStringLiteral = true; int startLine = startPoint.Line, startCol = startPoint.LineCharOffset, endLine = endPoint.Line, endCol = endPoint.LineCharOffset, documentLength = endPoint.Parent.EndPoint.Line, insertIndex = 0; if (isFullDocument) { m_StringResources.Clear(); } else { #region document manipulated -> adapt string resources and locations //determine whether the text between startLine and endLine (including) contains double quotes EditPoint editPoint = startPoint.CreateEditPoint() as EditPoint2; if (!startPoint.AtStartOfLine) { editPoint.StartOfLine(); } isTextWithStringLiteral = editPoint.GetLines(startLine, endLine + 1).Contains("\""); //move trailing locations behind changed lines if needed and //remove string resources on changed lines int lineOffset = documentLength - lastDocumentLength; #if DEBUG_OUTPUT System.Diagnostics.Debug.Print(" Line offset is {0}", lineOffset); #endif for (int i = m_StringResources.Count - 1; i >= 0; --i) { StringResource stringResource = m_StringResources[i]; int lineNo = stringResource.Location.X; if (lineNo + lineOffset > endLine) { if (lineOffset != 0) { #if DEBUG_OUTPUT System.Diagnostics.Debug.Print(" Move string literal from line {0} to {1}", lineNo, lineNo + lineOffset); #endif stringResource.Offset(lineOffset, 0); //move } //if } else if (lineNo >= startLine) { #if DEBUG_OUTPUT System.Diagnostics.Debug.Print(" Remove string literal {0} ({1}): {2}", i, stringResource.Location, stringResource.Text); #endif m_StringResources.RemoveAt(i); //remove changed line } else if (insertIndex == 0) { #if DEBUG_OUTPUT System.Diagnostics.Debug.Print(" List insert index is {0} / {1}", i + 1, m_StringResources.Count - 1); #endif insertIndex = i + 1; } //else if } //for #endregion } //else #if DEBUG_OUTPUT System.Diagnostics.Debug.Print(" Text has{0} string literals.", isTextWithStringLiteral ? string.Empty : " no"); #endif if (isTextWithStringLiteral) { CodeElements elements = m_Window.Document.ProjectItem.FileCodeModel.CodeElements; foreach (CodeElement element in elements) { ParseForStrings(element, m_DoProgress, stringResources, m_Settings, m_IsCSharp, startLine, endLine); #if DEBUG if (element.Kind == vsCMElement.vsCMElementProperty) { CodeProperty prop = element as CodeProperty; if ((prop.Getter == null) && (prop.Setter == null)) { //here we have an expression bodied property //if (m_IVsTextView != null) //{ // m_IVsTextView. //} } } #endif } //foreach #if DEBUG_OUTPUT System.Diagnostics.Debug.Print(" Found {0} string literals", stringResources.Count); #endif if (isFullDocument) { m_StringResources.AddRange(stringResources); } else if (stringResources.Count > 0) { m_StringResources.InsertRange(insertIndex, stringResources); } } //if m_DoCompleted(isFullDocument || (stringResources.Count > 0)); }
public override CodeFunction GenerateTest(CodeClass unitTestCodeClass, CodeFunction originalClassCodeFuntion) { vsCMFunction functionKind = vsCMFunction.vsCMFunctionFunction; object functionType = null; functionKind = vsCMFunction.vsCMFunctionSub; functionType = vsCMTypeRef.vsCMTypeRefVoid; string nextAvailableName = originalClassCodeFuntion.Name; if (!CodeSelectionHandler.CanGenerateHandleCodeFunction(unitTestCodeClass, nextAvailableName)) { nextAvailableName = GetNextAvailableCopyName(unitTestCodeClass, ref nextAvailableName, unitTestCodeClass.ProjectItem.ContainingProject); } CodeFunction unitTestCodeFunction = unitTestCodeClass.AddFunction( nextAvailableName, functionKind, functionType, -1, originalClassCodeFuntion.Access, -1); bool tvIsStatic = originalClassCodeFuntion.IsShared; //add the NUnit attribute to the function unitTestCodeFunction.AddAttribute("NUnit.Framework.Test", "", -1); try { unitTestCodeFunction.Comment = originalClassCodeFuntion.Comment; unitTestCodeFunction.DocComment = originalClassCodeFuntion.DocComment; } catch (Exception ex) { //ignore, for some reason the doc throws in vb Logger.LogException(ex); } string tvFunctionCallTemplate = string.Empty; //"iv{0}Type.{1}("; string tvFunctionReturnTemplate = string.Empty; //"{0} iv{1}Return = "; tvFunctionCallTemplate = "iv{0}Type.{1}("; if (tvIsStatic) { tvFunctionCallTemplate = "{0}.{1}("; } tvFunctionReturnTemplate = "Dim iv{1}Return As {0} = "; string tvTempParameterList = string.Empty; string tvFunctionCall = tvFunctionCallTemplate; string tvFunctionReturn = tvFunctionReturnTemplate; if (!originalClassCodeFuntion.FunctionKind.ToString().Equals("vsCMFunctionConstructor")) { CodeElements tvParameters = originalClassCodeFuntion.Parameters; foreach (CodeElement tvCodeElement in tvParameters) { if (!tvFunctionCall.Equals(tvFunctionCallTemplate)) { tvFunctionCall += ", "; } CodeParameter2 tvCodeParameter = (CodeParameter2)tvCodeElement; string parameterName = tvCodeParameter.Name; CodeTypeRef tvParameterType = tvCodeParameter.Type; vsCMParameterKind tvParameterKind = tvCodeParameter.ParameterKind; string parameterTypeAsString = tvParameterType.AsString; tvTempParameterList += "Dim " + parameterName + " As " + parameterTypeAsString + " = New " + parameterTypeAsString + "()" + Environment.NewLine + StringHelper.GetTabString(); if (tvParameterKind == vsCMParameterKind.vsCMParameterKindRef) { tvFunctionCall += parameterName; } else if (tvParameterKind == vsCMParameterKind.vsCMParameterKindOut) { tvFunctionCall += parameterName; } else if (tvParameterKind == vsCMParameterKind.vsCMParameterKindIn) { tvFunctionCall += parameterName; } else { tvFunctionCall += parameterName; } } tvFunctionCall = string.Format(tvFunctionCall + ")" + Environment.NewLine, ((CodeClass)originalClassCodeFuntion.Parent).Name, originalClassCodeFuntion.Name); } if (originalClassCodeFuntion.Type.TypeKind != vsCMTypeRef.vsCMTypeRefVoid) { tvFunctionReturn = string.Format(tvFunctionReturn, originalClassCodeFuntion.Type.AsString, originalClassCodeFuntion.Name); tvFunctionCall = tvFunctionReturn + tvFunctionCall; } TextPoint bodyStartingPoint = unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody); EditPoint boydEditPoint = bodyStartingPoint.CreateEditPoint(); if (!originalClassCodeFuntion.FunctionKind.ToString().Equals("vsCMFunctionConstructor")) { boydEditPoint.Insert("\t\t\t' TODO: Update variable/s' defaults to meet test needs" + Environment.NewLine); boydEditPoint.Insert(StringHelper.GetTabString() + tvTempParameterList + Environment.NewLine); boydEditPoint.Insert(StringHelper.GetTabString() + tvFunctionCall + Environment.NewLine); } if (originalClassCodeFuntion.Type.TypeKind != vsCMTypeRef.vsCMTypeRefVoid) { string stringHolder = "iv{0}Return"; stringHolder = string.Format(stringHolder, originalClassCodeFuntion.Name); //FIX ME (tabing) //boydEditPoint.Insert(string.Format("\t\t\tAssert.AreEqual({0}, default({1}));\r\n", stringHolder, originalClassCodeFuntion.Type.AsString)); } boydEditPoint.Insert(Environment.NewLine); boydEditPoint.Insert("\t\t\t'TODO: Update Assert to meet test needs" + Environment.NewLine); boydEditPoint.Insert("\t\t\t'Assert.AreEqual( , )" + Environment.NewLine); boydEditPoint.Insert("\t\t\t" + Environment.NewLine); boydEditPoint.Insert("\t\t\tThrow New Exception 'Not Implemented'" + Environment.NewLine); return(unitTestCodeFunction); }
/// <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); } }
protected static CodeElement GetActiveCodeElement(EditPoint selPoint, vsCMElement scope) { // get the element under the cursor CodeElement element = null; try { if (m_applicationObject.ActiveDocument.ProjectItem.FileCodeModel != null) { element = m_applicationObject.ActiveDocument.ProjectItem.FileCodeModel.CodeElementFromPoint(selPoint, scope); } } catch (System.Runtime.InteropServices.COMException) { element = null; } return element; }
/// <summary> /// Inserts regions per user settings. /// </summary> /// <param name="codeItems">The code items.</param> /// <param name="insertPoint">The default insertion point.</param> public void InsertRegions(IEnumerable <BaseCodeItem> codeItems, EditPoint insertPoint) { // Refresh and sort the code items. foreach (var codeItem in codeItems) { codeItem.RefreshCachedPositionAndName(); } codeItems = codeItems.OrderBy(x => x.StartOffset).ToList(); var regions = ComposeRegionsList(codeItems); var codeItemEnumerator = codeItems.GetEnumerator(); codeItemEnumerator.MoveNext(); EditPoint cursor = insertPoint.CreateEditPoint(); foreach (var region in regions) { // While the current code item is a region not in the list, advance to the next code item. var currentCodeItemAsRegion = codeItemEnumerator.Current as CodeItemRegion; while (currentCodeItemAsRegion != null && !regions.Contains(currentCodeItemAsRegion, _regionComparerByName)) { cursor = codeItemEnumerator.Current.EndPoint; codeItemEnumerator.MoveNext(); currentCodeItemAsRegion = codeItemEnumerator.Current as CodeItemRegion; } // If the current code item is this region, advance to the next code item and end this iteration. if (_regionComparerByName.Equals(currentCodeItemAsRegion, region)) { cursor = codeItemEnumerator.Current.EndPoint; codeItemEnumerator.MoveNext(); continue; } // Update the cursor position to the current code item. if (codeItemEnumerator.Current != null) { cursor = codeItemEnumerator.Current.StartPoint; } // If the current code item is a region, offset the position by 1 to workaround points not tracking for region types. if (currentCodeItemAsRegion != null) { cursor = cursor.CreateEditPoint(); currentCodeItemAsRegion.StartPoint.CharRight(); currentCodeItemAsRegion.EndPoint.CharRight(); } // Insert the #region tag cursor = InsertRegionTag(region, cursor); // Keep jumping forwards in code items as long as there's matches. while (CodeItemBelongsInRegion(codeItemEnumerator.Current, region)) { cursor = codeItemEnumerator.Current.EndPoint; codeItemEnumerator.MoveNext(); } // Insert the #endregion tag cursor = InsertEndRegionTag(region, cursor); // If the current code item is a region, reverse offset of the position. if (currentCodeItemAsRegion != null) { currentCodeItemAsRegion.StartPoint.CharLeft(); currentCodeItemAsRegion.EndPoint.CharLeft(); } } }
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); }
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 CheckAndAddAlias(string nameSpace, string className, string aliasName) { string resourceAlias1 = $"using {aliasName} = ", resourceAlias2 = $"global::{nameSpace}.{className}"; CodeElements elements = TextDocument.Parent.ProjectItem.FileCodeModel.CodeElements; CodeElement lastElement = null; bool isImport = false; #region find alias or last using/Import element (return if alias found) foreach (CodeElement element in elements) //not really fast but more safe { if (!isImport) { //find first using/import statement if (element.Kind == vsCMElement.vsCMElementImportStmt) { isImport = true; } } else { //using/import statement was available so find next NON using/import statement if (element.Kind != vsCMElement.vsCMElementImportStmt) { break; } } if (element.Kind == vsCMElement.vsCMElementOptionStmt) { //save last option statement lastElement = element; } else if (element.Kind == vsCMElement.vsCMElementImportStmt) { //save last using/import statement lastElement = element; //check if resource alias is already there CodeImport importElement = element as CodeImport; if ((importElement.Alias != null) && importElement.Alias.Equals(aliasName) && importElement.Namespace.Equals(resourceAlias2)) { return; } } } #endregion EditPoint insertPoint = null; if (lastElement == null) { insertPoint = TextDocument.CreateEditPoint(TextDocument.StartPoint); //beginning of text } else { //behind last element insertPoint = lastElement.EndPoint.CreateEditPoint(); insertPoint.LineDown(1); insertPoint.StartOfLine(); if (lastElement.Kind == vsCMElement.vsCMElementOptionStmt) { insertPoint.Insert(Environment.NewLine); } } resourceAlias2 += ";"; string alias = resourceAlias1 + resourceAlias2 + Environment.NewLine; insertPoint.Insert(alias); }
public static async Task ProcessAsync(Project project, Report report, bool addComment, Func <string, Task> writeAction) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var queue = new Queue <ProjectItem>(project.ProjectItems.Cast <ProjectItem>()); var subProjects = new List <Project>(); while (queue.Count > 0) { var item = queue.Dequeue(); if (item.ProjectItems != null) { foreach (var subItem in item.ProjectItems.Cast <ProjectItem>()) { queue.Enqueue(subItem); } } var kindGuid = Guid.Parse(item.Kind); if (kindGuid == VSConstants.GUID_ItemType_PhysicalFile) { if (item.FileCodeModel != null) { if (IsCSharpFile(item.FileCodeModel.Language)) { if (item.IsOpen && item.Document != null) { TextDocument editDoc = (TextDocument)item.Document.Object("TextDocument"); EditPoint objEditPt = editDoc.CreateEditPoint(); writeAction?.Invoke($"{item.Document.FullName}"); objEditPt.StartOfDocument(); item.Document.ReadOnly = false; if (addComment) { await AddCommentsAsync(objEditPt); } else { await RemoveCommentsAsync(objEditPt); } report.ProcessedItems += 1; report.ProcessedOpenedItems += 1; } else { for (short index = 0; index < item.FileCount; index++) { writeAction?.Invoke($"{item.FileNames[index]}"); if (item.IsOpen) { continue; } if (addComment) { AddComments(item.FileNames[index]); } else { RemoveComments(item.FileNames[index]); } report.ProcessedItems += 1; } } } } } if (kindGuid == ProjectItem) { subProjects.Add(item.SubProject); } } foreach (var subProject in subProjects) { await ProcessAsync(subProject, report, addComment, writeAction); } }
public static void Execute(ProjectItem projectItem) { var objTextDoc = (TextDocument)projectItem.Document.Object("TextDocument"); EditPoint editPoint = objTextDoc.StartPoint.CreateEditPoint(); editPoint.LineDown(); bool doEncountered = false; while (editPoint.LessThan(objTextDoc.EndPoint)) { editPoint.StartOfLine(); var start = editPoint.CreateEditPoint(); string previousLine = start.GetPreviousLineText(); string line = start.GetLineText(); string nextLine = start.GetNextLineText(); if (line.Trim() == "do") { doEncountered = true; } if (line.Trim().StartsWith("namespace ") && previousLine.EndsWith("</copyright>")) { start.StartOfLine(); start.Insert(Environment.NewLine); continue; } if (line.Trim().StartsWith("using ") && !line.Trim().StartsWith("using (") && !nextLine.Trim().StartsWith("using ") && !string.IsNullOrWhiteSpace(nextLine)) { start.EndOfLine(); start.Insert(Environment.NewLine); continue; } //if ((line.Trim() == "return" || line.TrimStart().StartsWith("return ")) // && !string.IsNullOrWhiteSpace(previousLine) // && previousLine.Trim() != "{" // && !previousLine.Trim().StartsWith("case ") // && !previousLine.Trim().StartsWith("default:") // && !previousLine.Trim().StartsWith(@"// ")) //{ // start.StartOfLine(); // start.Insert(Environment.NewLine); // continue; //} if (line.Trim() == "}" && !nextLine.Trim().StartsWith("else") && nextLine.Trim() != "}" && nextLine.Trim() != "};" && nextLine.Trim() != "});" && nextLine.Trim() != "}," && nextLine.Trim() != "finally" && nextLine.Trim() != "#endif" && !nextLine.Trim().StartsWith("catch (") && !nextLine.Trim().StartsWith("#endregion") && nextLine.Trim() != ("catch") && !(nextLine.Trim().StartsWith("while (") && doEncountered) && !string.IsNullOrWhiteSpace(nextLine)) { start.EndOfLine(); start.Insert(Environment.NewLine); continue; } if ((string.IsNullOrWhiteSpace(line) && string.IsNullOrWhiteSpace(previousLine)) || (string.IsNullOrWhiteSpace(line) && previousLine.Trim() == "{") || (string.IsNullOrWhiteSpace(line) && previousLine.TrimStart().StartsWith("using ") && nextLine.TrimStart().StartsWith("using "))) { start.DeleteCurrentLine(); continue; } if ((line.Trim() == "}" || line.Trim() == "{") && string.IsNullOrWhiteSpace(previousLine)) { start.DeletePreviousLine(); continue; } editPoint.LineDown(); } }
private bool Refactor(IList <CodeVariable> vars, IList <CodeVariable> disabledVars, string codeClassName, string languageGUID, CodeElements codeMembers, EditPoint insertLocation, out int gotoLine) { IList <CodeVariable> toDisable; IList <CodeProperty> props; IList <string> varNames; IList <string> propNames; // set invalid goto-line: gotoLine = -1; if (vars != null) { // get the language and a list of currently available properties: CodeModelLanguages language = CodeHelper.GetCodeLanguage(languageGUID); props = EditorHelper.GetList <CodeProperty>(codeMembers, vsCMElement.vsCMElementProperty); // remove the variables from the list for which the properties exist: FindExistingProperties(vars, props, language, out toDisable, false); // add additional disabled variables: if (disabledVars != null) { if (toDisable == null) { toDisable = disabledVars; } else { foreach (CodeVariable v in disabledVars) { if (!toDisable.Contains(v)) { toDisable.Add(v); } } } } if (cfgDialog == null) { cfgDialog = new PropertyRefactorForm(); cfgDialog.GeneratorOptions = PropertyGeneratorOptions.GetterAndSetter | PropertyGeneratorOptions.ForcePropertyPublic | PropertyGeneratorOptions.ForceVarDontChange | PropertyGeneratorOptions.SuppressComment; cfgDialog.RegionName = RegionName; } // show dialog with possibility to change: cfgDialog.InitializeInterface(vars, toDisable, language); if (cfgDialog.ShowDialog() == DialogResult.OK && cfgDialog.ReadInterface(out vars, out varNames, out propNames)) { // generate code based on user modifications: string code = GenerateSourceCodeOutput(codeClassName, vars, varNames, propNames, language, cfgDialog.GeneratorOptions, cfgDialog.RegionName); // insert code to the editor: if (!string.IsNullOrEmpty(code)) { insertLocation.ReplaceText(insertLocation, code, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat); // jump without selection to the insertion place: gotoLine = insertLocation.Line; return(true); } } } return(false); }
protected static string GetSelectedText(EditPoint selPoint) { return selPoint.GetText(selPoint.LineLength).Trim(); }
bool ICodeDomDesignerReload.ShouldReloadDesigner(CodeCompileUnit newTree) { if ((generatedMethods == null || generatedMethods.Count == 0) && (generatedFields == null || generatedFields.Count == 0)) { return(true); } Hashtable handlers = null; // now that we've got a parsed file, walk through each item that we created, and check // to see if it changed at all. // char[] splitChars = new char[] { ':' }; CodeTypeDeclaration codeType = null; if (generatedFields != null) { foreach (DictionaryEntry de in generatedFields) { string hashName = (string)de.Key; CodeMemberField oldField = de.Value as CodeMemberField; if (oldField == null) { continue; } // this string is in the format // <Type Name>:<Field Name> // string[] names = hashName.Split(splitChars); Debug.Assert(names.Length == 2, "Didn't get 2 items from the name hash string '" + hashName + "'"); CodeMemberField parsedField = FindMatchingMember(newTree, names[0], oldField, out codeType) as CodeMemberField; if (parsedField == null) { return(true); } } } if (generatedMethods != null) { foreach (DictionaryEntry de in generatedMethods) { string hashName = (string)de.Key; CodeMemberMethod oldMethod = de.Value as CodeMemberMethod; if (oldMethod == null) { continue; } // this string is in the format // <Type Name>:<Method Name>:<Parameter Count> string[] names = hashName.Split(splitChars); Debug.Assert(names.Length == 3, "Didn't get 3 items from the name hash string '" + hashName + "'"); CodeDomLoader.StartMark(); CodeMemberMethod parsedMethod = FindMatchingMember(newTree, names[0], oldMethod, out codeType) as CodeMemberMethod; CodeDomLoader.EndMark("Reload Parse II:" + oldMethod.Name); // if we have differing statment counts, don't even bother looking at code // if (parsedMethod == null) { return(true); } CodeElement vsCodeElement = parsedMethod.UserData[VsCodeDomParser.VsElementKey] as CodeElement; if (vsCodeElement == null) { return(true); } CodeDomLoader.StartMark(); EditPoint startPoint = vsCodeElement.StartPoint.CreateEditPoint(); string newCode = startPoint.GetText(vsCodeElement.EndPoint); CodeDomLoader.EndMark("GetCode from VS Element"); string oldCode = oldMethod.UserData[GeneratedCodeKey] as string; // okay, let's rock. if these are different, we need to reload // // sburke: binary compare if (oldCode != newCode) { return(true); } else { // add this to the list of things to generate next time in case we don't regenerate. // DictionaryEntry thisDe = de; thisDe.Value = parsedMethod; parsedMethod.UserData[GeneratedCodeKey] = oldCode; parsedMethod.UserData[VsCodeDomParser.VsGenerateStatementsKey] = VsCodeDomParser.VsGenerateStatementsKey; } // pick up the handlers from this class // if (handlers == null) { handlers = (Hashtable)codeType.UserData[VsCodeDomParser.VbHandlesClausesKey]; } } } if (IsVB) { if ((fullParseHandlers == null) != (handlers == null)) { return(true); } if (handlers != null) { // first, a quick check to see if our handlers have changed // string[] handlerNames = new string[handlers.Keys.Count]; handlers.Keys.CopyTo(handlerNames, 0); string[] lastHandlerHames = new string [fullParseHandlers.Count]; fullParseHandlers.Keys.CopyTo(lastHandlerHames, 0); Array.Sort(handlerNames, InvariantComparer.Default); Array.Sort(lastHandlerHames, InvariantComparer.Default); if (lastHandlerHames.Length != handlerNames.Length) { return(true); } for (int i = 0; i < handlerNames.Length; i++) { if (!handlerNames[i].Equals(lastHandlerHames[i])) { return(true); } } // handlers are all the same, make sure they point to the same members // foreach (DictionaryEntry de in fullParseHandlers) { CodeMemberMethod newHandler = handlers[de.Key] as CodeMemberMethod; if (newHandler == null) { return(true); } CodeMemberMethod oldHandler = de.Value as CodeMemberMethod; Debug.Assert(oldHandler != null, "Didn't get an old handler? How?"); if (newHandler.Name != oldHandler.Name || //newHandler.Attributes != oldHandler.Attributes || newHandler.ReturnType.BaseType != oldHandler.ReturnType.BaseType) { return(true); } if (newHandler.Parameters.Count == oldHandler.Parameters.Count) { // just to be sure, check the params. for (int i = 0; i < newHandler.Parameters.Count; i++) { if (newHandler.Parameters[i].Type.BaseType != newHandler.Parameters[i].Type.BaseType) { return(true); } } } else { return(true); } } } } return(false); }
public static void DoRemoveInvocationWithFilter(this CodeFunction codeFunction, string[] classNames, List <FluentAPIEntityNode> filter) { if (classNames == null) { return; } if (codeFunction == null) { return; } EditPoint editPoint = codeFunction.StartPoint.CreateEditPoint(); editPoint.SmartFormat(codeFunction.EndPoint); editPoint = codeFunction.StartPoint.CreateEditPoint(); string buff = editPoint.GetText(codeFunction.EndPoint); SyntaxTree tree = CSharpSyntaxTree.ParseText(buff); SyntaxNode root = tree.GetRoot(); if (root == null) { return; } MethodDeclarationSyntax methodDeclaration = root.GetOnModelCreatingParameterName("DbModelBuilder", "ModelBuilder", out string parameterName); if ((methodDeclaration == null) || string.IsNullOrEmpty(parameterName)) { return; } if (methodDeclaration.Body == null) { return; } List <TextSpan> spans = new List <TextSpan>(); foreach (StatementSyntax ss in methodDeclaration.Body.Statements) { if (ss.Kind() != SyntaxKind.ExpressionStatement) { continue; } ExpressionStatementSyntax expressionStatementSyntax = ss as ExpressionStatementSyntax; if (expressionStatementSyntax.Expression == null) { continue; } if (expressionStatementSyntax.Expression.Kind() != SyntaxKind.InvocationExpression) { continue; } InvocationExpressionSyntax invocationExpressionSyntax = expressionStatementSyntax.Expression as InvocationExpressionSyntax; if (!parameterName.Equals(invocationExpressionSyntax.InvocationExpressionRootName(classNames))) { continue; } FluentAPIEntityNode faen = expressionStatementSyntax.Expression.InvocationExpressionMethods(null); if (faen == null) { continue; } if (faen.Methods == null) { continue; } if (faen.IsSatisfiedTheFilter(filter)) { spans.Insert(0, expressionStatementSyntax.Span); } } foreach (TextSpan ts in spans) { buff = buff.Remove(ts.Start, ts.Length); // // the commented code does not work : ts.Start does not correctly point to begining of the operator //editPoint.CharRight(ts.Start); //editPoint.Delete(ts.Length); //editPoint.CharLeft(ts.Start); //if (codeFunction.ProjectItem != null) //{ // codeFunction.ProjectItem.Save(); //} } buff = buff.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine); editPoint = codeFunction.StartPoint.CreateEditPoint(); editPoint.Delete(codeFunction.EndPoint); editPoint.Insert(buff); if (codeFunction.ProjectItem != null) { codeFunction.ProjectItem.Save(); } }
/// <summary> /// Get and position EditPoint objects to include all of original text that is selected, plus surrounding text for complete lines of text /// </summary> /// <param name="document"></param> /// <param name="earlierPoint"></param> /// <param name="laterPoint"></param> public void GetEditPointsForLinesToCheck(TextDocument document, out EditPoint earlierPoint, out EditPoint laterPoint) { TextSelection selection = document.Selection; // Reorder selection points as needed if (selection.IsActiveEndGreater) { selection.SwapAnchor(); } // Get and position EditPoint objects to include all of original text that is selected, plus surrounding text for complete lines of text earlierPoint = selection.ActivePoint.CreateEditPoint(); laterPoint = selection.AnchorPoint.CreateEditPoint(); earlierPoint.StartOfLine(); laterPoint.LineDown(1); laterPoint.StartOfLine(); }
internal static bool IsCommentLine(EditPoint point) { return LineMatchesRegex(point, GetCommentRegex(point.Parent.Language)).Success; }
/// <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"); } } }
private static bool GetEditPointAtBeginningOfLine(IVsTextView textView, int lineIndex, out EditPoint editPoint) { IVsTextLines textLines; int hr = textView.GetBuffer(out textLines); if (hr == VSConstants.S_OK && textLines != null) { object editPointObject; hr = textLines.CreateEditPoint(lineIndex, 0, out editPointObject); if (hr == VSConstants.S_OK) { editPoint = editPointObject as EditPoint; return(editPoint != null); } } editPoint = null; return(false); }
public void insert_in_current(string value) { _tdoc.Selection.ActivePoint.CreateEditPoint().Insert(value); EditPoint p2 = _tdoc.EndPoint.CreateEditPoint(); }
/// <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> /// Evaluates an element into a codeblock /// </summary> /// <param name="parentElement">The parent element, containing the given element</param> /// <param name="element">The element to evaluate</param> /// <param name="newStartPoint">The starting point for the element</param> /// <returns>A CodeBlock derived from the Element with appropriate placement and access set</returns> private CodeBlock EvaluateBlock(CodeElement parentElement, CodeElement element, ref EditPoint newStartPoint) { CodeBlock currentBlock = null; ElementType blockType = GetType(element); bool blockStatic = GetElementIsStatic(element); bool blockConstant = GetElementIsConstant(element); string body = GetCodeBlockText(parentElement, element, out newStartPoint); ElementAccess blockAccess = GetAccess(element, blockConstant, blockStatic); int weight = GetWeight(element); currentBlock = new CodeBlock(blockAccess, blockType, element.Name, body); return(currentBlock); }
public override void Execute() { CodeClass codeClass = _target as CodeClass; // Determine which using sentence to add Project prjContainer = codeClass.ProjectItem.ContainingProject; ProjectItem constantsFolder = DteHelperEx.FindItemByName(prjContainer.ProjectItems, "Constants", false); string usingNamespace = constantsFolder == null ? GlobalUsingNamespace : LocalUsingNamespace; if (codeClass == null && !ReferenceUtil.HaveAClass(_target, out codeClass)) { return; } if (codeClass != null) { TextPoint tp = codeClass.StartPoint; EditPoint ep = tp.CreateEditPoint(); ep.StartOfDocument(); int lastUsing = -1; string keyword = string.Empty; string patternText = string.Empty; switch (codeClass.Language) { case CodeModelLanguageConstants.vsCMLanguageCSharp: keyword = "using"; patternText = String.Concat(keyword, " {0};"); break; case CodeModelLanguageConstants.vsCMLanguageVB: keyword = "Imports"; patternText = String.Concat(keyword, " {0}"); break; default: throw new NotSupportedException("Language not supported"); } //string usingText = String.Format("using {0}", usingNamespace); string usingText = String.Format(patternText, usingNamespace); while (!ep.AtEndOfDocument) { int length = ep.LineLength; string line = ep.GetText(ep.LineLength); if (line.Contains(usingText)) { return; } //if (line.StartsWith("using")) lastUsing = ep.Line; if (line.StartsWith(keyword)) { lastUsing = ep.Line; } ep.LineDown(1); } ep.StartOfDocument(); if (lastUsing > 0) { ep.LineDown(lastUsing); } ep.Insert(usingText); //ep.Insert(";"); ep.Insert(Environment.NewLine); if (ep.LineLength != 0) { ep.Insert(Environment.NewLine); } } }
/// <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 --"); } }
private void MenuItemCallback(object sender, EventArgs e, bool visitor) { try { // Return if I can't determine what application this is. DTE application = Workspaces.Help.GetApplication(); if (application == null) { return; } // Get active view and determine if it's a grammar file. var grammar_view = AntlrLanguagePackage.Instance.GetActiveView(); if (grammar_view == null) { return; } ITextCaret car = grammar_view.Caret; CaretPosition cp = car.Position; SnapshotPoint bp = cp.BufferPosition; int pos = bp.Position; ITextBuffer buffer = grammar_view.TextBuffer; var g4_file_path = buffer.GetFFN().Result; if (g4_file_path == null) { return; } IGrammarDescription grammar_description = LanguageServer.GrammarDescriptionFactory.Create(g4_file_path); if (!grammar_description.IsFileType(g4_file_path)) { return; } // Get name of base class for listener and visitor. These are generated by Antlr, // constructed from the name of the file. var grammar_name = Path.GetFileName(g4_file_path); grammar_name = Path.GetFileNameWithoutExtension(grammar_name); var listener_baseclass_name = visitor ? (grammar_name + "BaseVisitor") : (grammar_name + "BaseListener"); var listener_class_name = visitor ? ("My" + grammar_name + "Visitor") : ("My" + grammar_name + "Listener"); // In the current view, find the details of the Antlr symbol at the cursor. TextExtent extent = AntlrVSIX.Package.AntlrLanguagePackage.Instance.Navigator[grammar_view] .GetExtentOfWord(bp); SnapshotSpan span = extent.Span; AntlrLanguagePackage.Instance.Span = span; // Now, check for valid classification type. var cla = -1; bool can_gotovisitor = AntlrVSIX.Package.AntlrLanguagePackage.Instance.Aggregator[grammar_view].GetClassificationSpans(span).Where( classification => { var name = classification.ClassificationType.Classification; if (!grammar_description.InverseMap.TryGetValue(name, out int c)) { return(false); } cla = c; return(grammar_description.CanGotovisitor[cla]); }).Any(); if (!can_gotovisitor) { return; } // Find defining occurrence. List <Antlr4.Runtime.Tree.TerminalNodeImpl> where = new List <Antlr4.Runtime.Tree.TerminalNodeImpl>(); List <ParserDetails> where_details = new List <ParserDetails>(); Antlr4.Runtime.Tree.TerminalNodeImpl token = null; foreach (var kvp in ParserDetailsFactory.AllParserDetails) { string file_name = kvp.Key; ParserDetails details = kvp.Value; { var it = details.Defs.Where( (t) => t.Value == cla && t.Key.Symbol.Text == span.GetText()).Select(t => t.Key); where.AddRange(it); foreach (var i in it) { where_details.Add(details); } } } if (where.Any()) { token = where.First(); } else { System.Windows.Forms.MessageBox.Show( "Symbol '" + span.GetText() + "' definer not found."); return; } // Get the symbol name as a string. var symbol_name = token.Symbol.Text; var capitalized_symbol_name = Capitalized(symbol_name); // Parse all the C# files in the solution. Dictionary <string, SyntaxTree> trees = new Dictionary <string, SyntaxTree>(); foreach (var item in DteExtensions.SolutionFiles(application)) { string file_name = item.Name; if (file_name != null) { string prefix = file_name.TrimSuffix(".cs"); if (prefix == file_name) { continue; } try { object prop = item.Properties.Item("FullPath").Value; string ffn = (string)prop; StreamReader sr = new StreamReader(ffn); string code = sr.ReadToEnd(); SyntaxTree tree = CSharpSyntaxTree.ParseText(code); trees[ffn] = tree; } catch (Exception) { } } } // Find all occurrences of visitor class. List <ClassDeclarationSyntax> found_class = new List <ClassDeclarationSyntax>(); string class_file_path = null; try { foreach (var kvp in trees) { var file_name = kvp.Key; var tree = kvp.Value; // Look for IParseTreeListener or IParseTreeVisitor classes. var root = (CompilationUnitSyntax)tree.GetRoot(); if (root == null) { continue; } foreach (var nm in root.Members) { var namespace_member = nm as NamespaceDeclarationSyntax; if (namespace_member == null) { continue; } foreach (var cm in namespace_member.Members) { var class_member = cm as ClassDeclarationSyntax; if (class_member == null) { continue; } var bls = class_member.BaseList; if (bls == null) { continue; } var types = bls.Types; Regex reg = new Regex("[<].+[>]"); foreach (var type in types) { var s = type.ToString(); s = reg.Replace(s, ""); if (s.ToString() == listener_baseclass_name) { // Found the right class. found_class.Add(class_member); throw new Exception(); } } } } } } catch { } if (found_class.Count == 0) { if (!global::Options.POptions.GetBoolean("GenerateVisitorListener")) { return; } // Look in grammar directory for any C# files. string name_space = null; string ffn = Path.GetFullPath(g4_file_path); ffn = Path.GetDirectoryName(ffn); foreach (var i in DteExtensions.SolutionFiles(application)) { string file_name = i.Name; if (file_name != null) { string prefix = file_name.TrimSuffix(".cs"); if (prefix == file_name) { continue; } try { object prop = i.Properties.Item("FullPath").Value; string ffncs = (string)prop; // Look for namespace. var t = trees[ffncs]; if (t == null) { continue; } var root = t.GetCompilationUnitRoot(); foreach (var nm in root.Members) { var namespace_member = nm as NamespaceDeclarationSyntax; if (namespace_member == null) { continue; } name_space = namespace_member.Name.ToString(); break; } } catch (Exception) { } } } if (name_space == null) { name_space = "Generated"; } // Create class. string clazz = visitor ? $@" using System; using System.Collections.Generic; using System.Text; namespace {name_space} {{ class {listener_class_name}<Result> : {listener_baseclass_name}<Result> {{ //public override Result VisitA([NotNull] A3Parser.AContext context) //{{ // return VisitChildren(context); //}} }} }} " : $@" using System; using System.Collections.Generic; using System.Text; namespace {name_space} {{ class {listener_class_name} : {listener_baseclass_name} {{ //public override void EnterA(A3Parser.AContext context) //{{ // base.EnterA(context); //}} //public override void ExitA(A3Parser.AContext context) //{{ // base.ExitA(context); //}} }} }} "; class_file_path = ffn + Path.DirectorySeparatorChar + listener_class_name + ".cs"; System.IO.File.WriteAllText(class_file_path, clazz); var item = ProjectHelpers.GetSelectedItem(); string folder = FindFolder(item); if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) { return; } var file = new FileInfo(class_file_path); var selectedItem = Workspaces.Workspace.Instance.FindDocument(class_file_path); if (selectedItem == null) { //var selectedProject = item as Project; //Project project = selectedItem?.ContainingProject ?? selectedProject ?? null; //var projectItem = project.AddFileToProject(file); } // Redo parse. try { StreamReader sr = new StreamReader(class_file_path); string code = sr.ReadToEnd(); SyntaxTree tree = CSharpSyntaxTree.ParseText(code); trees[class_file_path] = tree; } catch (Exception) { } // Redo find class. try { var tree = trees[class_file_path]; var save = class_file_path; class_file_path = null; // Look for IParseTreeListener or IParseTreeVisitor classes. var root = (CompilationUnitSyntax)tree.GetRoot(); foreach (var nm in root.Members) { var namespace_member = nm as NamespaceDeclarationSyntax; if (namespace_member == null) { continue; } foreach (var cm in namespace_member.Members) { var class_member = cm as ClassDeclarationSyntax; if (class_member == null) { continue; } var bls = class_member.BaseList; if (bls == null) { continue; } var types = bls.Types; Regex reg = new Regex("[<].+[>]"); foreach (var type in types) { var s = type.ToString(); s = reg.Replace(s, ""); if (s.ToString() == listener_baseclass_name) { // Found the right class. found_class.Add(class_member); throw new Exception(); } } } } } catch { } } // Look for enter or exit method for symbol. MethodDeclarationSyntax found_member = null; var ctl = CtrlKeyState.GetStateForView(grammar_view).Enabled; var capitalized_member_name = ""; if (visitor) { capitalized_member_name = "Visit" + capitalized_symbol_name; } else if (ctl) { capitalized_member_name = "Exit" + capitalized_symbol_name; } else { capitalized_member_name = "Enter" + capitalized_symbol_name; } var capitalized_grammar_name = Capitalized(grammar_name); try { foreach (var fc in found_class) { foreach (var me in fc.Members) { var method_member = me as MethodDeclarationSyntax; if (method_member == null) { continue; } if (method_member.Identifier.ValueText.ToLower() == capitalized_member_name.ToLower()) { found_member = method_member; throw new Exception(); } } } } catch { } if (found_member == null) { if (!global::Options.POptions.GetBoolean("GenerateVisitorListener")) { return; } // Find point for edit. var fc = found_class.First(); var here = fc.OpenBraceToken; var spn = here.FullSpan; var end = spn.End; IVsTextView vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); if (vstv == null) { IVsTextViewExtensions.ShowFrame(class_file_path); vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); } IWpfTextView wpftv = vstv.GetIWpfTextView(); if (wpftv == null) { return; } ITextSnapshot cc = wpftv.TextBuffer.CurrentSnapshot; var res = vstv.GetBuffer(out IVsTextLines ppBuffer); var nss = new SnapshotSpan(cc, spn.End + 1, 0); var txt_span = nss.Span; int line_number; int colum_number; vstv.GetLineAndColumn(txt_span.Start, out line_number, out colum_number); res = ppBuffer.CreateEditPoint(line_number, colum_number, out object ppEditPoint); EditPoint editPoint = ppEditPoint as EditPoint; // Create class. string member = visitor ? $@" public override Result {capitalized_member_name}([NotNull] {capitalized_grammar_name}Parser.{capitalized_symbol_name}Context context) {{ return VisitChildren(context); }} " : $@" public override void {capitalized_member_name}({capitalized_grammar_name}Parser.{capitalized_symbol_name}Context context) {{ base.{capitalized_member_name}(context); }} "; editPoint.Insert(member); // Redo parse. try { vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); if (vstv == null) { IVsTextViewExtensions.ShowFrame(class_file_path); vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); } var text_buffer = vstv.GetITextBuffer(); var code = text_buffer.GetBufferText(); SyntaxTree tree = CSharpSyntaxTree.ParseText(code); trees[class_file_path] = tree; } catch (Exception) { } // Redo find class. try { var tree = trees[class_file_path]; var save = class_file_path; class_file_path = null; // Look for IParseTreeListener or IParseTreeVisitor classes. var root = (CompilationUnitSyntax)tree.GetRoot(); foreach (var nm in root.Members) { var namespace_member = nm as NamespaceDeclarationSyntax; if (namespace_member == null) { continue; } foreach (var cm in namespace_member.Members) { var class_member = cm as ClassDeclarationSyntax; if (class_member == null) { continue; } var bls = class_member.BaseList; if (bls == null) { continue; } var types = bls.Types; Regex reg = new Regex("[<].+[>]"); foreach (var type in types) { var s = type.ToString(); s = reg.Replace(s, ""); if (s.ToString() == listener_baseclass_name) { // Found the right class. found_class.Add(class_member); class_file_path = save; throw new Exception(); } } } } } catch { } try { foreach (var fcc in found_class) { foreach (var me in fcc.Members) { var method_member = me as MethodDeclarationSyntax; if (method_member == null) { continue; } if (method_member.Identifier.ValueText.ToLower() == capitalized_member_name.ToLower()) { found_member = method_member; throw new Exception(); } } } } catch { } } { // Open to this line in editor. IVsTextView vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); { IVsTextViewExtensions.ShowFrame(class_file_path); vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); } IWpfTextView wpftv = vstv.GetIWpfTextView(); if (wpftv == null) { return; } int line_number; int colum_number; var txt_span = found_member.Identifier.Span; vstv.GetLineAndColumn(txt_span.Start, out line_number, out colum_number); // Create new span in the appropriate view. ITextSnapshot cc = wpftv.TextBuffer.CurrentSnapshot; SnapshotSpan ss = new SnapshotSpan(cc, txt_span.Start, txt_span.Length); SnapshotPoint sp = ss.Start; // Put cursor on symbol. wpftv.Caret.MoveTo(sp); // This sets cursor, bot does not center. // Center on cursor. //wpftv.Caret.EnsureVisible(); // This works, sort of. It moves the scroll bar, but it does not CENTER! Does not really work! if (line_number > 0) { vstv.CenterLines(line_number - 1, 2); } else { vstv.CenterLines(line_number, 1); } return; } } catch (Exception exception) { Logger.Log.Notify(exception.StackTrace); } }
/// <summary> /// Inserts a #region tag for the specified region preceding the specified start point. /// </summary> /// <param name="region">The region to start.</param> /// <param name="startPoint">The starting point.</param> /// <returns>The updated cursor.</returns> private EditPoint InsertRegionTag(CodeItemRegion region, EditPoint startPoint) { var cursor = startPoint.CreateEditPoint(); // If the cursor is not preceeded only by whitespace, insert a new line. var firstNonWhitespaceIndex = cursor.GetLine().TakeWhile(char.IsWhiteSpace).Count(); if (cursor.DisplayColumn > firstNonWhitespaceIndex + 1) { cursor.Insert(Environment.NewLine); } cursor.Insert(string.Format("#region {0}{1}", region.Name, Environment.NewLine)); startPoint.SmartFormat(cursor); region.StartPoint = cursor.CreateEditPoint(); region.StartPoint.LineUp(); region.StartPoint.StartOfLine(); var regionWrapper = new[] { region }; _insertBlankLinePaddingLogic.InsertPaddingBeforeRegionTags(regionWrapper); _insertBlankLinePaddingLogic.InsertPaddingAfterRegionTags(regionWrapper); return cursor; }
protected void onPaneUpdated(OutputWindowPane pane) { if (pane == null || pane.Guid == null) { return; } TextDocument textD; try { textD = pane.TextDocument; } catch (System.Runtime.InteropServices.COMException ex) { Log.Debug("notifyRaw: COMException - '{0}'", ex.Message); return; } int countLines = textD.EndPoint.Line; if (countLines <= 1 || countLines - getPrevCountLines(pane.Guid) < 1) { return; } if (!dataList.ContainsKey(pane.Guid)) { dataList[pane.Guid] = new ConcurrentQueue <string>(); } EditPoint point = textD.StartPoint.CreateEditPoint(); // text between Start (inclusive) and ExclusiveEnd (exclusive) dataList[pane.Guid].Enqueue(point.GetLines(getPrevCountLines(pane.Guid), countLines)); // e.g. first line: 1, 2 setPrevCountLines(countLines, pane.Guid); //TODO: fix me. Prevent Duplicate Data / bug with OutputWindowPane if (tUpdated == null || tUpdated.ThreadState == ThreadState.Unstarted || tUpdated.ThreadState == ThreadState.Stopped) { tUpdated = new System.Threading.Thread(() => { if (pane == null) { return; } try { notifyRaw(pane.Guid, pane.Name); } catch (Exception ex) { Log.Debug("notifyRaw: failed '{0}'", ex.Message); } }); try { tUpdated.Start(); } catch (Exception ex) { // ThreadStateException, OutOfMemoryException Log.Debug("notifyRaw: can't start '{0}'", ex.Message); } } }
//If the result is true this method also sets the currently active edit point. public bool EditPointsHitTest(Point pt) { if (this.EditPoints.Count > 0) { foreach (EditPoint editPoint in this.EditPoints) { if (DesignerGeometryHelper.DistanceBetweenPoints(pt, editPoint.Location) <= EditPointHitTestRadius) { this.activeEditPoint = editPoint; return true; } } } return false; }
private void ReplaceText(PasteCleaner cleaner, TextDocument doc, EditPoint start, string text) { string clean = cleaner.Clean(); _dte.UndoContext.Open("Paste FixR"); // Insert start.ReplaceText(text.Replace("\n", string.Empty).Length, clean, 0); //start.Insert(clean); // Format doc.Selection.MoveToPoint(start, true); FormatSelection(); _textView.Selection.Clear(); _dte.UndoContext.Close(); }
//The Connector editor is to be destroyed. Remove the adorners on the editor. activeEditPoint=null sets BeingEdited property to false. public void Remove() { this.activeEditPoint = null; RemoveAdorners(); this.EditPoints.Clear(); this.Connector.IsSelected = false; // Restore the IsHitTestVisible property this.SetIsHitTestVisibleForOverlappingStartDots(true); this.Connector = null; this.parentPanel = null; }
protected static CodeElement SmartGetActiveCodeElement(EditPoint selPoint) { var list = new vsCMElement[] { vsCMElement.vsCMElementFunction, vsCMElement.vsCMElementClass }; CodeElement element = null; foreach (vsCMElement elem in list) { element = GetActiveCodeElement(selPoint, elem); if (element != null) break; } return element; }
void UpdateEditPoints(Point newPoint) { if (this.editPoints.Count < 2 || this.editPoints[0].Type != EditPoint.EditPointTypes.ConnectionEditPoint || this.editPoints[this.editPoints.Count - 1].Type != EditPoint.EditPointTypes.ConnectionEditPoint) { Fx.Assert(false, "EditPoints are invalid"); return; } if (this.activeEditPoint != null) { int activeEditPointIndex = this.editPoints.IndexOf(this.activeEditPoint); EditPoint previous = (activeEditPointIndex > 0) ? this.editPoints[activeEditPointIndex - 1] : null; EditPoint next = (activeEditPointIndex < this.editPoints.Count - 1) ? this.editPoints[activeEditPointIndex + 1] : null; //Note that extra edit points are only added if we are connected to connection point if (previous != null && previous.Type == EditPoint.EditPointTypes.ConnectionEditPoint) { double slopeOfLine = DesignerGeometryHelper.SlopeOfLineSegment(previous.Location, this.activeEditPoint.Location); Orientation orientation = (Math.Abs(slopeOfLine) < 1) ? Orientation.Horizontal : Orientation.Vertical; int editPointOffset = Convert.ToInt32(DesignerGeometryHelper.DistanceBetweenPoints(previous.Location, (next != null) ? next.Location : this.activeEditPoint.Location)) / 4; if (orientation == Orientation.Horizontal) { editPointOffset *= (previous.Location.X < this.activeEditPoint.Location.X) ? 1 : -1; } else { editPointOffset *= (previous.Location.Y < this.activeEditPoint.Location.Y) ? 1 : -1; } activeEditPointIndex = this.editPoints.IndexOf(this.activeEditPoint); Point editPointLocation = (orientation == Orientation.Horizontal) ? new Point(previous.Location.X + editPointOffset, previous.Location.Y) : new Point(previous.Location.X, previous.Location.Y + editPointOffset); previous = new EditPoint(EditPoint.EditPointTypes.MultiSegmentEditPoint, editPointLocation); this.editPoints.InsertRange(activeEditPointIndex, new EditPoint[] { new EditPoint(EditPoint.EditPointTypes.MultiSegmentEditPoint, editPointLocation), previous }); } if (next != null && next.Type == EditPoint.EditPointTypes.ConnectionEditPoint) { double slopeOfLine = DesignerGeometryHelper.SlopeOfLineSegment(this.activeEditPoint.Location, next.Location); Orientation orientation = (Math.Abs(slopeOfLine) < 1) ? Orientation.Horizontal : Orientation.Vertical; int editPointOffset = Convert.ToInt32(DesignerGeometryHelper.DistanceBetweenPoints((previous != null) ? previous.Location : this.activeEditPoint.Location, next.Location)) / 4; if (orientation == Orientation.Horizontal) { editPointOffset *= (this.activeEditPoint.Location.X < next.Location.X) ? -1 : 1; } else { editPointOffset *= (this.activeEditPoint.Location.Y < next.Location.Y) ? -1 : 1; } activeEditPointIndex = this.editPoints.IndexOf(this.activeEditPoint); Point editPointLocation = (orientation == Orientation.Horizontal) ? new Point(next.Location.X + editPointOffset, next.Location.Y) : new Point(next.Location.X, next.Location.Y + editPointOffset); next = new EditPoint(EditPoint.EditPointTypes.MultiSegmentEditPoint, editPointLocation); this.editPoints.InsertRange(activeEditPointIndex + 1, new EditPoint[] { next, new EditPoint(EditPoint.EditPointTypes.MultiSegmentEditPoint, editPointLocation) }); } if (this.activeEditPoint.Type == EditPoint.EditPointTypes.ConnectionEditPoint) { Fx.Assert(this.editPoints[0].Type == EditPoint.EditPointTypes.ConnectionEditPoint, "EditPoint type is wrong."); Fx.Assert(this.editPoints[editPoints.Count - 1].Type == EditPoint.EditPointTypes.ConnectionEditPoint, "EditPoint type is wrong."); this.activeEditPoint.Location = newPoint; Fx.Assert(this.editPoints.Count > 0, "Some edit point should exist"); ConnectionPoint targetConnPt = null; Point[] points = null; Point begin = this.editPoints[0].Location; Point end = this.editPoints[this.editPoints.Count - 1].Location; if (typeof(ConnectionPointsAdorner).IsAssignableFrom(Mouse.DirectlyOver.GetType())) { ConnectionPointsAdorner connPtsAdorner = Mouse.DirectlyOver as ConnectionPointsAdorner; targetConnPt = FreeFormPanel.ConnectionPointHitTest(newPoint, connPtsAdorner); } if (activeEditPointIndex == 0) { // We are dragging the source point of a connector. ConnectionPoint destConnPt = FreeFormPanel.GetDestinationConnectionPoint(this.editedConnector); if (targetConnPt != null) { points = ConnectorRouter.Route(parentPanel, targetConnPt, destConnPt); this.activeEditPoint.Location = targetConnPt.Location; } else { points = ConnectorRouter.Route(parentPanel, begin, destConnPt); } } else { // We are dragging the destination point of a connector. ConnectionPoint srcConnPt = FreeFormPanel.GetSourceConnectionPoint(this.editedConnector); if (targetConnPt != null) { points = ConnectorRouter.Route(parentPanel, srcConnPt, targetConnPt); this.activeEditPoint.Location = targetConnPt.Location; } else { points = ConnectorRouter.Route(parentPanel, srcConnPt, end); } } //When we start editing the end point we need to clear the slate and start over List<EditPoint> newEditPoints = new List<EditPoint>(); if (points != null && points.Length > 1) { RemoveEditPoints(EditPoint.EditPointTypes.MultiSegmentEditPoint); for (int i = 1; i < points.Length - 1; ++i) { newEditPoints.Add(new EditPoint(EditPoint.EditPointTypes.MultiSegmentEditPoint, points[i])); } this.editPoints.InsertRange(1, newEditPoints.ToArray()); } } else if (this.activeEditPoint.Type == EditPoint.EditPointTypes.MultiSegmentEditPoint) { if (previous != null && previous.Type != EditPoint.EditPointTypes.ConnectionEditPoint && next != null && next.Type != EditPoint.EditPointTypes.ConnectionEditPoint) { //Update the previous point double slopeOfLine = DesignerGeometryHelper.SlopeOfLineSegment(previous.Location, this.activeEditPoint.Location); Orientation orientation = (Math.Abs(slopeOfLine) < 1) ? Orientation.Horizontal : Orientation.Vertical; previous.Location = (orientation == Orientation.Horizontal) ? new Point(previous.Location.X, newPoint.Y) : new Point(newPoint.X, previous.Location.Y); //Update the next point slopeOfLine = DesignerGeometryHelper.SlopeOfLineSegment(this.activeEditPoint.Location, next.Location); orientation = (Math.Abs(slopeOfLine) < 1) ? Orientation.Horizontal : Orientation.Vertical; next.Location = (orientation == Orientation.Horizontal) ? new Point(next.Location.X, newPoint.Y) : new Point(newPoint.X, next.Location.Y); //Update the current point this.activeEditPoint.Location = newPoint; } else { Fx.Assert(false, "Should not be here. UpdateEditPoints failed."); } } } // Remove all the redundant edit points RemoveCoincidingEditPoints(); bool validEditPoints = ValidateEditPoints(); Fx.Assert(validEditPoints, "Validating EditPoints failed."); }
/// <summary> /// Inserts regions per user settings. /// </summary> /// <param name="codeItems">The code items.</param> /// <param name="insertPoint">The default insertion point.</param> public void InsertRegions(IEnumerable<BaseCodeItem> codeItems, EditPoint insertPoint) { // Refresh and sort the code items. foreach (var codeItem in codeItems) { codeItem.RefreshCachedPositionAndName(); } codeItems = codeItems.OrderBy(x => x.StartOffset).ToList(); var regions = ComposeRegionsList(codeItems); var codeItemEnumerator = codeItems.GetEnumerator(); codeItemEnumerator.MoveNext(); EditPoint cursor = insertPoint.CreateEditPoint(); foreach (var region in regions) { // While the current code item is a region not in the list, advance to the next code item. var currentCodeItemAsRegion = codeItemEnumerator.Current as CodeItemRegion; while (currentCodeItemAsRegion != null && !regions.Contains(currentCodeItemAsRegion, _regionComparerByName)) { cursor = codeItemEnumerator.Current.EndPoint; codeItemEnumerator.MoveNext(); currentCodeItemAsRegion = codeItemEnumerator.Current as CodeItemRegion; } // If the current code item is this region, advance to the next code item and end this iteration. if (_regionComparerByName.Equals(currentCodeItemAsRegion, region)) { cursor = codeItemEnumerator.Current.EndPoint; codeItemEnumerator.MoveNext(); continue; } // Update the cursor position to the current code item. if (codeItemEnumerator.Current != null) { cursor = codeItemEnumerator.Current.StartPoint; } // If the current code item is a region, offset the position by 1 to workaround points not tracking for region types. if (currentCodeItemAsRegion != null) { cursor = cursor.CreateEditPoint(); currentCodeItemAsRegion.StartPoint.CharRight(); currentCodeItemAsRegion.EndPoint.CharRight(); } // Insert the #region tag cursor = InsertRegionTag(region, cursor); // Keep jumping forwards in code items as long as there's matches. while (CodeItemBelongsInRegion(codeItemEnumerator.Current, region)) { cursor = codeItemEnumerator.Current.EndPoint; codeItemEnumerator.MoveNext(); } // Insert the #endregion tag cursor = InsertEndRegionTag(region, cursor); // If the current code item is a region, reverse offset of the position. if (currentCodeItemAsRegion != null) { currentCodeItemAsRegion.StartPoint.CharLeft(); currentCodeItemAsRegion.EndPoint.CharLeft(); } } }
public override CodeFunction GenerateTest(CodeClass unitTestCodeClass, CodeProperty originalClassCodeProperty) { vsCMFunction functionKind = vsCMFunction.vsCMFunctionFunction; object functionType = null; functionKind = vsCMFunction.vsCMFunctionSub; functionType = vsCMTypeRef.vsCMTypeRefVoid; string nextAvailableName = originalClassCodeProperty.Name; if (!CodeSelectionHandler.CanGenerateHandleCodeFunction(unitTestCodeClass, nextAvailableName)) { nextAvailableName = GetNextAvailableCopyName(unitTestCodeClass, ref nextAvailableName, unitTestCodeClass.ProjectItem.ContainingProject); } CodeFunction unitTestCodeFunction = unitTestCodeClass.AddFunction( nextAvailableName, functionKind, functionType, -1, originalClassCodeProperty.Access, -1); unitTestCodeFunction.AddAttribute("NUnit.Framework.Test", "", -1); try { unitTestCodeFunction.Comment = originalClassCodeProperty.Comment; unitTestCodeFunction.DocComment = originalClassCodeProperty.DocComment; } catch (Exception ex) { Logger.LogException(ex); //ignore } TextPoint bodyStartingPoint = unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody); EditPoint boydEditPoint = bodyStartingPoint.CreateEditPoint(); //Stop here if not read-write type property now... if (originalClassCodeProperty.Setter == null) { boydEditPoint = bodyStartingPoint.CreateEditPoint(); boydEditPoint.Insert(StringHelper.GetTabString() + "' Property is not read-write please add your own code here." + Environment.NewLine); return(unitTestCodeFunction); } string tvFunctionCallTemplate = string.Empty; // "iv{0}Type.{1} = default({2});"; tvFunctionCallTemplate = "iv{0}Type.{1} = New {2}()" + Environment.NewLine; string tvFunctionCall = tvFunctionCallTemplate; CodeTypeRef tvPropertyType = originalClassCodeProperty.Type; string tvPropertyTypeAsString = tvPropertyType.AsString; tvFunctionCall = string.Format(tvFunctionCall, ((CodeClass)originalClassCodeProperty.Parent).Name, originalClassCodeProperty.Name, tvPropertyTypeAsString); bodyStartingPoint = unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody); boydEditPoint = bodyStartingPoint.CreateEditPoint(); //FIX ME (tabing) boydEditPoint.Insert(StringHelper.GetTabString() + tvFunctionCall + Environment.NewLine); //FIX ME (tabbing) string tvTempString = string.Empty; // "iv{0}Type.{1}, default({2})"; tvTempString = "iv{0}Type.{1}, New {2}()"; tvTempString = string.Format(tvTempString, ((CodeClass)originalClassCodeProperty.Parent).Name, originalClassCodeProperty.Name, tvPropertyTypeAsString); boydEditPoint.Insert(Environment.NewLine); boydEditPoint.Insert("\t\t\t'TODO: Update Assert to meet test needs" + Environment.NewLine); boydEditPoint.Insert("\t\t\t'Assert.AreEqual(" + tvTempString + ")" + Environment.NewLine); boydEditPoint.Insert("\t\t\t" + Environment.NewLine); boydEditPoint.Insert("\t\t\tThrow New Exception 'Not Implemented'" + Environment.NewLine); return(unitTestCodeFunction); }
private static bool GetEditPointAtBeginningOfLine(IVsTextView textView, int lineIndex, out EditPoint editPoint) { IVsTextLines textLines; int hr = textView.GetBuffer(out textLines); if (hr == VSConstants.S_OK && textLines != null) { object editPointObject; hr = textLines.CreateEditPoint(lineIndex, 0, out editPointObject); if (hr == VSConstants.S_OK) { editPoint = editPointObject as EditPoint; return editPoint != null; } } editPoint = null; return false; }
void UpdateEditPoints(Point newPoint) { if (this.editPoints.Count < 2 || this.editPoints[0].Type != EditPoint.EditPointTypes.ConnectionEditPoint || this.editPoints[this.editPoints.Count - 1].Type != EditPoint.EditPointTypes.ConnectionEditPoint) { Debug.Assert(false, "EditPoints are invalid"); return; } if (this.activeEditPoint != null) { int activeEditPointIndex = this.editPoints.IndexOf(this.activeEditPoint); EditPoint previous = (activeEditPointIndex > 0) ? this.editPoints[activeEditPointIndex - 1] : null; EditPoint next = (activeEditPointIndex < this.editPoints.Count - 1) ? this.editPoints[activeEditPointIndex + 1] : null; //Note that extra edit points are only added if we are connected to connection point if (previous != null && previous.Type == EditPoint.EditPointTypes.ConnectionEditPoint) { double slopeOfLine = DesignerGeometryHelper.SlopeOfLineSegment(previous.Location, this.activeEditPoint.Location); Orientation orientation = (Math.Abs(slopeOfLine) < 1) ? Orientation.Horizontal : Orientation.Vertical; int editPointOffset = Convert.ToInt32(DesignerGeometryHelper.DistanceBetweenPoints(previous.Location, (next != null) ? next.Location : this.activeEditPoint.Location)) / 4; if (orientation == Orientation.Horizontal) { editPointOffset *= (previous.Location.X < this.activeEditPoint.Location.X) ? 1 : -1; } else { editPointOffset *= (previous.Location.Y < this.activeEditPoint.Location.Y) ? 1 : -1; } activeEditPointIndex = this.editPoints.IndexOf(this.activeEditPoint); Point editPointLocation = (orientation == Orientation.Horizontal) ? new Point(previous.Location.X + editPointOffset, previous.Location.Y) : new Point(previous.Location.X, previous.Location.Y + editPointOffset); previous = new EditPoint(EditPoint.EditPointTypes.MultiSegmentEditPoint, editPointLocation); this.editPoints.InsertRange(activeEditPointIndex, new EditPoint[] { new EditPoint(EditPoint.EditPointTypes.MultiSegmentEditPoint, editPointLocation), previous }); } if (next != null && next.Type == EditPoint.EditPointTypes.ConnectionEditPoint) { double slopeOfLine = DesignerGeometryHelper.SlopeOfLineSegment(this.activeEditPoint.Location, next.Location); Orientation orientation = (Math.Abs(slopeOfLine) < 1) ? Orientation.Horizontal : Orientation.Vertical; int editPointOffset = Convert.ToInt32(DesignerGeometryHelper.DistanceBetweenPoints((previous != null) ? previous.Location : this.activeEditPoint.Location, next.Location)) / 4; if (orientation == Orientation.Horizontal) { editPointOffset *= (this.activeEditPoint.Location.X < next.Location.X) ? -1 : 1; } else { editPointOffset *= (this.activeEditPoint.Location.Y < next.Location.Y) ? -1 : 1; } activeEditPointIndex = this.editPoints.IndexOf(this.activeEditPoint); Point editPointLocation = (orientation == Orientation.Horizontal) ? new Point(next.Location.X + editPointOffset, next.Location.Y) : new Point(next.Location.X, next.Location.Y + editPointOffset); next = new EditPoint(EditPoint.EditPointTypes.MultiSegmentEditPoint, editPointLocation); this.editPoints.InsertRange(activeEditPointIndex + 1, new EditPoint[] { next, new EditPoint(EditPoint.EditPointTypes.MultiSegmentEditPoint, editPointLocation) }); } if (this.activeEditPoint.Type == EditPoint.EditPointTypes.ConnectionEditPoint) { Debug.Assert(this.editPoints[0].Type == EditPoint.EditPointTypes.ConnectionEditPoint, "EditPoint type is wrong."); Debug.Assert(this.editPoints[editPoints.Count - 1].Type == EditPoint.EditPointTypes.ConnectionEditPoint, "EditPoint type is wrong."); this.activeEditPoint.Location = newPoint; Point begin, end; Debug.Assert(this.editPoints.Count > 0, "Some edit point should exist"); begin = this.editPoints[0].Location; end = this.editPoints[this.editPoints.Count - 1].Location; //When we start editing the end point we need to clear the slate and start over List <EditPoint> newEditPoints = new List <EditPoint>(); Point[] points = ConnectorRouter.Route(parentPanel, begin, end); if (points != null && points.Length > 1) { RemoveEditPoints(EditPoint.EditPointTypes.MultiSegmentEditPoint); for (int i = 1; i < points.Length - 1; ++i) { newEditPoints.Add(new EditPoint(EditPoint.EditPointTypes.MultiSegmentEditPoint, points[i])); } this.editPoints.InsertRange(1, newEditPoints.ToArray()); } } else if (this.activeEditPoint.Type == EditPoint.EditPointTypes.MultiSegmentEditPoint) { if (previous != null && previous.Type != EditPoint.EditPointTypes.ConnectionEditPoint && next != null && next.Type != EditPoint.EditPointTypes.ConnectionEditPoint) { //Update the previous point double slopeOfLine = DesignerGeometryHelper.SlopeOfLineSegment(previous.Location, this.activeEditPoint.Location); Orientation orientation = (Math.Abs(slopeOfLine) < 1) ? Orientation.Horizontal : Orientation.Vertical; previous.Location = (orientation == Orientation.Horizontal) ? new Point(previous.Location.X, newPoint.Y) : new Point(newPoint.X, previous.Location.Y); //Update the next point slopeOfLine = DesignerGeometryHelper.SlopeOfLineSegment(this.activeEditPoint.Location, next.Location); orientation = (Math.Abs(slopeOfLine) < 1) ? Orientation.Horizontal : Orientation.Vertical; next.Location = (orientation == Orientation.Horizontal) ? new Point(next.Location.X, newPoint.Y) : new Point(newPoint.X, next.Location.Y); //Update the current point this.activeEditPoint.Location = newPoint; } else { Debug.Assert(false, "Should not be here. UpdateEditPoints failed."); } } } // Remove all the redundant edit points RemoveCoincidingEditPoints(); bool validEditPoints = ValidateEditPoints(); Debug.Assert(validEditPoints, "Validating EditPoints failed."); }
//Connector editing is completed. This function saves the state of the connectorEditor into the corresponding connector. //Returns whether the Editor was persisted or not. It might not be persisted if Connector end points do not lie on a designer. public bool Persist(Point finalSnappedPoint) { List<Point> segments = new List<Point>(); this.Update(finalSnappedPoint); if (this.activeEditPoint.Type == EditPoint.EditPointTypes.ConnectionEditPoint) { return false; } segments = this.GetPointsFromEditPoints(); this.parentPanel.UpdateConnectorPoints(Connector, segments); this.activeEditPoint = null; RemoveAdorners(); DisplayEditPoints(); return true; }
/// <summary>实现 IDTCommandTarget 接口的 Exec 方法。此方法在调用该命令时调用。</summary> /// <param term='commandName'>要执行的命令的名称。</param> /// <param term='executeOption'>描述该命令应如何运行。</param> /// <param term='varIn'>从调用方传递到命令处理程序的参数。</param> /// <param term='varOut'>从命令处理程序传递到调用方的参数。</param> /// <param term='handled'>通知调用方此命令是否已被处理。</param> /// <seealso class='Exec' /> public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled) { handled = false; if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault) { if (commandName == "MyCodeAddin.Connect.MyCodeAddin") { //此处添加自己的逻辑代码 #region //Point pos = new Point(); //var aa = GetCaretPos(ref pos); #endregion //TextPoint pt; //var ab = pt.CodeElement[vsCMElement //获取被选中文件路径及文件名 string fileFullPath = GetSelecteditempath(); //获取被选中文件路径(不包含文件名) string filePath = GetSelectedProjectPath(); //获取被选中的工程 Project project = GetSelectedProject(); SelectedItem item = GetProjectItemSel(); //文档 Document doc = _applicationObject.ActiveDocument; TextDocument textDoc = (TextDocument)_applicationObject.ActiveDocument.Object(""); TextSelection texSel = (TextSelection)_applicationObject.ActiveDocument.Selection; EditPoint Start = texSel.AnchorPoint.CreateEditPoint(); TextPoint endpt = texSel.BottomPoint; UndoContext undoObj = _applicationObject.UndoContext; undoObj.Open("Comment Region"); #region Business Methods //<# foreach(var item in Items) //{ // #> //public <#= item.Type #> <#= item.Name #> //{ // get ; // set ; //} //<#}#> #endregion //Do While (Start.LessThan(endpt)) Start.Insert("public {get;set;}"); Start.LineDown(); Start.StartOfLine(); //Loop undoObj.Close(); string actDocName = doc.Name; //var er=textPT.get_CodeElement(vsCMElement.vsCMElementClass); //var pt = textPT.CodeElement[vsCMElement.vsCMElementClass]; //MainForm mainF = new MainForm(); //mainF.applicationObject = _applicationObject; //mainF.project = project; //mainF.fileFullPath = fileFullPath; //mainF.filePath = filePath; //mainF.Show(); //handled = true; //return; //Form1 mainF = new Form1(); //mainF.applicationObject = _applicationObject; //mainF.project = project; //mainF.projectSel = item; //mainF.fileFullPath = fileFullPath; //mainF.filePath = filePath; //mainF.doc = doc; //mainF.textDoc = textDoc; //mainF.texSel = texSel; //mainF.start = Start; //mainF.undoObj = undoObj; //mainF.Show(); handled = true; return; //if (!GetSelecteditempath().ToLower().EndsWith(".cs")) //{ // return; //} ////读取选中类文件 //FileStream fs = new FileStream(GetSelecteditempath(), FileMode.Open, FileAccess.Read); //StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("GB2312")); ////将文件内容编译生成对象 //string conString = sr.ReadToEnd(); //object classobject = DynamicCompiling.Compo(conString); //string aa = classobject.GetType().Namespace; //if (classobject is string) //{ // MessageBox.Show("动态编译失败:" + "\r\n" + classobject, "类文件编译错误!"); // sr.Close(); // fs.Close(); // handled = true; // return; //} ////创建代码文件,并添加到项目中 //Createcode(classobject, GetSelectedProject(), GetSelectedProjectPath()); //sr.Close(); //fs.Close(); //handled = true; } } }
//Add edit points of specified type void AddEditPoints(EditPoint.EditPointTypes editPointType) { if (editPointType == EditPoint.EditPointTypes.ConnectionEditPoint) { if (this.editPoints.Count == 0 || !this.editPoints[0].Location.Equals(editedConnector.Points[0])) { this.editPoints.Insert(0, new EditPoint(EditPoint.EditPointTypes.ConnectionEditPoint, editedConnector.Points[0])); } if (this.editPoints.Count < 2 || !this.editPoints[this.editPoints.Count - 1].Equals(editedConnector.Points[editedConnector.Points.Count - 1])) { editPoints.Add(new EditPoint(EditPoint.EditPointTypes.ConnectionEditPoint, editedConnector.Points[editedConnector.Points.Count - 1])); } } else if (editPointType == EditPoint.EditPointTypes.MultiSegmentEditPoint) { if (this.editPoints.Count == 2) { List<Point> segments = new List<Point>(this.editedConnector.Points); if (segments.Count > 0) { segments.RemoveAt(0); segments.RemoveAt(segments.Count - 1); } for (int i = 0; i < segments.Count; i++) { this.editPoints.Insert(this.editPoints.Count - 1, new EditPoint(EditPoint.EditPointTypes.MultiSegmentEditPoint, segments[i])); } } else { Fx.Assert(false, "EditPoints.Count is not 2."); } } }
/// <summary> /// See CharMoveExact /// </summary> /// <param name="point"></param> /// <param name="count"></param> /// <returns></returns> /// <remarks>See CharMoveExact</remarks> public static EditPoint CharLeftExact(this EditPoint point, int count) { return(CharMoveExact(point, count, -1)); }
//Remove edit points of specified type //This method does not remove this.activeEditPoint. void RemoveEditPoints(EditPoint.EditPointTypes editPointType) { List<EditPoint> editPointsToRemove = new List<EditPoint>(); for (int i = 0; i < this.editPoints.Count; i++) { EditPoint editPoint = this.editPoints[i]; if (editPoint.Type == editPointType) { editPointsToRemove.Add(editPoint); } } for (int i = 0; i < editPointsToRemove.Count; i++) { EditPoint editPoint = editPointsToRemove[i]; if (editPoint != this.activeEditPoint) { this.editPoints.Remove(editPoint); } } }
/// <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. string pattern = _package.UsePOSIXRegEx ? @"^:b*\#" : @"^[ \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(); } }
private string ToString(EditPoint e) { return string.Format("AbsoluteCharOffset={0} AtEndOfDocument={1} AtEndOfLine={2} AtStartOfDocument={3} AtStartOfLine={4} DisplayColumn={5} Line={6} LineCharOffset={7} LineLength={8}", e.AbsoluteCharOffset, e.AtEndOfDocument, e.AtEndOfLine, e.AtStartOfDocument, e.AtStartOfLine, e.DisplayColumn, e.Line, e.LineCharOffset, e.LineLength); }
internal static bool IsCommentLine(EditPoint point) { return(LineMatchesRegex(point, GetCommentRegex(point.GetCodeLanguage())).Success); }
/// <summary> /// Substitutes all occurrences between the specified start and end points of the specified /// pattern string with the specified replacement string. /// </summary> /// <param name="startPoint">The start point.</param> /// <param name="endPoint">The end point.</param> /// <param name="patternString">The pattern string.</param> /// <param name="replacementString">The replacement string.</param> internal static void SubstituteAllStringMatches(EditPoint startPoint, EditPoint endPoint, string patternString, string replacementString) { TextRanges dummy = null; int lastCount = -1; while (startPoint.ReplacePattern(endPoint, patternString, replacementString, StandardFindOptions, ref dummy)) { // it is possible that the replacements aren't actually being done. In such a case, // we can detect the situation by seeing if the count always remains the same, and // if so exiting early. if (lastCount == dummy.Count) { OutputWindowHelper.WarningWriteLine("Forced a break out of TextDocumentHelper's SubstituteAllStringMatches for a pair of points."); break; } lastCount = dummy.Count; } }
static protected string GetSelectedText(EditPoint selPoint) { return(selPoint.GetText(selPoint.LineLength).Trim()); }
internal static Match LineMatchesRegex(EditPoint point, Regex regex) { var line = point.GetLine(); var match = regex.Match(line); return match; }
/// <summary> /// Selects the introduction page html to be at the top of the windows /// </summary> public override void Execute() { DTE vs = GetService <DTE>(true); ProjectItem actionClassFile = (ProjectItem)DteHelper.GetTarget(vs); if ((actionClassFile == null) || (actionClassFile.FileCodeModel == null) || (actionClassFile.FileCodeModel.CodeElements == null) || (actionClassFile.FileCodeModel.CodeElements.Count == 0)) { return; } string fieldName = ""; if ((ParameterName.Length > 1) && (ParameterName[0] >= 'A') && (ParameterName[0] <= 'Z')) { fieldName = char.ToLower(parameterName[0], CultureInfo.CurrentCulture) + parameterName.Substring(1); } else { fieldName = "_" + parameterName; } string attribute; if (ParameterIsOutput) { attribute = "Output"; } else { attribute = "Input"; } bool addedProperty = false; foreach (CodeElement element in actionClassFile.FileCodeModel.CodeElements) { if (element.Kind == vsCMElement.vsCMElementNamespace) { foreach (CodeElement elementNamespace in ((CodeNamespace)element).Members) { if (elementNamespace.Kind == vsCMElement.vsCMElementClass) { #region Look where to insert the property object whereToInsert = null; CodeClass classAction = (CodeClass)elementNamespace; CodeProperty foundProperty = null; foreach (CodeElement classElement in classAction.Members) { if (foundProperty != null) { if (classElement.Kind == vsCMElement.vsCMElementVariable) { // Then insert after this declaration of variable that was after the property whereToInsert = classElement; } } if (classElement.Kind == vsCMElement.vsCMElementProperty) { foundProperty = (CodeProperty)classElement; bool hasAttribute = false; for (int i = 1; i <= foundProperty.Attributes.Count; i++) { if (foundProperty.Attributes.Item(i).Name == attribute) { hasAttribute = true; break; } } if (!hasAttribute) { foundProperty = null; } } } if (foundProperty != null) { if (whereToInsert == null) { whereToInsert = foundProperty; } } else if (whereToInsert == null) { whereToInsert = 0; } #endregion CodeProperty prop = classAction.AddProperty(ParameterName, ParameterName, ParameterType, whereToInsert, vsCMAccess.vsCMAccessPublic, actionClassFile.Name); TextPoint getTextTP = prop.Getter.GetStartPoint(vsCMPart.vsCMPartBody); EditPoint getText = getTextTP.CreateEditPoint(); getText.ReplaceText(prop.Getter.GetEndPoint(vsCMPart.vsCMPartBody), string.Format(CultureInfo.InvariantCulture, "return {0};", fieldName), (int)vsEPReplaceTextOptions.vsEPReplaceTextNormalizeNewlines); getText.SmartFormat(getTextTP); TextPoint setTextTP = prop.Setter.GetStartPoint(vsCMPart.vsCMPartBody); EditPoint setText = setTextTP.CreateEditPoint(); setText.ReplaceText(0, string.Format(CultureInfo.InvariantCulture, "{0}=value;", fieldName), 0); setText.SmartFormat(setTextTP); if (ParameterIsOutput) { prop.AddAttribute(attribute, "", 0); } else { prop.AddAttribute(attribute, "true", 0); } classAction.AddVariable(fieldName, ParameterType, prop, vsCMAccess.vsCMAccessPrivate, actionClassFile.Name); // Stop adding property, just the first class found addedProperty = true; break; } } if (addedProperty) { break; } } } }