I am trying to turn
namespace DevComponents.WpfEditors.Primitives
{
/// <summary>
/// Interaction logic for EditorFreeTextButton.xaml
/// </summary>
public partial class EditorFreeTextButton : EditorButton
{
public EditorFreeTextButton()
{
InitializeComponent();
}
}
}
into
namespace DevComponents.WpfEditors.Primitives
{
/// <summary>
/// Interaction logic for EditorFreeTextButton.xaml
/// </summary>
[System.Reflection.Obfuscation(Exclude = true)]
public partial class EditorFreeTextButton : EditorButton
{
public EditorFreeTextButton()
{
InitializeComponent();
}
}
}
through Roslyn. I have the following code that works
private static SyntaxNode AddAnnotation(ClassDeclarationSyntax classNode, SyntaxNode rootNode)
{
var name = SyntaxFactory.ParseName("System.Reflection.Obfuscation");
var arguments = SyntaxFactory.ParseAttributeArgumentList("(Exclude = true)");
var attribute = SyntaxFactory.Attribute(name, arguments);
var leadingTrivia = classNode.GetLeadingTrivia();
var whitespace = leadingTrivia.LastOrDefault(x => x.Kind() == SyntaxKind.WhitespaceTrivia);
var attributeList = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(attribute))
.WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed);
var newClassNode = classNode.WithoutLeadingTrivia()
.WithLeadingTrivia(whitespace)
.AddAttributeLists(attributeList)
.WithLeadingTrivia(leadingTrivia);
rootNode = rootNode.ReplaceNode(classNode, newClassNode);
return rootNode;
}
However I feel like I am coding in circles to get all the leading Trivia right.
Is there a easier way to insert an attribute to be after the SingleLineDocumentationCommentTrivia
and be formatted correctly with the correct leading whitespace trivia?
1 Answer 1
Look into the WithAnnotation(Formatter.Annotation)
member. This should create a new node with the correct leading indentation.
var newClassNode = classNode.AddAttributeLists(attributeList)
.WithAnnotation(Formatter.Annotation)
-
\$\begingroup\$ That puts the annotation before the
SingleLineDocumentationCommentTrivia
. however theFormatter.Annotation
might be useful \$\endgroup\$Scott Chamberlain– Scott Chamberlain2016年10月25日 19:43:27 +00:00Commented Oct 25, 2016 at 19:43 -
\$\begingroup\$ OK, I'll delete this then. \$\endgroup\$user34073– user340732016年10月25日 19:44:08 +00:00Commented Oct 25, 2016 at 19:44
Formatter.Annotation
more. \$\endgroup\$