diff --git a/TabletBot.Discord/Formatting.cs b/TabletBot.Discord/Formatting.cs index 3b06307..a91ce87 100644 --- a/TabletBot.Discord/Formatting.cs +++ b/TabletBot.Discord/Formatting.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.Text; using Discord; @@ -22,10 +23,31 @@ public static string CodeBlock(string text, string? lang = null) => public static void AppendCodeBlock(this StringBuilder stringBuilder, string[] lines, string? lang = null) { + TrimBaseIndentation(lines); + stringBuilder.AppendLine(CODE_BLOCK + lang); foreach (var line in lines) stringBuilder.AppendLine(line); stringBuilder.AppendLine(CODE_BLOCK); } + + public static void TrimBaseIndentation(string[] lines) + { + var baseIndentationLength = lines.Min(line => { + var indentation = CountIndentation(line); + return line.Length > indentation ? indentation : int.MaxValue; + }); + + for (int i = 0; i != lines.Length; i++) + lines[i] = lines[i].Substring(Math.Min(baseIndentationLength, lines[i].Length)).TrimEnd(); + } + + public static int CountIndentation(string line) + { + for (var i = 0; i < line.Length; i++) + if (!char.IsWhiteSpace(line[i])) + return i; + return int.MaxValue; + } } -} \ No newline at end of file +}