public AnalyzeFormatting ( IDocument document, SyntaxTree syntaxTree, |
||
document | IDocument | Document. |
syntaxTree | SyntaxTree | Syntax tree. |
token | The cancellation token. | |
return |
public string FormatText (CSharpFormattingPolicy policy, TextStylePolicy textPolicy, string mimeType, string input, int startOffset, int endOffset) { var data = new TextEditorData (); data.Document.SuppressHighlightUpdate = true; data.Document.MimeType = mimeType; data.Document.FileName = "toformat.cs"; if (textPolicy != null) { data.Options.TabsToSpaces = textPolicy.TabsToSpaces; data.Options.TabSize = textPolicy.TabWidth; data.Options.IndentationSize = textPolicy.IndentWidth; data.Options.IndentStyle = textPolicy.RemoveTrailingWhitespace ? IndentStyle.Virtual : IndentStyle.Smart; } data.Text = input; // System.Console.WriteLine ("-----"); // System.Console.WriteLine (data.Text.Replace (" ", ".").Replace ("\t", "->")); // System.Console.WriteLine ("-----"); var parser = new CSharpParser (); var compilationUnit = parser.Parse (data); bool hadErrors = parser.HasErrors; if (hadErrors) { // foreach (var e in parser.ErrorReportPrinter.Errors) // Console.WriteLine (e.Message); return input.Substring (startOffset, Math.Max (0, Math.Min (endOffset, input.Length) - startOffset)); } var originalVersion = data.Document.Version; var textEditorOptions = data.CreateNRefactoryTextEditorOptions (); var formattingVisitor = new ICSharpCode.NRefactory.CSharp.CSharpFormatter ( policy.CreateOptions (), textEditorOptions ) { FormattingMode = FormattingMode.Intrusive }; var changes = formattingVisitor.AnalyzeFormatting (data.Document, compilationUnit); try { changes.ApplyChanges (startOffset, endOffset - startOffset); } catch (Exception e) { LoggingService.LogError ("Error in code formatter", e); return input.Substring (startOffset, Math.Max (0, Math.Min (endOffset, input.Length) - startOffset)); } // check if the formatter has produced errors parser = new CSharpParser (); parser.Parse (data); if (parser.HasErrors) { LoggingService.LogError ("C# formatter produced source code errors. See console for output."); return input.Substring (startOffset, Math.Max (0, Math.Min (endOffset, input.Length) - startOffset)); } var currentVersion = data.Document.Version; string result = data.GetTextBetween (startOffset, originalVersion.MoveOffsetTo (currentVersion, endOffset, ICSharpCode.NRefactory.Editor.AnchorMovementType.Default)); data.Dispose (); return result; }
/// <summary> /// Formats the specified part of the document. /// </summary> public static void Format(ITextEditor editor, int offset, int length, CSharpFormattingOptions options) { var formatter = new CSharpFormatter(options, editor.ToEditorOptions()); formatter.AddFormattingRegion(new DomRegion(editor.Document.GetLocation(offset), editor.Document.GetLocation(offset + length))); var changes = formatter.AnalyzeFormatting(editor.Document, SyntaxTree.Parse(editor.Document)); changes.ApplyChanges(offset, length); }
/// <summary> /// Formats the specified part of the document. /// </summary> public static void Format(ITextEditor editor, int offset, int length, CSharpFormattingOptionsContainer optionsContainer) { TextEditorOptions editorOptions = editor.ToEditorOptions(); optionsContainer.CustomizeEditorOptions(editorOptions); var formatter = new CSharpFormatter(optionsContainer.GetEffectiveOptions(), editorOptions); formatter.AddFormattingRegion(new DomRegion(editor.Document.GetLocation(offset), editor.Document.GetLocation(offset + length))); var changes = formatter.AnalyzeFormatting(editor.Document, SyntaxTree.Parse(editor.Document)); changes.ApplyChanges(offset, length); }
static FormattingChanges GetFormattingChanges(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain, MonoDevelop.Ide.Gui.Document document, string input, DomRegion formattingRegion, ref int formatStartOffset, ref int formatLength, bool formatLastStatementOnly) { using (var stubData = TextEditorData.CreateImmutable(input)) { stubData.Document.FileName = document.FileName; var parser = document.HasProject ? new CSharpParser(TypeSystemParser.GetCompilerArguments(document.Project)) : new CSharpParser(); var compilationUnit = parser.Parse(stubData); bool hadErrors = parser.HasErrors; if (hadErrors) { using (var stubData2 = TextEditorData.CreateImmutable(input + "}")) { compilationUnit = parser.Parse(stubData2); hadErrors = parser.HasErrors; } } // try it out, if the behavior is better when working only with correct code. if (hadErrors) { return(null); } var policy = policyParent.Get <CSharpFormattingPolicy> (mimeTypeChain); var formattingVisitor = new ICSharpCode.NRefactory.CSharp.CSharpFormatter(policy.CreateOptions(), document.Editor.CreateNRefactoryTextEditorOptions()); formattingVisitor.FormattingMode = FormattingMode.Intrusive; formattingVisitor.AddFormattingRegion(formattingRegion); var changes = formattingVisitor.AnalyzeFormatting(stubData.Document, compilationUnit); if (formatLastStatementOnly) { AstNode node = compilationUnit.GetAdjacentNodeAt <Statement> (stubData.OffsetToLocation(formatStartOffset + formatLength - 1)); if (node != null) { while (node.Role == Roles.EmbeddedStatement || node.Role == IfElseStatement.TrueRole || node.Role == IfElseStatement.FalseRole) { node = node.Parent; } // include indentation if node starts in new line var formatNode = node.GetPrevNode(); if (formatNode.Role != Roles.NewLine) { formatNode = node; } var start = stubData.LocationToOffset(formatNode.StartLocation); if (start > formatStartOffset) { var end = stubData.LocationToOffset(node.EndLocation); formatStartOffset = start; formatLength = end - start; } } } return(changes); } }
//public static CSharpFormattingOptions tModLoaderFormat = FormattingOptionsFactory.CreateAllman(); public static string FormatCode(string text, CSharpFormattingOptions options, CancellationToken ct) { var formatter = new CSharpFormatter(options) { FormattingMode = FormattingMode.Intrusive }; text = text.Replace("\r\n\r\n", "\r\n"); var doc = new StringBuilderDocument(text); var syntaxTree = SyntaxTree.Parse(doc, doc.FileName, null, ct); formatter.AnalyzeFormatting(doc, syntaxTree, ct).ApplyChanges(); return doc.Text; }
protected static FormattingChanges GetChanges(CSharpFormattingOptions policy, string input, out StringBuilderDocument document, FormattingMode mode = FormattingMode.Intrusive, TextEditorOptions options = null) { options = GetActualOptions(options); input = NormalizeNewlines(input); document = new StringBuilderDocument(input); var visitor = new CSharpFormatter(policy, options); visitor.FormattingMode = mode; var syntaxTree = new CSharpParser().Parse(document, "test.cs"); return visitor.AnalyzeFormatting(document, syntaxTree); }
/*public static string ApplyChanges (string text, List<TextReplaceAction> changes) { changes.Sort ((x, y) => y.Offset.CompareTo (x.Offset)); StringBuilder b = new StringBuilder(text); foreach (var change in changes) { //Console.WriteLine ("---- apply:" + change); // Console.WriteLine (adapter.Text); if (change.Offset > b.Length) continue; b.Remove(change.Offset, change.RemovedChars); b.Insert(change.Offset, change.InsertedText); } // Console.WriteLine ("---result:"); // Console.WriteLine (adapter.Text); return b.ToString(); }*/ protected static IDocument GetResult(CSharpFormattingOptions policy, string input, FormattingMode mode = FormattingMode.Intrusive) { input = NormalizeNewlines(input); var document = new StringBuilderDocument(input); var options = new TextEditorOptions(); options.EolMarker = "\n"; options.WrapLineLength = 80; var visitor = new CSharpFormatter (policy, options); visitor.FormattingMode = mode; var syntaxTree = new CSharpParser ().Parse (document, "test.cs"); var changes = visitor.AnalyzeFormatting(document, syntaxTree); changes.ApplyChanges(); return document; }
/// <summary> /// Formats the specified part of the document. /// </summary> public static void Format(ITextEditor editor, int offset, int length, CSharpFormattingOptionsContainer optionsContainer) { SyntaxTree syntaxTree = SyntaxTree.Parse(editor.Document); if (syntaxTree.Errors.Count > 0) { // Don't format files containing syntax errors! return; } TextEditorOptions editorOptions = editor.ToEditorOptions(); optionsContainer.CustomizeEditorOptions(editorOptions); var formatter = new CSharpFormatter(optionsContainer.GetEffectiveOptions(), editorOptions); formatter.AddFormattingRegion(new DomRegion(editor.Document.GetLocation(offset), editor.Document.GetLocation(offset + length))); var changes = formatter.AnalyzeFormatting(editor.Document, syntaxTree); changes.ApplyChanges(offset, length); }
static FormattingChanges GetFormattingChanges (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, MonoDevelop.Ide.Gui.Document document, string input, DomRegion formattingRegion, ref int formatStartOffset, ref int formatLength, bool formatLastStatementOnly) { using (var stubData = TextEditorData.CreateImmutable (input)) { stubData.Document.FileName = document.FileName; var parser = document.HasProject ? new CSharpParser (TypeSystemParser.GetCompilerArguments (document.Project)) : new CSharpParser (); var compilationUnit = parser.Parse (stubData); bool hadErrors = parser.HasErrors; if (hadErrors) { using (var stubData2 = TextEditorData.CreateImmutable (input + "}")) { compilationUnit = parser.Parse (stubData2); hadErrors = parser.HasErrors; } } // try it out, if the behavior is better when working only with correct code. if (hadErrors) { return null; } var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain); var formattingVisitor = new ICSharpCode.NRefactory.CSharp.CSharpFormatter (policy.CreateOptions (), document.Editor.CreateNRefactoryTextEditorOptions ()); formattingVisitor.FormattingMode = FormattingMode.Intrusive; formattingVisitor.AddFormattingRegion (formattingRegion); var changes = formattingVisitor.AnalyzeFormatting (stubData.Document, compilationUnit); if (formatLastStatementOnly) { AstNode node = compilationUnit.GetAdjacentNodeAt<Statement> (stubData.OffsetToLocation (formatStartOffset + formatLength - 1)); if (node != null) { while (node.Role == Roles.EmbeddedStatement || node.Role == IfElseStatement.TrueRole || node.Role == IfElseStatement.FalseRole) node = node.Parent; // include indentation if node starts in new line var formatNode = node.GetPrevNode (); if (formatNode.Role != Roles.NewLine) formatNode = node; var start = stubData.LocationToOffset (formatNode.StartLocation); if (start > formatStartOffset) { var end = stubData.LocationToOffset (node.EndLocation); formatStartOffset = start; formatLength = end - start; } } } return changes; } }
public static string FormatText(CSharpFormattingPolicy policy, TextStylePolicy textPolicy, string mimeType, string input, int startOffset, int endOffset) { var data = new TextEditorData(); data.Document.SuppressHighlightUpdate = true; data.Document.MimeType = mimeType; data.Document.FileName = "toformat.cs"; if (textPolicy != null) { data.Options.TabsToSpaces = textPolicy.TabsToSpaces; data.Options.TabSize = textPolicy.TabWidth; data.Options.IndentationSize = textPolicy.IndentWidth; data.Options.IndentStyle = textPolicy.RemoveTrailingWhitespace ? IndentStyle.Virtual : IndentStyle.Smart; } data.Text = input; // System.Console.WriteLine ("-----"); // System.Console.WriteLine (data.Text.Replace (" ", ".").Replace ("\t", "->")); // System.Console.WriteLine ("-----"); var parser = new CSharpParser(); var compilationUnit = parser.Parse(data); bool hadErrors = parser.HasErrors; if (hadErrors) { // foreach (var e in parser.ErrorReportPrinter.Errors) // Console.WriteLine (e.Message); return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset))); } var originalVersion = data.Document.Version; var textEditorOptions = data.CreateNRefactoryTextEditorOptions(); var formattingVisitor = new ICSharpCode.NRefactory.CSharp.CSharpFormatter( policy.CreateOptions(), textEditorOptions ) { FormattingMode = FormattingMode.Intrusive }; var changes = formattingVisitor.AnalyzeFormatting(data.Document, compilationUnit); try { changes.ApplyChanges(startOffset, endOffset - startOffset); } catch (Exception e) { LoggingService.LogError("Error in code formatter", e); return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset))); } // check if the formatter has produced errors parser = new CSharpParser(); parser.Parse(data); if (parser.HasErrors) { LoggingService.LogError("C# formatter produced source code errors. See console for output."); return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset))); } var currentVersion = data.Document.Version; string result = data.GetTextBetween(startOffset, originalVersion.MoveOffsetTo(currentVersion, endOffset)); data.Dispose(); return(result); }
public override void Complete(ICSharpCode.AvalonEdit.Editing.TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { if (declarationBegin > completionSegment.Offset) { base.Complete(textArea, completionSegment, insertionRequestEventArgs); return; } TypeSystemAstBuilder b = new TypeSystemAstBuilder(new CSharpResolver(contextAtCaret)); b.ShowTypeParameterConstraints = false; b.GenerateBody = true; var entityDeclaration = b.ConvertEntity(this.Entity); entityDeclaration.Modifiers &= ~(Modifiers.Virtual | Modifiers.Abstract); entityDeclaration.Modifiers |= Modifiers.Override; if (!this.Entity.IsAbstract) { // modify body to call the base method if (this.Entity.EntityType == EntityType.Method) { var baseCall = new BaseReferenceExpression().Invoke(this.Entity.Name, ParametersToExpressions(this.Entity)); var body = entityDeclaration.GetChildByRole(Roles.Body); body.Statements.Clear(); if (((IMethod)this.Entity).ReturnType.IsKnownType(KnownTypeCode.Void)) body.Statements.Add(new ExpressionStatement(baseCall)); else body.Statements.Add(new ReturnStatement(baseCall)); } else if (this.Entity.EntityType == EntityType.Indexer || this.Entity.EntityType == EntityType.Property) { Expression baseCall; if (this.Entity.EntityType == EntityType.Indexer) baseCall = new BaseReferenceExpression().Indexer(ParametersToExpressions(this.Entity)); else baseCall = new BaseReferenceExpression().Member(this.Entity.Name); var getterBody = entityDeclaration.GetChildByRole(PropertyDeclaration.GetterRole).Body; if (!getterBody.IsNull) { getterBody.Statements.Clear(); getterBody.Add(new ReturnStatement(baseCall.Clone())); } var setterBody = entityDeclaration.GetChildByRole(PropertyDeclaration.SetterRole).Body; if (!setterBody.IsNull) { setterBody.Statements.Clear(); setterBody.Add(new AssignmentExpression(baseCall.Clone(), new IdentifierExpression("value"))); } } } var document = textArea.Document; StringWriter w = new StringWriter(); var formattingOptions = FormattingOptionsFactory.CreateSharpDevelop(); var segmentDict = SegmentTrackingOutputFormatter.WriteNode(w, entityDeclaration, formattingOptions, textArea.Options); string newText = w.ToString().TrimEnd(); document.Replace(declarationBegin, completionSegment.EndOffset - declarationBegin, newText); var throwStatement = entityDeclaration.Descendants.FirstOrDefault(n => n is ThrowStatement); if (throwStatement != null) { var segment = segmentDict[throwStatement]; textArea.Selection = new RectangleSelection(textArea, new TextViewPosition(textArea.Document.GetLocation(declarationBegin + segment.Offset)), new TextViewPosition(textArea.Document.GetLocation(declarationBegin + segment.Offset + segment.Length))); } //format the inserted code nicely var formatter = new CSharpFormatter(formattingOptions); formatter.AddFormattingRegion(new DomRegion(document.GetLocation(declarationBegin), document.GetLocation(declarationBegin + newText.Length))); var syntaxTree = new CSharpParser().Parse(document); formatter.AnalyzeFormatting(document, syntaxTree).ApplyChanges(); }