Skip to content
This repository was archived by the owner on Nov 24, 2022. It is now read-only.

Commit 4bb94ff

Browse files
committed
Formatting: Trim base indentation off code block content
1 parent 60fe2a2 commit 4bb94ff

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

TabletBot.Discord/Formatting.cs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
using System;
2+
using System.Linq;
23
using System.Text;
4+
using System.Text.RegularExpressions;
35
using Discord;
46

57
namespace TabletBot.Discord
@@ -23,9 +25,24 @@ public static string CodeBlock(string text, string? lang = null) =>
2325
public static void AppendCodeBlock(this StringBuilder stringBuilder, string[] lines, string? lang = null)
2426
{
2527
stringBuilder.AppendLine(CODE_BLOCK + lang);
26-
foreach (var line in lines)
28+
foreach (var line in TrimBaseIndentation(lines))
2729
stringBuilder.AppendLine(line);
2830
stringBuilder.AppendLine(CODE_BLOCK);
2931
}
32+
33+
public static string[] TrimBaseIndentation(string[] lines)
34+
{
35+
var baseIndentationLength = lines.Min(line => {
36+
var indentation = CountIndentation(line);
37+
return line.Length > indentation ? indentation : int.MaxValue;
38+
});
39+
40+
for (int i = 0; i != lines.Length; i++)
41+
lines[i] = lines[i].Substring(Math.Min(baseIndentationLength, lines[i].Length)).TrimEnd();
42+
43+
return lines;
44+
}
45+
46+
public static int CountIndentation(string line) => line.TakeWhile(Char.IsWhiteSpace).Count();
3047
}
3148
}

0 commit comments

Comments
 (0)