Replacing the method body removes the next line break
I am using the following code to replace the body of Roslyn methods;
/* method is instance of MethodDeclarationSyntax */
BlockSyntax newBody = SyntaxFactory.Block(SyntaxFactory.ParseStatement("throw new NotImplementedException();"));
BlockSyntax body = method.Body;
var modifiedMethod = method.ReplaceNode(body, newBody);
But when I do this, line breaks after removing methods and after tag #region
or #endregion
after method will fail.
for example
#region
static void RemoveRegions(string str)
{
return;
}
#endregion
And after body replacement
#region
static void RemoveRegions(string str)
{
throw new NotImplementedException();
} #endregion // This cause to compiling error
source to share
The original BlockSyntax body
contained some "Trailing Trivia" as a space ( newline ) after the closing curly brace. Your constructed BlockSyntax newBody
will also contain a close curly brace, but that curly brace doesn't know if it should have spaces after it.
You can do one of three things. I think # 1 is the best option, but I list the others for completeness:
-
Reuse final trivia from the original node. ... You can use trailing trivia from the original node using GetTrailingTrivia and WithTrailingTrivia :
var originalTrailingTrivia = body.GetTrailingTrivia(); newBody = newBody.WithTrailingTrivia(originalTrailingTrivia);
In my opinion, this is your best choice. It will preserve the layout of the code, preserving any catchy little things (be it one blank line, five blank lines, zero blank lines and two spaces, one space and a comment, etc.) and will be more consistent with other scripts that you haven't came up with.
-
Format the new node. ... Let the inline Formatter decide how to handle whitespace using WithAdditionalAnnotations to add Formatter.Annotation and execute Formatter.FormatAsync on a tree containing
newBody
:newBody = newBody.WithAdditionalAnnotation(Formatter.Annotation) // Code that replaces this node back into the document var formattedDocument = Formatter.Format(document, Formatter.Annotation);
Note that this will also format the content of the method. You can only format closed curly braces and tokens around it by adding Formatter.Annotation directly to the closing curly brace, not the whole BlockSyntax, and following the same steps. This approach might make sense, but it will remove any comments or deliberately weird spaces attached to the closing curly brace.
-
Add a trailing newline manually. Create a new line manually and add it in
newBody
using WithTrailingTrivia:newBody = newBody.WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed);
This will also remove any comments or deliberately weird spaces attached to the closing curly brace. It also ignores all context and will not honor any user-specified formatting options that might change the desired layout of the method blocks.
source to share