djs_formatters/markdown.rs
1//! Markdown: emphasis, code, quotes, headings, lists and links.
2//!
3//! Every formatter takes any [`Display`](fmt::Display) content, so they nest without
4//! allocating: `bold(italic("x"))` is `**_x_**`. They do not escape the content: escape text
5//! from users with [`escape_markdown`](crate::escape_markdown) first.
6
7use core::fmt;
8
9/// Defines a formatter wrapping its content between two markers.
10macro_rules! wrapper {
11 (
12 $(#[$meta:meta])*
13 $function:ident => $type:ident, $open:literal, $close:literal,
14 $js:literal, $example:literal => $output:literal
15 ) => {
16 #[doc = concat!("Content written as `", $open, "…", $close, "`. Returned by [`", stringify!($function), "`].")]
17 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18 #[must_use = "a formatter does nothing until it is written"]
19 pub struct $type<T>(T);
20
21 $(#[$meta])*
22 ///
23 #[doc = concat!("discord.js counterpart: `", $js, "`.")]
24 ///
25 /// # Examples
26 ///
27 /// ```
28 #[doc = concat!("use djs_formatters::", stringify!($function), ";")]
29 ///
30 #[doc = concat!("assert_eq!(", stringify!($function), "(", $example, ").to_string(), ", $output, ");")]
31 /// ```
32 pub const fn $function<T: fmt::Display>(content: T) -> $type<T> {
33 $type(content)
34 }
35
36 impl<T: fmt::Display> fmt::Display for $type<T> {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 write!(f, concat!($open, "{}", $close), self.0)
39 }
40 }
41 };
42}
43
44wrapper! {
45 /// Shows `content` in bold: `**content**`.
46 bold => Bold, "**", "**", "bold", r#""important""# => r#""**important**""#
47}
48
49wrapper! {
50 /// Shows `content` in italics: `_content_`.
51 italic => Italic, "_", "_", "italic", r#""maybe""# => r#""_maybe_""#
52}
53
54wrapper! {
55 /// Underlines `content`: `__content__`.
56 underline => Underline, "__", "__", "underline", r#""note""# => r#""__note__""#
57}
58
59wrapper! {
60 /// Strikes `content` through: `~~content~~`.
61 strikethrough => Strikethrough, "~~", "~~", "strikethrough", r#""old""# => r#""~~old~~""#
62}
63
64wrapper! {
65 /// Hides `content` until it is clicked: `||content||`.
66 spoiler => Spoiler, "||", "||", "spoiler", r#""the ending""# => r#""||the ending||""#
67}
68
69wrapper! {
70 /// Shows `content` as code on one line: `` `content` ``.
71 ///
72 /// The content cannot contain a backtick; a code block can.
73 inline_code => InlineCode, "`", "`", "inlineCode", r#""cargo build""# => r#""`cargo build`""#
74}
75
76wrapper! {
77 /// Quotes one line: `> content`.
78 ///
79 /// Only the first line is quoted; [`block_quote`] quotes everything after it.
80 quote => Quote, "> ", "", "quote", r#""well said""# => r#""> well said""#
81}
82
83wrapper! {
84 /// Quotes `content` and everything after it in the message: `>>> content`.
85 block_quote => BlockQuote, ">>> ", "", "blockQuote", r#""line 1\nline 2""# => r#"">>> line 1\nline 2""#
86}
87
88wrapper! {
89 /// Shows `content` small and grey, as a line of subtext: `-# content`.
90 subtext => Subtext, "-# ", "", "subtext", r#""edited""# => r#""-# edited""#
91}
92
93wrapper! {
94 /// Links to `url` without an embed preview: `<url>`.
95 hide_link_embed => HideLinkEmbed, "<", ">", "hideLinkEmbed", r#""https://example.com""# => r#""<https://example.com>""#
96}
97
98/// A code block: ```` ```language\ncontent\n``` ````. Returned by [`code_block`].
99///
100/// discord.js counterpart: the string `codeBlock` returns (`@discordjs/formatters`).
101#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
102#[must_use = "a formatter does nothing until it is written"]
103pub struct CodeBlock<'a, T> {
104 content: T,
105 language: Option<&'a str>,
106}
107
108/// Shows `content` as a block of code, highlighted for a [`language`](CodeBlock::language)
109/// such as `rust` if set (D-213).
110///
111/// The content cannot contain three backticks in a row.
112///
113/// discord.js counterpart: `codeBlock`.
114///
115/// # Examples
116///
117/// ```
118/// use djs_formatters::code_block;
119///
120/// assert_eq!(code_block("let x = 1;").to_string(), "```\nlet x = 1;\n```");
121/// assert_eq!(code_block("let x = 1;").language("rust").to_string(), "```rust\nlet x = 1;\n```");
122/// ```
123pub const fn code_block<'a, T: fmt::Display>(content: T) -> CodeBlock<'a, T> {
124 CodeBlock {
125 content,
126 language: None,
127 }
128}
129
130impl<'a, T> CodeBlock<'a, T> {
131 /// Sets the language the code is highlighted for (`rust`, `json`, `diff`, …).
132 ///
133 /// discord.js counterpart: the `language` argument of `codeBlock` (`@discordjs/formatters`).
134 pub const fn language(mut self, language: &'a str) -> Self {
135 self.language = Some(language);
136 self
137 }
138}
139
140impl<T: fmt::Display> fmt::Display for CodeBlock<'_, T> {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 write!(
143 f,
144 "```{}\n{}\n```",
145 self.language.unwrap_or_default(),
146 self.content
147 )
148 }
149}
150
151/// The size of a [`heading`].
152///
153/// discord.js counterpart: `HeadingLevel`.
154#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
155#[non_exhaustive]
156pub enum HeadingLevel {
157 /// The largest: `# content`.
158 #[default]
159 One,
160 /// `## content`.
161 Two,
162 /// The smallest: `### content`.
163 Three,
164}
165
166/// A heading: `# content`, `## content` or `### content`. Returned by [`heading`].
167///
168/// discord.js counterpart: the string `heading` returns (`@discordjs/formatters`).
169#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
170#[must_use = "a formatter does nothing until it is written"]
171pub struct Heading<T> {
172 content: T,
173 level: HeadingLevel,
174}
175
176/// Shows `content` as a heading, the largest unless a smaller
177/// [`level`](Heading::level) is set (D-213).
178///
179/// discord.js counterpart: `heading`.
180///
181/// # Examples
182///
183/// ```
184/// use djs_formatters::{HeadingLevel, heading};
185///
186/// assert_eq!(heading("Rules").to_string(), "# Rules");
187/// assert_eq!(heading("Rules").level(HeadingLevel::Three).to_string(), "### Rules");
188/// ```
189pub const fn heading<T: fmt::Display>(content: T) -> Heading<T> {
190 Heading {
191 content,
192 level: HeadingLevel::One,
193 }
194}
195
196impl<T> Heading<T> {
197 /// Sets the size of the heading.
198 ///
199 /// discord.js counterpart: the `level` argument of `heading`, a `HeadingLevel` (`@discordjs/formatters`).
200 pub const fn level(mut self, level: HeadingLevel) -> Self {
201 self.level = level;
202 self
203 }
204}
205
206impl<T: fmt::Display> fmt::Display for Heading<T> {
207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208 let marker = match self.level {
209 HeadingLevel::One => "#",
210 HeadingLevel::Two => "##",
211 HeadingLevel::Three => "###",
212 };
213 write!(f, "{marker} {}", self.content)
214 }
215}
216
217/// A masked link: `[content](url)` or `[content](url "title")`. Returned by [`hyperlink`].
218///
219/// discord.js counterpart: the string `hyperlink` returns (`@discordjs/formatters`).
220#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
221#[must_use = "a formatter does nothing until it is written"]
222pub struct Hyperlink<'a, T, U> {
223 content: T,
224 url: U,
225 title: Option<&'a str>,
226}
227
228/// Shows `content` as a link to `url`, with a [`title`](Hyperlink::title) shown on hover if
229/// set (D-213).
230///
231/// Wrap the URL in `<…>` (`hyperlink("docs", hide_link_embed(url))`) to avoid an embed
232/// preview.
233///
234/// discord.js counterpart: `hyperlink`.
235///
236/// # Examples
237///
238/// ```
239/// use djs_formatters::hyperlink;
240///
241/// assert_eq!(
242/// hyperlink("the docs", "https://docs.rs").to_string(),
243/// "[the docs](https://docs.rs)"
244/// );
245/// assert_eq!(
246/// hyperlink("the docs", "https://docs.rs").title("Rust docs").to_string(),
247/// r#"[the docs](https://docs.rs "Rust docs")"#
248/// );
249/// ```
250pub const fn hyperlink<'a, T: fmt::Display, U: fmt::Display>(
251 content: T,
252 url: U,
253) -> Hyperlink<'a, T, U> {
254 Hyperlink {
255 content,
256 url,
257 title: None,
258 }
259}
260
261impl<'a, T, U> Hyperlink<'a, T, U> {
262 /// Sets the text shown when the link is hovered.
263 ///
264 /// discord.js counterpart: the `title` argument of `hyperlink` (`@discordjs/formatters`).
265 pub const fn title(mut self, title: &'a str) -> Self {
266 self.title = Some(title);
267 self
268 }
269}
270
271impl<T: fmt::Display, U: fmt::Display> fmt::Display for Hyperlink<'_, T, U> {
272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273 match self.title {
274 Some(title) => write!(f, "[{}]({} \"{title}\")", self.content, self.url),
275 None => write!(f, "[{}]({})", self.content, self.url),
276 }
277 }
278}
279
280/// An item of a [list](unordered_list): a line of text, or a nested list indented under the
281/// line before it.
282///
283/// A flat list takes plain [`Display`](fmt::Display) items (`&["a", "b"]`); nested lists take
284/// these.
285///
286/// discord.js counterpart: an element of a `RecursiveArray`.
287///
288/// # Examples
289///
290/// ```
291/// use djs_formatters::{ListItem, unordered_list};
292///
293/// let items = [
294/// ListItem::Text("Fruit"),
295/// ListItem::Nested(&[ListItem::Text("Apple"), ListItem::Text("Pear")]),
296/// ListItem::Text("Bread"),
297/// ];
298/// assert_eq!(unordered_list(&items).to_string(), "- Fruit\n - Apple\n - Pear\n- Bread");
299/// ```
300#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
301pub enum ListItem<'a, T> {
302 /// A line of the list.
303 Text(T),
304 /// A list nested one level deeper.
305 Nested(&'a [ListItem<'a, T>]),
306}
307
308/// What a list can hold: any [`Display`](fmt::Display) value, or a [`ListItem`].
309///
310/// Implemented by this crate only: every `Display` type and `ListItem` already are.
311///
312/// discord.js counterpart: an item of `unorderedList` and `orderedList` (`@discordjs/formatters`).
313pub trait ListEntry: private::WriteEntry {}
314
315impl<T: private::WriteEntry + ?Sized> ListEntry for T {}
316
317mod private {
318 use core::fmt;
319
320 /// How a [`ListEntry`](super::ListEntry) writes itself; private, so the trait cannot be
321 /// implemented elsewhere and its method is not part of the API.
322 pub trait WriteEntry {
323 /// Writes the entry as the line(s) of a list at `depth` (0 for the top), numbered from
324 /// `number` when the list is ordered, after a line break unless `first`. Returns the
325 /// number of the next line.
326 fn write_entry(
327 &self,
328 f: &mut fmt::Formatter<'_>,
329 depth: usize,
330 number: Option<u64>,
331 first: &mut bool,
332 ) -> Result<Option<u64>, fmt::Error>;
333 }
334
335 /// Writes one line of a list: the separator, the indentation and the marker.
336 pub(super) fn write_line(
337 f: &mut fmt::Formatter<'_>,
338 depth: usize,
339 number: Option<u64>,
340 first: &mut bool,
341 text: &dyn fmt::Display,
342 ) -> Result<Option<u64>, fmt::Error> {
343 if !*first {
344 f.write_str("\n")?;
345 }
346 *first = false;
347 for _ in 0..depth {
348 f.write_str(" ")?;
349 }
350 if let Some(number) = number {
351 write!(f, "{number}. {text}")?;
352 Ok(Some(number.saturating_add(1)))
353 } else {
354 write!(f, "- {text}")?;
355 Ok(None)
356 }
357 }
358}
359
360impl<T: fmt::Display + ?Sized> private::WriteEntry for T {
361 fn write_entry(
362 &self,
363 f: &mut fmt::Formatter<'_>,
364 depth: usize,
365 number: Option<u64>,
366 first: &mut bool,
367 ) -> Result<Option<u64>, fmt::Error> {
368 private::write_line(f, depth, number, first, &self)
369 }
370}
371
372impl<T: fmt::Display> private::WriteEntry for ListItem<'_, T> {
373 fn write_entry(
374 &self,
375 f: &mut fmt::Formatter<'_>,
376 depth: usize,
377 number: Option<u64>,
378 first: &mut bool,
379 ) -> Result<Option<u64>, fmt::Error> {
380 match self {
381 Self::Text(text) => private::write_line(f, depth, number, first, text),
382 Self::Nested(items) => {
383 // A nested ordered list counts from 1 again.
384 let mut nested = number.map(|_| 1);
385 for item in *items {
386 nested = item.write_entry(f, depth + 1, nested, first)?;
387 }
388 Ok(number)
389 }
390 }
391 }
392}
393
394/// A bulleted list: one `- item` per line. Returned by [`unordered_list`].
395///
396/// discord.js counterpart: the string `unorderedList` returns (`@discordjs/formatters`).
397#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
398#[must_use = "a formatter does nothing until it is written"]
399pub struct UnorderedList<'a, T> {
400 items: &'a [T],
401}
402
403/// Shows `items` as a bulleted list, one per line; [`ListItem::Nested`] indents a list
404/// under the line before it (two spaces per level).
405///
406/// discord.js counterpart: `unorderedList`.
407///
408/// # Examples
409///
410/// ```
411/// use djs_formatters::unordered_list;
412///
413/// assert_eq!(unordered_list(&["eggs", "milk"]).to_string(), "- eggs\n- milk");
414/// ```
415pub const fn unordered_list<T: ListEntry>(items: &[T]) -> UnorderedList<'_, T> {
416 UnorderedList { items }
417}
418
419impl<T: ListEntry> fmt::Display for UnorderedList<'_, T> {
420 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
421 let mut first = true;
422 for item in self.items {
423 item.write_entry(f, 0, None, &mut first)?;
424 }
425 Ok(())
426 }
427}
428
429/// A numbered list: `1. item`, `2. item`, … Returned by [`ordered_list`].
430///
431/// discord.js counterpart: the string `orderedList` returns (`@discordjs/formatters`).
432#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
433#[must_use = "a formatter does nothing until it is written"]
434pub struct OrderedList<'a, T> {
435 items: &'a [T],
436 start: u64,
437}
438
439/// Shows `items` as a numbered list from 1, or from [`start`](OrderedList::start) (D-213);
440/// nested lists count from 1.
441///
442/// Each line carries its own number (discord.js writes the first number on every line;
443/// Discord shows both the same way).
444///
445/// discord.js counterpart: `orderedList`.
446///
447/// # Examples
448///
449/// ```
450/// use djs_formatters::ordered_list;
451///
452/// assert_eq!(ordered_list(&["wake up", "code"]).to_string(), "1. wake up\n2. code");
453/// assert_eq!(ordered_list(&["third"]).start(3).to_string(), "3. third");
454/// ```
455pub const fn ordered_list<T: ListEntry>(items: &[T]) -> OrderedList<'_, T> {
456 OrderedList { items, start: 1 }
457}
458
459impl<T> OrderedList<'_, T> {
460 /// Sets the number of the first line (at least 1; 0 counts as 1, as in discord.js).
461 pub const fn start(mut self, start: u64) -> Self {
462 self.start = if start == 0 { 1 } else { start };
463 self
464 }
465}
466
467impl<T: ListEntry> fmt::Display for OrderedList<'_, T> {
468 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
469 let mut first = true;
470 let mut number = Some(self.start);
471 for item in self.items {
472 number = item.write_entry(f, 0, number, &mut first)?;
473 }
474 Ok(())
475 }
476}
477
478/// A text face Discord offers as a slash command, ready to send.
479///
480/// discord.js counterpart: `Faces`.
481///
482/// # Examples
483///
484/// ```
485/// use djs_formatters::Face;
486///
487/// assert_eq!(format!("{} oh well", Face::Shrug), r"¯\_(ツ)_/¯ oh well");
488/// ```
489#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
490#[non_exhaustive]
491pub enum Face {
492 /// `¯\_(ツ)_/¯` (the underscore escaped, so it is not read as italics).
493 Shrug,
494 /// `(╯°□°)╯︵ ┻━┻`.
495 Tableflip,
496 /// `┬─┬ノ( º _ ºノ)`.
497 Unflip,
498}
499
500impl Face {
501 /// The face as written in a message.
502 ///
503 /// discord.js counterpart: the values of `Faces` (`@discordjs/formatters`).
504 #[must_use]
505 pub const fn as_str(self) -> &'static str {
506 match self {
507 Self::Shrug => r"¯\_(ツ)_/¯",
508 Self::Tableflip => "(╯°□°)╯︵ ┻━┻",
509 Self::Unflip => "┬─┬ノ( º _ ºノ)",
510 }
511 }
512}
513
514impl fmt::Display for Face {
515 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
516 f.write_str(self.as_str())
517 }
518}