public static SyntaxToken TrimTrailingTrivia(this SyntaxToken token) { SyntaxTriviaList trailingTrivia = token.TrailingTrivia; SyntaxTriviaList newTrailingTrivia = trailingTrivia.TrimEnd(); if (trailingTrivia.Count != newTrailingTrivia.Count) { return(token.WithTrailingTrivia(newTrailingTrivia)); } else { return(token); } }
public override SyntaxToken VisitToken(SyntaxToken token) { if (_separators.Contains(token)) { SyntaxTriviaList triviaList = token.TrailingTrivia; if (!triviaList.Contains(SyntaxKind.EndOfLineTrivia)) { return(token.WithTrailingTrivia(triviaList.TrimEnd().Add(CSharpFactory.NewLine()))); } } return(base.VisitToken(token)); }
private static Task <Document> RemoveBracesAsync( Document document, BlockSyntax block, CancellationToken cancellationToken) { var switchSection = (SwitchSectionSyntax)block.Parent; SyntaxList <StatementSyntax> statements = block.Statements; SyntaxTriviaList leadingTrivia = block.OpenBraceToken.LeadingTrivia; leadingTrivia = AddTriviaIfNecessary(leadingTrivia, block.OpenBraceToken.TrailingTrivia); leadingTrivia = AddTriviaIfNecessary(leadingTrivia, statements[0].GetLeadingTrivia()); SyntaxTriviaList trailingTrivia = statements.Last().GetTrailingTrivia(); trailingTrivia = AddTriviaIfNecessary(trailingTrivia, block.CloseBraceToken.LeadingTrivia); trailingTrivia = AddTriviaIfNecessary(trailingTrivia, block.CloseBraceToken.TrailingTrivia); trailingTrivia = trailingTrivia.TrimEnd().Add(CSharpFactory.NewLine()); var switchStatement = (SwitchStatementSyntax)switchSection.Parent; if (!switchStatement.Sections.IsLast(switchSection)) { trailingTrivia = trailingTrivia.Add(CSharpFactory.NewLine()); } SyntaxList <StatementSyntax> newStatements = statements.ReplaceAt(0, statements[0].WithLeadingTrivia(leadingTrivia)); newStatements = newStatements.ReplaceAt(newStatements.Count - 1, newStatements.Last().WithTrailingTrivia(trailingTrivia)); SwitchSectionSyntax newSwitchSection = switchSection .WithStatements(newStatements) .WithFormatterAnnotation(); return(document.ReplaceNodeAsync(switchSection, newSwitchSection, cancellationToken)); SyntaxTriviaList AddTriviaIfNecessary(SyntaxTriviaList trivia, SyntaxTriviaList triviaToAdd) { if (triviaToAdd.Any(f => f.IsKind(SyntaxKind.SingleLineCommentTrivia))) { trivia = trivia.AddRange(triviaToAdd); } return(trivia); } }
public static TNode TrimTrailingTrivia <TNode>(this TNode node) where TNode : SyntaxNode { if (node == null) { throw new ArgumentNullException(nameof(node)); } SyntaxTriviaList trailingTrivia = node.GetTrailingTrivia(); SyntaxTriviaList newTrailingTrivia = trailingTrivia.TrimEnd(); if (trailingTrivia.Count != newTrailingTrivia.Count) { return(node.WithTrailingTrivia(newTrailingTrivia)); } else { return(node); } }