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

Commit 57ee921

Browse files
committed
Formatting: Trim base indentation off code blocks
1 parent 656ab38 commit 57ee921

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

TabletBot.Discord/Formatting.cs

Lines changed: 23 additions & 0 deletions
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
@@ -22,10 +24,31 @@ public static string CodeBlock(string text, string? lang = null) =>
2224

2325
public static void AppendCodeBlock(this StringBuilder stringBuilder, string[] lines, string? lang = null)
2426
{
27+
TrimBaseIndentation(lines);
28+
2529
stringBuilder.AppendLine(CODE_BLOCK + lang);
2630
foreach (var line in lines)
2731
stringBuilder.AppendLine(line);
2832
stringBuilder.AppendLine(CODE_BLOCK);
2933
}
34+
35+
public static void TrimBaseIndentation(string[] lines)
36+
{
37+
var baseIndentationLength = lines.Min(line => {
38+
var indentation = CountIndentation(line);
39+
return line.Length > indentation ? indentation : int.MaxValue;
40+
});
41+
42+
for (int i = 0; i != lines.Length; i++)
43+
lines[i] = lines[i].Substring(Math.Min(baseIndentationLength, lines[i].Length)).TrimEnd();
44+
}
45+
46+
public static int CountIndentation(string line)
47+
{
48+
for (var i = 0; i < line.Length; i++)
49+
if (!char.IsWhiteSpace(line[i]))
50+
return i;
51+
return int.MaxValue;
52+
}
3053
}
3154
}

0 commit comments

Comments
 (0)