Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Code Formatter
#3
AStyle does not support some C# features, for example verbatim and raw strings. Damages these strings.

Workaround: with Roslyn find these strings and replace with safe strings. After formatting restore.

Code:
Copy      Help
// script "AStyle.cs"
/*/
role editorExtension;
testInternal Au.Editor;
r Au.Editor.dll;
r Au.Controls.dll;
c \AStyleInterface.cs;
r Roslyn\Microsoft.CodeAnalysis.dll;
r Roslyn\Microsoft.CodeAnalysis.CSharp.dll;
/*/

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.CSharp.Syntax;

//print.clear();
if (!CodeInfo.GetContextAndDocument(out var cd, metaToo: true)) return;
var text = cd.code;

var a = new List<(TextSpan, string)>();
foreach (var n in cd.syntaxRoot.DescendantNodes()) {
    //CiUtil.PrintNode(n);
    switch (n) {
    case LiteralExpressionSyntax when n.Kind() is SyntaxKind.StringLiteralExpression or SyntaxKind.Utf8StringLiteralExpression:
    case InterpolatedStringExpressionSyntax:
        //CiUtil.PrintNode(n.GetFirstToken());
        var span = n.Span;
        if (n.GetFirstToken().Kind() is SyntaxKind.StringLiteralToken && text[span.Start] != '@') continue; //simple string
        a.Add((span, text[span.Start..span.End]));
        break;
    }
}

//print.it(a);
if (a.Count > 0) {
    var b = new StringBuilder();
    int end = 0, i = 0;
    foreach (var (v, s) in a) {
        b.Append(text, end, v.Start - end);
        b.AppendFormat("\"\x1{0}\"", i++);
        end = v.End;
    }

    b.Append(text, end, text.Length - end);
    text = b.ToString();
}


var aStyle = new AStyleInterface();
text = aStyle.FormatSource(text, "style=allman");

if (a.Count > 0) {
    text = text.RxReplace(@"""\x1\d+""", m => a[text.ToInt(m.Start + 2)].Item2);
    //print.it(text);
}

Panels.Editor.ActiveDoc.EReplaceTextGently(text);



#region code to format

class C {
    public void F() {
        var a = @"verbatim
string F() {
}"
;
        
        a = """
raw
string F() {
}
"""
;
        
        a = $"""
raw
string F()
{1
            + 2}
"""
;
        
        var b = @"UTF-8
string F() {
}"u8
;
    }
}


//TODO: in the same way escape #if-disabled code
#if DEBUG
class D {
    
}
#else
class D {
    
}

#endif

#endregion


Messages In This Thread
Code Formatter - by marktech - 11-17-2022, 08:55 PM
RE: Code Formatter - by Gintaras - 02-13-2023, 01:47 PM
RE: Code Formatter - by Gintaras - 02-13-2023, 03:20 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)