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?
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With