/*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); }
public static async Task ComputeRefactoringsAsync(RefactoringContext context, AttributeArgumentListSyntax argumentList) { if (!argumentList.Arguments.Any()) { return; } await AttributeArgumentParameterNameRefactoring.ComputeRefactoringsAsync(context, argumentList).ConfigureAwait(false); if (context.IsRefactoringEnabled(RefactoringIdentifiers.DuplicateArgument)) { DuplicateAttributeArgumentRefactoring.ComputeRefactoring(context, argumentList); } if (context.IsRefactoringEnabled(RefactoringIdentifiers.FormatArgumentList) && context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(argumentList)) { if (argumentList.IsSingleLine()) { if (argumentList.Arguments.Count > 1) { context.RegisterRefactoring( "Format arguments on separate lines", cancellationToken => { return(CSharpFormatter.ToMultiLineAsync( context.Document, argumentList, cancellationToken)); }); } } else { context.RegisterRefactoring( "Format arguments on a single line", cancellationToken => { return(CSharpFormatter.ToSingleLineAsync( context.Document, argumentList, cancellationToken)); }); } } }
public static async Task ComputeRefactoringsAsync(RefactoringContext context, ParameterListSyntax parameterList) { SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters; if (parameters.Any()) { if (context.IsRefactoringEnabled(RefactoringIdentifiers.DuplicateParameter)) { var refactoring = new DuplicateParameterRefactoring(parameterList); refactoring.ComputeRefactoring(context); } if (context.IsRefactoringEnabled(RefactoringIdentifiers.CheckParameterForNull)) { await CheckParameterForNullRefactoring.ComputeRefactoringAsync(context, parameterList).ConfigureAwait(false); } if (context.IsAnyRefactoringEnabled( RefactoringIdentifiers.IntroduceAndInitializeField, RefactoringIdentifiers.IntroduceAndInitializeProperty)) { IntroduceAndInitializeRefactoring.ComputeRefactoring(context, parameterList); } if (context.IsRefactoringEnabled(RefactoringIdentifiers.FormatParameterList) && (context.Span.IsEmpty || context.Span.IsBetweenSpans(parameterList))) { if (parameterList.IsSingleLine()) { if (parameters.Count > 1) { context.RegisterRefactoring( "Format parameters on separate lines", cancellationToken => CSharpFormatter.ToMultiLineAsync(context.Document, parameterList, cancellationToken)); } } else { context.RegisterRefactoring( "Format parameters on a single line", cancellationToken => CSharpFormatter.ToSingleLineAsync(context.Document, parameterList, cancellationToken)); } } } }
/// <summary> /// Perform a reformat of the text /// </summary> /// <param name="sender">Sender object</param> /// <param name="e">Event arguments</param> private void OnDoReformat(object sender, EventArgs e) { try { #if NETFRAMEWORK CSharpFormatter formatter = new CSharpFormatter(FormattingOptionsFactory.CreateAllman()); string newText = formatter.Format(managerView.Editor.Text); managerView.Editor.Text = newText; explorerPresenter.CommandHistory.Add(new Commands.ChangeProperty(manager, "Code", newText)); #else throw new NotImplementedException(); #endif } catch (Exception err) { explorerPresenter.MainPresenter.ShowError(err); } }
public void LetsTalkAboutCastleWindsor() { var workingPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(workingPath); var nuget = GetNuGet("Castle.Windsor", "4.0.0"); var nugetStream = new MemoryStream(); nugetStream.Write(nuget, 0, nuget.Length); var a = new ZipArchive(nugetStream); foreach (var file in a.Entries) { if (file.FullName == "lib/net45/Castle.Windsor.dll") { file.ExtractToFile(Path.Combine(workingPath, file.Name), false); } if (file.FullName == "lib/net45/Castle.Windsor.xml") { file.ExtractToFile(Path.Combine(workingPath, file.Name), false); } } var formatter = new CSharpFormatter(); var generatedHtml = formatter.GetHtmlForMarkdownContent(@" # Let's talk about Castle Windsor There is this IFacility inferface: #r ""Castle.Windsor.dll"" var t = typeof(Castle.MicroKernel.IFacility); var container = new Castle.Windsor.WindsorContainer(); container.Resolve<string>(); ", baseReferencePath: workingPath); Assert.True(generatedHtml.Contains("Unit of extension. A facility should use the extension points offered by the kernel to augment its functionality.")); Assert.True(generatedHtml.Contains("Returns a component instance by the service")); }
protected static void Continue(CSharpFormattingOptions policy, IDocument document, string expectedOutput, FormattingMode formattingMode = FormattingMode.OnTheFly) { expectedOutput = NormalizeNewlines(expectedOutput); var options = new TextEditorOptions(); options.EolMarker = "\n"; var formatter = new CSharpFormatter(policy, options); formatter.FormattingMode = formattingMode; string newText = formatter.Format(document); if (expectedOutput != newText) { Console.WriteLine("expected:"); Console.WriteLine(expectedOutput); Console.WriteLine("got:"); Console.WriteLine(newText); } Assert.AreEqual(expectedOutput, newText); }
/// <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); }
/// <summary> /// 実際にフォーマットを行う /// </summary> /// <param name="path">フォーマットするファイルへのパス</param> private static void Format(string path) { // フォーマットを行うソースコードを全て読み込む string targetSourceCode; using (var reader = new StreamReader(path)) { targetSourceCode = reader.ReadToEnd(); } // ソースコードをフォーマットする CSharpFormatter formatter = new CSharpFormatter(FormattingOptions.options); var formatSourceCode = formatter.Format(targetSourceCode); // 同じファイル名で出力する using (var writer = new StreamWriter(path)) { writer.Write(formatSourceCode); } }
public override void FormatText(IEnumerable<AstNode> nodes) { var syntaxTree = SyntaxTree.Parse(currentDocument, "dummy.cs"); var formatter = new CSharpFormatter(FormattingOptions, Options); var segments = new List<ISegment>(); foreach (var node in nodes.OrderByDescending (n => n.StartLocation)) { var segment = GetSegment(node); formatter.AddFormattingRegion (new ICSharpCode.NRefactory.TypeSystem.DomRegion ( currentDocument.GetLocation (segment.Offset), currentDocument.GetLocation (segment.EndOffset) )); segments.Add(segment); } if (segments.Count == 0) return; var changes = formatter.AnalyzeFormatting (currentDocument, syntaxTree); foreach (var segment in segments) { changes.ApplyChanges(segment.Offset, segment.Length - 1); } }
public static void ComputeRefactorings(RefactoringContext context, BinaryExpressionSyntax binaryExpression) { binaryExpression = GetBinaryExpression(binaryExpression, context.Span); if (binaryExpression != null && IsFormattableKind(binaryExpression.Kind())) { if (binaryExpression.IsSingleLine()) { context.RegisterRefactoring( "Format binary expression on multiple lines", cancellationToken => CSharpFormatter.ToMultiLineAsync(context.Document, binaryExpression, cancellationToken)); } else { context.RegisterRefactoring( "Format binary expression on a single line", cancellationToken => CSharpFormatter.ToSingleLineAsync(context.Document, binaryExpression, cancellationToken)); } } }
public override void CreateNewType(AstNode newType, NewTypeContext ntctx) { if (newType == null) { throw new System.ArgumentNullException("newType"); } var correctFileName = MoveTypeToFile.GetCorrectFileName(context, (EntityDeclaration)newType); var content = context.Document.Editor.Text; var types = new List <EntityDeclaration> (context.Unit.GetTypes()); types.Sort((x, y) => y.StartLocation.CompareTo(x.StartLocation)); foreach (var removeType in types) { var start = context.GetOffset(removeType.StartLocation); var end = context.GetOffset(removeType.EndLocation); content = content.Remove(start, end - start); } var insertLocation = types.Count > 0 ? context.GetOffset(types.Last().StartLocation) : -1; var formattingPolicy = this.document.GetFormattingPolicy(); if (insertLocation < 0 || insertLocation > content.Length) { insertLocation = content.Length; } content = content.Substring(0, insertLocation) + newType.GetText(formattingPolicy.CreateOptions()) + content.Substring(insertLocation); var formatter = new CSharpFormatter(); content = formatter.FormatText(formattingPolicy, null, CSharpFormatter.MimeType, content, 0, content.Length); File.WriteAllText(correctFileName, content); document.Project.AddFile(correctFileName); MonoDevelop.Ide.IdeApp.ProjectOperations.Save(document.Project); MonoDevelop.Ide.IdeApp.Workbench.OpenDocument(correctFileName); }
public static async Task ComputeRefactoringsAsync(RefactoringContext context, MemberAccessExpressionSyntax memberAccessExpression) { if (context.Span.IsEmpty && memberAccessExpression.Span.Contains(context.Span) && memberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); List <MemberAccessExpressionSyntax> expressions = GetChain(memberAccessExpression, semanticModel, context.CancellationToken); if (expressions.Count > 1) { if (expressions[0].IsSingleLine(includeExteriorTrivia: false)) { context.RegisterRefactoring( "Format expression chain on multiple lines", cancellationToken => { return(CSharpFormatter.ToMultiLineAsync( context.Document, expressions.ToArray(), cancellationToken)); }); } else { context.RegisterRefactoring( "Format expression chain on a single line", cancellationToken => { return(CSharpFormatter.ToSingleLineAsync( context.Document, expressions[0], cancellationToken)); }); } } } }
private CSharpResultProviderTestBase(CSharpFormatter formatter) : this(new DkmInspectionSession(ImmutableArray.Create <IDkmClrFormatter>(formatter), ImmutableArray.Create <IDkmClrResultProvider>(new CSharpResultProvider(formatter, formatter)))) { }
public async Task <Document> RefactorAsync( Document document, ExpressionStatementSyntax expressionStatement, CancellationToken cancellationToken) { SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); InvocationExpressionSyntax invocationExpression = GetInvocationExpression(expressionStatement); semanticModel.TryGetMethodInfo(invocationExpression, out MethodInfo methodInfo, cancellationToken); MemberInvocationExpressionInfo invocationInfo = SyntaxInfo.MemberInvocationExpressionInfo(invocationExpression); ITypeSymbol typeSymbol = methodInfo.ReturnType; string name = ((IdentifierNameSyntax)WalkDownMethodChain(invocationInfo).Expression).Identifier.ValueText; StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(expressionStatement); SyntaxList <StatementSyntax> statements = statementsInfo.Statements; int index = statements.IndexOf(expressionStatement); string indentation = CSharpFormatter.GetIncreasedIndentation(expressionStatement, cancellationToken).ToString(); var sb = new StringBuilder(invocationExpression.ToString()); int j = index; while (j < statements.Count - 1) { StatementSyntax statement = statements[j + 1]; if (!IsFixableStatement(statement, name, typeSymbol, semanticModel, cancellationToken)) { break; } sb.AppendLine(); sb.Append(indentation); sb.Append(GetTextToAppend((ExpressionStatementSyntax)statement)); j++; } StatementSyntax lastStatement = statements[j]; SyntaxList <StatementSyntax> newStatements = statements; while (j > index) { newStatements = newStatements.RemoveAt(j); j--; } ExpressionSyntax newInvocationExpression = SyntaxFactory.ParseExpression(sb.ToString()); SyntaxTriviaList trailingTrivia = statementsInfo .Node .DescendantTrivia(TextSpan.FromBounds(invocationExpression.Span.End, lastStatement.Span.End)) .ToSyntaxTriviaList() .EmptyIfWhitespace() .AddRange(lastStatement.GetTrailingTrivia()); ExpressionStatementSyntax newExpressionStatement = expressionStatement .ReplaceNode(invocationExpression, newInvocationExpression) .WithLeadingTrivia(expressionStatement.GetLeadingTrivia()) .WithTrailingTrivia(trailingTrivia) .WithFormatterAndSimplifierAnnotations(); newStatements = newStatements.ReplaceAt(index, newExpressionStatement); return(await document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken).ConfigureAwait(false)); }
public override void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { if (declarationBegin > completionSegment.Offset) { base.Complete(textArea, completionSegment, insertionRequestEventArgs); return; } var b = new TypeSystemAstBuilder(new CSharpResolver(contextAtCaret)) { ShowTypeParameterConstraints = false, 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.SymbolKind == SymbolKind.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.SymbolKind == SymbolKind.Indexer || this.Entity.SymbolKind == SymbolKind.Property) { Expression baseCall; if (this.Entity.SymbolKind == SymbolKind.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(); }
public static void ComputeRefactorings(RefactoringContext context, AccessorDeclarationSyntax accessor) { if (context.IsRefactoringEnabled(RefactoringIdentifiers.FormatAccessorBraces)) { BlockSyntax body = accessor.Body; if (body?.Span.Contains(context.Span) == true && !body.OpenBraceToken.IsMissing && !body.CloseBraceToken.IsMissing) { if (body.IsSingleLine()) { if (accessor.Parent?.IsMultiLine() == true) { context.RegisterRefactoring( "Format braces on separate lines", cancellationToken => CSharpFormatter.ToMultiLineAsync(context.Document, accessor, cancellationToken)); } } else { SyntaxList <StatementSyntax> statements = body.Statements; if (statements.Count == 1 && statements[0].IsSingleLine()) { context.RegisterRefactoring( "Format braces on a single line", cancellationToken => CSharpFormatter.ToSingleLineAsync(context.Document, accessor, cancellationToken)); } } } } if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseExpressionBodiedMember) && context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(accessor) && context.SupportsCSharp6 && UseExpressionBodiedMemberRefactoring.CanRefactor(accessor)) { SyntaxNode node = accessor; var accessorList = accessor.Parent as AccessorListSyntax; if (accessorList != null) { SyntaxList <AccessorDeclarationSyntax> accessors = accessorList.Accessors; if (accessors.Count == 1 && accessors.First().IsKind(SyntaxKind.GetAccessorDeclaration)) { var parent = accessorList.Parent as MemberDeclarationSyntax; if (parent != null) { node = parent; } } } context.RegisterRefactoring( "Use expression-bodied member", cancellationToken => UseExpressionBodiedMemberRefactoring.RefactorAsync(context.Document, node, cancellationToken)); } }
public override void CreateNewType (AstNode newType, NewTypeContext ntctx) { if (newType == null) throw new System.ArgumentNullException ("newType"); var correctFileName = MoveTypeToFile.GetCorrectFileName (context, (EntityDeclaration)newType); var content = context.Document.Editor.Text; var types = new List<TypeDeclaration> (context.Unit.GetTypes ()); types.Sort ((x, y) => y.StartLocation.CompareTo (x.StartLocation)); foreach (var removeType in types) { var start = context.GetOffset (removeType.StartLocation); var end = context.GetOffset (removeType.EndLocation); content = content.Remove (start, end - start); } var insertLocation = types.Count > 0 ? context.GetOffset (types.Last ().StartLocation) : -1; var formattingPolicy = this.document.GetFormattingPolicy (); if (insertLocation < 0 || insertLocation > content.Length) insertLocation = content.Length; content = content.Substring (0, insertLocation) + newType.GetText (formattingPolicy.CreateOptions ()) + content.Substring (insertLocation); var formatter = new CSharpFormatter (); content = formatter.FormatText (formattingPolicy, null, CSharpFormatter.MimeType, content, 0, content.Length); File.WriteAllText (correctFileName, content); document.Project.AddFile (correctFileName); MonoDevelop.Ide.IdeApp.ProjectOperations.Save (document.Project); MonoDevelop.Ide.IdeApp.Workbench.OpenDocument (correctFileName); }
public static async Task <Document> RefactorAsync( Document document, ExpressionStatementSyntax expressionStatement, CancellationToken cancellationToken) { SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); INamedTypeSymbol symbol = semanticModel.GetTypeByMetadataName(MetadataNames.System_Text_StringBuilder); var invocationExpression = (InvocationExpressionSyntax)expressionStatement.Expression; MemberInvocationExpression memberInvocation = MemberInvocationExpression.Create(invocationExpression); ExpressionSyntax expression = GetFirstInvocationInMethodChain(memberInvocation, symbol, semanticModel, cancellationToken).Expression; StatementContainer statementContainer = StatementContainer.Create(expressionStatement); SyntaxList <StatementSyntax> statements = statementContainer.Statements; int index = statements.IndexOf(expressionStatement); string indentation = CSharpFormatter.GetIncreasedIndentation(expressionStatement, cancellationToken).ToString(); var sb = new StringBuilder(invocationExpression.ToString()); int j = index; while (j < statements.Count - 1) { StatementSyntax statement = statements[j + 1]; if (!IsFixable(statement, expression, symbol, semanticModel, cancellationToken)) { break; } sb.AppendLine(); sb.Append(indentation); sb.Append(GetTextToAppend((ExpressionStatementSyntax)statement, symbol, semanticModel, cancellationToken)); j++; } StatementSyntax lastStatement = statements[j]; SyntaxList <StatementSyntax> newStatements = statements; while (j > index) { newStatements = newStatements.RemoveAt(j); j--; } ExpressionSyntax newInvocationExpression = SyntaxFactory.ParseExpression(sb.ToString()); SyntaxTriviaList trailingTrivia = statementContainer .Node .DescendantTrivia(TextSpan.FromBounds(invocationExpression.Span.End, lastStatement.Span.End)) .ToSyntaxTriviaList() .EmptyIfWhitespace() .AddRange(lastStatement.GetTrailingTrivia()); ExpressionStatementSyntax newExpressionStatement = expressionStatement .WithExpression(newInvocationExpression) .WithLeadingTrivia(expressionStatement.GetLeadingTrivia()) .WithTrailingTrivia(trailingTrivia) .WithFormatterAndSimplifierAnnotations(); newStatements = newStatements.ReplaceAt(index, newExpressionStatement); return(await document.ReplaceNodeAsync(statementContainer.Node, statementContainer.NodeWithStatements(newStatements), cancellationToken).ConfigureAwait(false)); }
public void LineCanBeTranslatedToHtml() { var html = new CSharpFormatter().GetHtmlForCsxContent("var a = 1 + 2;"); }
private static DkmInspectionSession CreateDkmInspectionSession(CSharpFormatter formatter = null) { formatter = formatter ?? new CSharpFormatter(); return(new DkmInspectionSession(ImmutableArray.Create <IDkmClrFormatter>(formatter), ImmutableArray.Create <IDkmClrResultProvider>(new CSharpResultProvider(formatter, formatter)))); }
private void textBoxInput_Leave(object sender, EventArgs e) { textBoxOutput.Text = CSharpFormatter.CSharp(textBoxInput.Text.Replace('\xA0', ' ')).ToString(); }
private CSharpResultProviderTestBase(CSharpFormatter formatter) : this(CreateDkmInspectionSession(formatter)) { }
public void Cast() { var source = @"class C { }"; var runtime = new DkmClrRuntimeInstance( ReflectionUtilities.GetMscorlib(GetAssembly(source)) ); using (runtime.Load()) { IDkmClrFullNameProvider fullNameProvider = new CSharpFormatter(); var inspectionContext = CreateDkmInspectionContext(); var type = runtime.GetType("C"); Assert.Equal( "(C)o", fullNameProvider.GetClrCastExpression( inspectionContext, "o", type, null, DkmClrCastExpressionOptions.None ) ); Assert.Equal( "o as C", fullNameProvider.GetClrCastExpression( inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ConditionalCast ) ); Assert.Equal( "(C)(o)", fullNameProvider.GetClrCastExpression( inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeArgument ) ); Assert.Equal( "(o) as C", fullNameProvider.GetClrCastExpression( inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeArgument | DkmClrCastExpressionOptions.ConditionalCast ) ); Assert.Equal( "((C)o)", fullNameProvider.GetClrCastExpression( inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression ) ); Assert.Equal( "(o as C)", fullNameProvider.GetClrCastExpression( inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression | DkmClrCastExpressionOptions.ConditionalCast ) ); Assert.Equal( "((C)(o))", fullNameProvider.GetClrCastExpression( inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression | DkmClrCastExpressionOptions.ParenthesizeArgument ) ); Assert.Equal( "((o) as C)", fullNameProvider.GetClrCastExpression( inspectionContext, "o", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression | DkmClrCastExpressionOptions.ParenthesizeArgument | DkmClrCastExpressionOptions.ConditionalCast ) ); // Some of the same tests with "..." as the expression ("..." is used // by the debugger when the expression cannot be determined). Assert.Equal( "(C)...", fullNameProvider.GetClrCastExpression( inspectionContext, "...", type, null, DkmClrCastExpressionOptions.None ) ); Assert.Equal( "... as C", fullNameProvider.GetClrCastExpression( inspectionContext, "...", type, null, DkmClrCastExpressionOptions.ConditionalCast ) ); Assert.Equal( "(... as C)", fullNameProvider.GetClrCastExpression( inspectionContext, "...", type, null, DkmClrCastExpressionOptions.ParenthesizeEntireExpression | DkmClrCastExpressionOptions.ConditionalCast ) ); } }
static int Main(string[] args) { var options = new Options(); if (!CommandLine.Parser.Default.ParseArguments(args, options)) { return(1); } if (!File.Exists(options.InputFile)) { Console.WriteLine("Fatal: Input file does not exist."); return(2); } var inputFile = new FileInfo(options.InputFile); var inputFormat = options.InputFormat; if (inputFormat == InputFormat.ByExtension) { if (inputFile.Extension.Equals(".md", StringComparison.InvariantCultureIgnoreCase)) { inputFormat = InputFormat.Markdown; } else if (inputFile.Extension.Equals(".cs", StringComparison.InvariantCultureIgnoreCase) || inputFile.Extension.Equals(".csx", StringComparison.InvariantCultureIgnoreCase)) { inputFormat = InputFormat.Csharp; } else { Console.WriteLine("Fatal: You did not specify input format and the input file name does not have .md, .cs or .csx extension."); return(3); } } var outputFile = options.OutputFile; if (string.IsNullOrWhiteSpace(outputFile)) { outputFile = inputFile.Directory.FullName + "/" + Path.GetFileNameWithoutExtension(inputFile.Name) + ".html"; if (options.Verbose) { Console.WriteLine($"Info: You did not supply output file name, using `{outputFile}`."); } } if (File.Exists(outputFile) && !options.OverwriteOutputFile) { Console.WriteLine($"Fatal: Output file ({outputFile}) already exists and you did not set `overwrite` command line argument to `true`."); return(4); } var formatter = new CSharpFormatter(); try { if (inputFormat == InputFormat.Markdown) { formatter.SaveHtmlForMarkdownFile( options.InputFile, options.OutputFile, options.BaseReferencePath, options.FailOnCompileWarning, options.FailOnCompileError); } else { formatter.SaveHtmlForCsxFile( options.InputFile, options.OutputFile, options.BaseReferencePath, options.FailOnCompileWarning, options.FailOnCompileError); } return(0); } catch (CompilationErrorException ex) { Console.WriteLine("Fatal: Compilation issues:"); foreach (var error in ex.Errors) { Console.WriteLine($" {error}"); } return(5); } }
public static HtmlString CSharp(this HtmlHelper @this, string code) { return(CSharpFormatter.CSharp(code)); }
protected override string Transform(string code, string fileName, Action <ValidationResult> notify) { var formatter = new CSharpFormatter(_options); return(formatter.Format(code)); }
void UpdateExample (string example) { var formatter = new CSharpFormatter (); string text; if (!string.IsNullOrEmpty (example)) { text = Environment.NewLine != "\n" ? example.Replace ("\n", Environment.NewLine) : example; } else { text = ""; } texteditor.Document.Text = formatter.FormatText (profile, null, CSharpFormatter.MimeType, text, 0, text.Length); }
private CSharpResultProviderTestBase(CSharpFormatter formatter) : this(new DkmInspectionSession(ImmutableArray.Create<IDkmClrFormatter>(formatter), ImmutableArray.Create<IDkmClrResultProvider>(new CSharpResultProvider(formatter, formatter)))) { }