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

Commit 98976ed

Browse files
Merge pull request #74 from vedattt/codeblock-indent-trim
Trim base indentation off code block content
2 parents 656ab38 + 2c88bd0 commit 98976ed

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

TabletBot.Discord/Formatting.cs

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

@@ -22,10 +23,31 @@ public static string CodeBlock(string text, string? lang = null) =>
2223

2324
public static void AppendCodeBlock(this StringBuilder stringBuilder, string[] lines, string? lang = null)
2425
{
26+
TrimBaseIndentation(lines);
27+
2528
stringBuilder.AppendLine(CODE_BLOCK + lang);
2629
foreach (var line in lines)
2730
stringBuilder.AppendLine(line);
2831
stringBuilder.AppendLine(CODE_BLOCK);
2932
}
33+
34+
public static void TrimBaseIndentation(string[] lines)
35+
{
36+
var baseIndentationLength = lines.Min(line => {
37+
var indentation = CountIndentation(line);
38+
return line.Length > indentation ? indentation : int.MaxValue;
39+
});
40+
41+
for (int i = 0; i != lines.Length; i++)
42+
lines[i] = lines[i].Substring(Math.Min(baseIndentationLength, lines[i].Length)).TrimEnd();
43+
}
44+
45+
public static int CountIndentation(string line)
46+
{
47+
for (var i = 0; i < line.Length; i++)
48+
if (!char.IsWhiteSpace(line[i]))
49+
return i;
50+
return int.MaxValue;
51+
}
3052
}
31-
}
53+
}

0 commit comments

Comments
 (0)