|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under MIT. See LICENSE in the project root for license information. |
| 3 | +using System; |
| 4 | +using System.Collections; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.ComponentModel.Composition; |
| 7 | +using System.Linq; |
| 8 | +using System.Threading; |
| 9 | +using System.Threading.Tasks; |
| 10 | + |
| 11 | +using Microsoft.CodeAnalysis; |
| 12 | +using Microsoft.CodeAnalysis.CSharp; |
| 13 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 14 | + |
| 15 | +namespace Microsoft.DotNet.CodeFormatting.Rules |
| 16 | +{ |
| 17 | + // [Export(typeof(IFormattingRule))] |
| 18 | + // This rule negates the changes done by the IsFormatterFormattingRule, when there are #ifdef using |
| 19 | + // statements. Thus the formatter will enter an infinite loop. Enable this rule as required. |
| 20 | + internal sealed class HasNewLineBeforeFirstUsingFormattingRule : IFormattingRule |
| 21 | + { |
| 22 | + public async Task<Document> ProcessAsync(Document document, CancellationToken cancellationToken) |
| 23 | + { |
| 24 | + var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken) as CSharpSyntaxNode; |
| 25 | + if (syntaxRoot == null) |
| 26 | + return document; |
| 27 | + |
| 28 | + var firstUsing = syntaxRoot.DescendantNodesAndSelf().OfType<UsingDirectiveSyntax>().FirstOrDefault(); |
| 29 | + IEnumerable<SyntaxTrivia> newTrivia = Enumerable.Empty<SyntaxTrivia>(); |
| 30 | + |
| 31 | + if (firstUsing == null) |
| 32 | + return document; |
| 33 | + |
| 34 | + if (firstUsing.HasLeadingTrivia) |
| 35 | + { |
| 36 | + var trivia = firstUsing.GetLeadingTrivia(); |
| 37 | + if (trivia.Last().CSharpKind() == SyntaxKind.EndOfLineTrivia) |
| 38 | + { |
| 39 | + int index = trivia.Count - 2; |
| 40 | + while (index >= 0) |
| 41 | + { |
| 42 | + if (trivia.ElementAt(index).CSharpKind() != SyntaxKind.EndOfLineTrivia) |
| 43 | + break; |
| 44 | + index--; |
| 45 | + } |
| 46 | + |
| 47 | + newTrivia = trivia.Take(index + 1); |
| 48 | + } |
| 49 | + else |
| 50 | + { |
| 51 | + newTrivia = trivia; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + newTrivia = newTrivia.Concat(new[] { SyntaxFactory.EndOfLine("\n"), SyntaxFactory.EndOfLine("\n") }); |
| 56 | + |
| 57 | + return document.WithSyntaxRoot(syntaxRoot.ReplaceNode(firstUsing, firstUsing.WithLeadingTrivia(newTrivia))); |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments