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

Commit f0c8f89

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

File tree

1 file changed

+39
-3
lines changed

1 file changed

+39
-3
lines changed

TabletBot.Discord/Formatting.cs

Lines changed: 39 additions & 3 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
@@ -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

Comments
 (0)