2

I am trying to learn roslyn and I want to change all whitespaces in my methods to same length.

For example I want to change this:

private void Method()
{
    int a=2;
        int b=4;
                int c;
    if (b != 0)
    {
        c = (a / b);
    }
}

To something like this (I want to ignore braces):

private void Method()
{
        int a=2;
        int b=4;
        int c;
        if (b != 0)
    {
        c = (a / b);
    }
}

I tried to VisitBlock and then change leadingTrivia of every statement.

I have my statements in IEnumerable Inteface and I have list for new statements

IEnumerable<StatementSyntax> statements = node.Statements.OfType<StatementSyntax>();
var newStatements = new SyntaxList<SyntaxNode>();

Then i am creating new whitespace trivia

Next I am making new statements in loop and finally I am creating new block.

foreach (var statement in statements)
{
    StatementSyntax newStatement = statement.WithLeadingTrivia(newWhiteSpace);
    newStatements = newStatements.Insert(newStatements.Count, newStatement);
}
var newBlock = SyntaxFactory.Block(newStatements)
node = node.ReplaceNode(node, newBlock);

This works almost fine for me but when I have statemenets bigger than 1 line, only 1st line is changed.

Luke1000
  • 21
  • 3
  • 1
    That sounds.. horrible. Aside from the lunatic reasons why you would want to do this: can you flesh your question out more? Which parts should be intended and which shouldn't? What about even more nested calls? – Jeroen Vannevel Oct 30 '16 at 21:48
  • I am just trying to understand roslyn. I am fighting with this exercise whole day and I just want to know how to do this. I dont care about nested calls. I want to modify simply methods. I added my sad code to first post. – Luke1000 Oct 30 '16 at 22:35
  • The code is a bit confusing to read but I would definitely suggest to use the `DocumentEditor` when you change multiple pieces of code. The sympton you describe sounds like it will be solved with this. – Jeroen Vannevel Oct 30 '16 at 22:38
  • http://stackoverflow.com/questions/19711218/how-to-add-white-space-and-or-format-code – m0sa Oct 31 '16 at 20:46

0 Answers0