Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format C# code with indents programmatically

Tags:

c#

formatting

I'm making a C# application including a RichTextBox in which the user will be able to put some C# code in it and format it by indents like what Visual Studio does.

private void btnEdit_Click(object sender, EventArgs e)
{
  //rchCode.Text= formattedCode; // Which I haven't got anywhere so far
}

I looked for the same questions and this answer suggests using something called NArrange, but I don't want use other tools, add-ins or such.

Also this one offering the CodeDOM way which I haven't figure it out how to use it (If it's helpful in anyway)

I want to do it by writing some actual code. How can I do it?

like image 987
Alex Jolig Avatar asked Jan 13 '16 06:01

Alex Jolig


2 Answers

To properly indent code you would need Microsoft.CodeAnalysis.CSharp nuget package and .NET framework 4.6+. Sample code:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

...

public string ArrangeUsingRoslyn(string csCode) {
    var tree = CSharpSyntaxTree.ParseText(csCode);
    var root = tree.GetRoot().NormalizeWhitespace();
    var ret = root.ToFullString();
    return ret;
}

One-liner:

csCode = CSharpSyntaxTree.ParseText(csCode).GetRoot().NormalizeWhitespace().ToFullString();

You may also use NArrange to sort methods in your cs file, organize usings, create regions, etc.

like image 137
Anton Krouglov Avatar answered Oct 29 '22 07:10

Anton Krouglov


So I got the solution this way:

It's not still perfect (as it always add one or more new lines before the first code line). So if anyone can improve it or has a better way to do it, I'll appreciate any new suggestions.

private void btnEdit_Click(object sender, EventArgs e)
{
    RichTextBox rchTemp = new RichTextBox();
    foreach (string line in rchCode.Lines)
    {
        rchTemp.AppendText("\r\n" + line.Trim());
    }

    RichTextBox rchTemp2 = new RichTextBox();
    int indentCount = 0;
    bool shouldIndent = false;

    foreach (string line in rchTemp.Lines)
    {
        if (shouldIndent)
            indentCount++;

        if (line.Contains("}"))
            indentCount--;

        if (indentCount == 0)
        {
            rchTemp2.AppendText("\r\n" + line);
            shouldIndent = line.Contains("{");

            continue;
        }

        string blankSpace = string.Empty;
        for (int i = 0; i < indentCount; i++)
        {
            blankSpace += "    ";
        }

        rchTemp2.AppendText("\r\n" + blankSpace + line);
        shouldIndent = line.Contains("{");
    }
    rchCode.Text = rchTemp2.Text;
}
like image 2
Alex Jolig Avatar answered Oct 29 '22 07:10

Alex Jolig