11using System ;
2+ using System . Linq ;
23using System . Text ;
4+ using System . Text . RegularExpressions ;
35using Discord ;
46
57namespace TabletBot . Discord
@@ -20,12 +22,46 @@ public static class Formatting
2022 public static string CodeBlock ( string text , string ? lang = null ) =>
2123 $ "{ CODE_BLOCK } { lang } { Environment . NewLine } { text } { Environment . NewLine } { CODE_BLOCK } ";
2224
23- public static void AppendCodeBlock ( this StringBuilder stringBuilder , string [ ] lines , string ? lang = null )
25+ public static void AppendCodeBlock ( this StringBuilder stringBuilder , string text , string ? lang = null )
2426 {
2527 stringBuilder . AppendLine ( CODE_BLOCK + lang ) ;
26- foreach ( var line in lines )
27- stringBuilder . AppendLine ( line ) ;
28+ stringBuilder . Append ( TrimBaseIndentation ( text ) ) ;
2829 stringBuilder . AppendLine ( CODE_BLOCK ) ;
2930 }
31+
32+ public static void AppendCodeBlock ( this StringBuilder stringBuilder , string [ ] lines , string ? lang = null )
33+ => AppendCodeBlock ( stringBuilder , String . Join ( Environment . NewLine , lines ) , lang ) ;
34+
35+ public static string TrimBaseIndentation ( string text )
36+ {
37+ var endsTrimmedContent = TrimStartRegex . Replace ( text . TrimEnd ( ) , "$1" , 1 ) ;
38+ var lines = endsTrimmedContent . Split ( Environment . NewLine ) ;
39+ var baseIndentationLength = CountIndentation ( lines [ 0 ] ) ;
40+
41+ for ( int i = 0 ; i != lines . Length ; i ++ )
42+ {
43+ var line = lines [ i ] ;
44+
45+ var indentationLength = CountIndentation ( line ) ;
46+ if ( indentationLength < baseIndentationLength )
47+ {
48+ if ( indentationLength == line . Length )
49+ {
50+ lines [ i ] = "" ;
51+ continue ;
52+ }
53+
54+ return endsTrimmedContent ;
55+ }
56+
57+ lines [ i ] = line . Substring ( Math . Min ( baseIndentationLength , line . Length ) ) . TrimEnd ( ) ;
58+ }
59+
60+ return String . Join ( Environment . NewLine , lines ) ;
61+ }
62+
63+ private static readonly Regex TrimStartRegex = new Regex ( "^\\ s*\n (\\ s*)(?=\\ S*)" , RegexOptions . Compiled ) ;
64+
65+ public static int CountIndentation ( string line ) => line . TakeWhile ( Char . IsWhiteSpace ) . Count ( ) ;
3066 }
3167}
0 commit comments