From be7b5f9e0d9d328ee1a5167867db62007d9c523b Mon Sep 17 00:00:00 2001 From: Chris Johnston Date: Wed, 24 Jul 2019 21:45:26 -0700 Subject: [PATCH] Implement Quote Formatting Adds support for block quote text formatting. This feature is currently only implemented in the Canary client. This formatting adds a "> " to each new line from the input text. --- src/Discord.Net.Core/Format.cs | 38 ++++++++++++++++++++++ test/Discord.Net.Tests.Unit/FormatTests.cs | 17 ++++++++++ 2 files changed, 55 insertions(+) diff --git a/src/Discord.Net.Core/Format.cs b/src/Discord.Net.Core/Format.cs index 07a9ec75c..3a04c7e6f 100644 --- a/src/Discord.Net.Core/Format.cs +++ b/src/Discord.Net.Core/Format.cs @@ -1,3 +1,5 @@ +using System.Text; + namespace Discord { /// A helper class for formatting characters. @@ -37,5 +39,41 @@ namespace Discord text = text.Replace(unsafeChar, $"\\{unsafeChar}"); return text; } + + /// + /// Formats a string as a quote. + /// + /// The text to format. + /// Gets the formatted quote text. // TODO: better xmldoc + public static string Quote(string text) + { + if (text == null) + return null; + + StringBuilder result = new StringBuilder(); + + int startIndex = 0; + int newLineIndex; + do + { + newLineIndex = text.IndexOf('\n', startIndex); + if (newLineIndex == -1) + { + // read the rest of the string + var str = text.Substring(startIndex); + result.Append($"> {str}"); + } + else + { + // read until the next newline + var str = text.Substring(startIndex, newLineIndex - startIndex); + result.Append($"> {str}\n"); + } + startIndex = newLineIndex + 1; + } + while (newLineIndex != -1 && startIndex != text.Length); + + return result.ToString(); + } } } diff --git a/test/Discord.Net.Tests.Unit/FormatTests.cs b/test/Discord.Net.Tests.Unit/FormatTests.cs index d5ab82362..7f7b54469 100644 --- a/test/Discord.Net.Tests.Unit/FormatTests.cs +++ b/test/Discord.Net.Tests.Unit/FormatTests.cs @@ -28,5 +28,22 @@ namespace Discord Assert.Equal("```cs\ntest\n```", Format.Code("test", "cs")); Assert.Equal("```cs\nanother\none\n```", Format.Code("another\none", "cs")); } + [Fact] + public void QuoteNullString() + { + Assert.Null(Format.Quote(null)); + } + [Theory] + [InlineData("", "> ")] + [InlineData("\n", "> \n")] + [InlineData("\n ", "> \n> ")] + [InlineData("input", "> input")] // single line + // should work with CR or CRLF + [InlineData("inb4\ngreentext", "> inb4\n> greentext")] + [InlineData("inb4\r\ngreentext", "> inb4\r\n> greentext")] + public void Quote(string input, string expected) + { + Assert.Equal(expected, Format.Quote(input)); + } } }