using System.Text;
namespace Discord
{
/// A helper class for formatting characters.
public static class Format
{
// Characters which need escaping
private static readonly string[] SensitiveCharacters = { "\\", "*", "_", "~", "`", "|", ">" };
/// Returns a markdown-formatted string with bold formatting.
public static string Bold(string text) => $"**{text}**";
/// Returns a markdown-formatted string with italics formatting.
public static string Italics(string text) => $"*{text}*";
/// Returns a markdown-formatted string with underline formatting.
public static string Underline(string text) => $"__{text}__";
/// Returns a markdown-formatted string with strikethrough formatting.
public static string Strikethrough(string text) => $"~~{text}~~";
/// Returns a string with spoiler formatting.
public static string Spoiler(string text) => $"||{text}||";
/// Returns a markdown-formatted URL. Only works in descriptions and fields.
public static string Url(string text, string url) => $"[{text}]({url})";
/// Escapes a URL so that a preview is not generated.
public static string EscapeUrl(string url) => $"<{url}>";
/// Returns a markdown-formatted string with codeblock formatting.
public static string Code(string text, string language = null)
{
if (language != null || text.Contains("\n"))
return $"```{language ?? ""}\n{text}\n```";
else
return $"`{text}`";
}
/// Sanitizes the string, safely escaping any Markdown sequences.
public static string Sanitize(string text)
{
foreach (string unsafeChar in SensitiveCharacters)
text = text.Replace(unsafeChar, $"\\{unsafeChar}");
return text;
}
///
/// Formats a string as a quote.
///
/// The text to format.
/// Gets the formatted quote text.
public static string Quote(string text)
{
// do not modify null or whitespace text
// whitespace does not get quoted properly
if (string.IsNullOrWhiteSpace(text))
return text;
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();
}
///
/// Formats a string as a block quote.
///
/// The text to format.
/// Gets the formatted block quote text.
public static string BlockQuote(string text)
{
// do not modify null or whitespace
if (string.IsNullOrWhiteSpace(text))
return text;
return $">>> {text}";
}
}
}