Skip to main content

djs_formatters/
escape.rs

1//! Escaping markdown so that text is shown as written (D-212).
2
3use std::borrow::Cow;
4
5/// Which kinds of markdown [`escape`](Self::escape) neutralizes.
6///
7/// [`new`](Self::new) (and `Default`) gives discord.js' defaults: everything except
8/// headings, lists and masked links; [`none`](Self::none) starts from nothing. Each setter
9/// turns one kind on or off.
10///
11/// # Rules
12///
13/// Escaping puts a backslash before the characters that would start formatting. The rules:
14///
15/// - **Asterisks and underscores** are escaped by run: [`bold`](EscapeOptions::bold) (`**`)
16///   and [`underline`](EscapeOptions::underline) (`__`) escape a run two characters at a
17///   time, [`italic`](EscapeOptions::italic) a single one — a run of one, or the first of an
18///   odd run. With both (the default) every character of the run is escaped.
19/// - **Tildes and bars** are escaped in pairs (`~~` for strikethrough, `||` for spoilers); a
20///   single `~` or `|` formats nothing and is kept.
21/// - **Backticks:** runs of one or two are escaped for [inline code](EscapeOptions::inline_code),
22///   runs of three or more for [code blocks](EscapeOptions::code_block). Turning off
23///   [`code_block_content`](EscapeOptions::code_block_content) or
24///   [`inline_code_content`](EscapeOptions::inline_code_content) leaves the text between two
25///   delimiters untouched.
26/// - **Backslashes** are doubled ([`backslash`](EscapeOptions::backslash)).
27/// - At the start of a line, on request: a heading's `#`, a bullet `-` or `*`, a numbered
28///   list's `.`; and anywhere on request the `[` of a masked link `[text](url)`.
29/// - **Links and tokens are copied as they are:** a link (`http://` or `https://`, up to the
30///   next whitespace) and a `<…>` token on one line — a mention, emoji, timestamp, guild
31///   navigation, e-mail, phone or hidden link: content starting with `@`, `#`, `+` or
32///   containing `:` or `@` without whitespace, or a command mention `</name …:id>`. Escaping
33///   them would break them.
34///
35/// For ordinary text the result is the same as discord.js'. In unusual input it differs on
36/// purpose: every backtick of a long run is escaped (discord.js leaves the fourth of four
37/// alone), every masked link of a line is escaped (discord.js only the first), text after a
38/// custom emoji on the same line is still escaped (discord.js stops escaping `_` there), and
39/// nothing inside a link is touched (discord.js escapes `**` and backslashes in links).
40///
41/// discord.js counterpart: `EscapeMarkdownOptions`.
42///
43/// # Examples
44///
45/// ```
46/// use djs_formatters::EscapeOptions;
47///
48/// let options = EscapeOptions::new().heading(true).code_block_content(false);
49/// assert_eq!(options.escape("# **hi**\n```**raw**```"), "\\# \\*\\*hi\\*\\*\n\\`\\`\\`**raw**\\`\\`\\`");
50/// ```
51#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
52#[expect(
53    clippy::struct_excessive_bools,
54    reason = "one switch per kind of markdown, as in discord.js"
55)]
56pub struct EscapeOptions {
57    code_block: bool,
58    inline_code: bool,
59    bold: bool,
60    italic: bool,
61    underline: bool,
62    strikethrough: bool,
63    spoiler: bool,
64    code_block_content: bool,
65    inline_code_content: bool,
66    backslash: bool,
67    heading: bool,
68    bulleted_list: bool,
69    numbered_list: bool,
70    masked_link: bool,
71}
72
73impl Default for EscapeOptions {
74    fn default() -> Self {
75        Self::new()
76    }
77}
78
79/// Defines the setters of [`EscapeOptions`].
80macro_rules! setters {
81    ($($(#[$meta:meta])* $field:ident,)*) => {
82        $(
83            $(#[$meta])*
84            pub const fn $field(mut self, on: bool) -> Self {
85                self.$field = on;
86                self
87            }
88        )*
89    };
90}
91
92impl EscapeOptions {
93    /// discord.js' defaults: code, emphasis, strikethrough, spoilers and backslashes are
94    /// escaped, also inside code; headings, lists and masked links are not.
95    #[must_use]
96    pub const fn new() -> Self {
97        Self {
98            code_block: true,
99            inline_code: true,
100            bold: true,
101            italic: true,
102            underline: true,
103            strikethrough: true,
104            spoiler: true,
105            code_block_content: true,
106            inline_code_content: true,
107            backslash: true,
108            heading: false,
109            bulleted_list: false,
110            numbered_list: false,
111            masked_link: false,
112        }
113    }
114
115    /// Nothing escaped, but code content not skipped: a start for escaping a few kinds.
116    ///
117    /// discord.js counterpart: `EscapeMarkdownOptions` with every option `false` (`@discordjs/formatters`).
118    #[must_use]
119    pub const fn none() -> Self {
120        Self {
121            code_block: false,
122            inline_code: false,
123            bold: false,
124            italic: false,
125            underline: false,
126            strikethrough: false,
127            spoiler: false,
128            code_block_content: true,
129            inline_code_content: true,
130            backslash: false,
131            heading: false,
132            bulleted_list: false,
133            numbered_list: false,
134            masked_link: false,
135        }
136    }
137
138    setters! {
139        /// Escapes runs of three or more backticks (code blocks). Default: on.
140        #[must_use]
141        code_block,
142        /// Escapes runs of one or two backticks (inline code). Default: on.
143        #[must_use]
144        inline_code,
145        /// Escapes `**`. Default: on.
146        #[must_use]
147        bold,
148        /// Escapes a single `*` or `_`. Default: on.
149        #[must_use]
150        italic,
151        /// Escapes `__`. Default: on.
152        #[must_use]
153        underline,
154        /// Escapes `~~`. Default: on.
155        #[must_use]
156        strikethrough,
157        /// Escapes `||`. Default: on.
158        #[must_use]
159        spoiler,
160        /// Escapes the text inside code blocks too; off leaves it as written. Default: on.
161        #[must_use]
162        code_block_content,
163        /// Escapes the text inside inline code too; off leaves it as written. Default: on.
164        #[must_use]
165        inline_code_content,
166        /// Doubles backslashes. Default: on. (discord.js: the `escape` option.)
167        #[must_use]
168        backslash,
169        /// Escapes the `#` of a heading at the start of a line. Default: off.
170        #[must_use]
171        heading,
172        /// Escapes a `-` or `*` bullet at the start of a line. Default: off.
173        #[must_use]
174        bulleted_list,
175        /// Escapes the `.` of a numbered list item (`1.`) at the start of a line. Default: off.
176        #[must_use]
177        numbered_list,
178        /// Escapes the `[` of a masked link `[text](url)`. Default: off.
179        #[must_use]
180        masked_link,
181    }
182
183    /// Escapes the enabled kinds of markdown in `text`, borrowing it when nothing needs
184    /// escaping. See the [type docs](Self#rules) for the rules.
185    ///
186    /// discord.js counterpart: `escapeMarkdown(text, options)`.
187    #[must_use]
188    pub fn escape<'a>(&self, text: &'a str) -> Cow<'a, str> {
189        let mut scanner = Scanner {
190            options: *self,
191            bytes: text.as_bytes(),
192            text,
193            out: None,
194            copied: 0,
195            line: Line::NONE,
196        };
197        scanner.run();
198        scanner.finish()
199    }
200}
201
202/// Escapes `text` with discord.js' defaults ([`EscapeOptions::new`]): emphasis, code,
203/// strikethrough, spoilers and backslashes, outside links and mentions.
204///
205/// discord.js counterpart: `escapeMarkdown`.
206///
207/// # Examples
208///
209/// ```
210/// use djs_formatters::escape_markdown;
211///
212/// assert_eq!(escape_markdown("**not bold** and `code`"), r"\*\*not bold\*\* and \`code\`");
213/// // Links and mentions keep working:
214/// assert_eq!(escape_markdown("see https://x.dev/a_b_c by <@1>"), "see https://x.dev/a_b_c by <@1>");
215/// // Nothing to escape: the text is borrowed.
216/// assert!(matches!(escape_markdown("plain"), std::borrow::Cow::Borrowed(_)));
217/// ```
218#[must_use]
219pub fn escape_markdown(text: &str) -> Cow<'_, str> {
220    EscapeOptions::new().escape(text)
221}
222
223/// Defines the single-kind escapers.
224macro_rules! escapers {
225    ($($function:ident => $option:ident, $js:literal, $what:literal, $input:literal => $output:literal;)*) => {
226        $(
227            #[doc = concat!("Escapes only ", $what, " in `text` ([`EscapeOptions::", stringify!($option), "`]).")]
228            ///
229            #[doc = concat!("discord.js counterpart: `", $js, "`.")]
230            ///
231            /// # Examples
232            ///
233            /// ```
234            #[doc = concat!("assert_eq!(djs_formatters::", stringify!($function), "(", $input, "), ", $output, ");")]
235            /// ```
236            #[must_use]
237            pub fn $function(text: &str) -> Cow<'_, str> {
238                EscapeOptions::none().$option(true).escape(text)
239            }
240        )*
241    };
242}
243
244escapers! {
245    escape_code_block => code_block, "escapeCodeBlock", "runs of three or more backticks",
246        r#""```rust```""# => r#"r"\`\`\`rust\`\`\`""#;
247    escape_inline_code => inline_code, "escapeInlineCode", "runs of one or two backticks",
248        r#""`a` ``b``""# => r#"r"\`a\` \`\`b\`\`""#;
249    escape_bold => bold, "escapeBold", "`**`", r#""**a**""# => r#"r"\*\*a\*\*""#;
250    escape_italic => italic, "escapeItalic", "a single `*` or `_`",
251        r#""*a* _b_""# => r#"r"\*a\* \_b\_""#;
252    escape_underline => underline, "escapeUnderline", "`__`", r#""__a__""# => r#"r"\_\_a\_\_""#;
253    escape_strikethrough => strikethrough, "escapeStrikethrough", "`~~`",
254        r#""~~a~~ ~b""# => r#"r"\~\~a\~\~ ~b""#;
255    escape_spoiler => spoiler, "escapeSpoiler", "`||`", r#""||a||""# => r#"r"\|\|a\|\|""#;
256    escape_escape => backslash, "escapeEscape", "backslashes", r#"r"a\b""# => r#"r"a\\b""#;
257    escape_heading => heading, "escapeHeading", "headings at the start of a line",
258        r###""## Title""### => r###"r"\## Title""###;
259    escape_bulleted_list => bulleted_list, "escapeBulletedList",
260        "bullets at the start of a line", r#""- item""# => r#"r"\- item""#;
261    escape_numbered_list => numbered_list, "escapeNumberedList",
262        "numbered list items at the start of a line", r#""1. item""# => r#"r"1\. item""#;
263    escape_masked_link => masked_link, "escapeMaskedLink", "masked links",
264        r#""[a](https://b.c)""# => r#"r"\[a](https://b.c)""#;
265}
266
267/// No position: an unset mark.
268const NONE: usize = usize::MAX;
269
270/// What the line being scanned needs escaped apart from single characters.
271#[derive(Clone, Copy, Debug)]
272struct Line {
273    /// The index after the line's `\n` (or the text's end).
274    end: usize,
275    /// Positions to escape at the start of the line: a bullet, a heading's `#`, a numbered
276    /// item's `.`.
277    marks: [usize; 3],
278    /// The last `](` of the line followed by a URL and `)`: a `[` at least two bytes before
279    /// it starts a masked link.
280    link_middle: usize,
281}
282
283impl Line {
284    /// No line loaded yet: nothing marked.
285    const NONE: Self = Self {
286        end: 0,
287        marks: [NONE; 3],
288        link_middle: NONE,
289    };
290}
291
292/// One pass over the text, copying it lazily into `out` from the first escape on.
293struct Scanner<'a> {
294    options: EscapeOptions,
295    text: &'a str,
296    bytes: &'a [u8],
297    out: Option<String>,
298    copied: usize,
299    line: Line,
300}
301
302/// Whether `byte` is whitespace for links and tokens.
303const fn is_space(byte: u8) -> bool {
304    matches!(byte, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C)
305}
306
307/// A lookup table of the bytes in `bytes`.
308const fn table(bytes: &[u8]) -> [bool; 256] {
309    let mut table = [false; 256];
310    let mut index = 0;
311    while index < bytes.len() {
312        table[bytes[index] as usize] = true;
313        index += 1;
314    }
315    table
316}
317
318/// The bytes the scanner stops at: markdown characters, `<` (tokens) and `:` (links); every
319/// other byte is copied without a look.
320static STOPS: [bool; 256] = table(b"<\\*_~|`[:");
321/// [`STOPS`] plus what line starts need: line breaks and the characters of the marks.
322static LINE_STOPS: [bool; 256] = table(b"<\\*_~|`[:\n#-.");
323
324impl<'a> Scanner<'a> {
325    /// Puts a backslash before the byte at `index` (an ASCII character, so a char boundary);
326    /// indexes come in increasing order.
327    fn escape_at(&mut self, index: usize) {
328        let out = self
329            .out
330            .get_or_insert_with(|| String::with_capacity(self.text.len() + 16));
331        out.push_str(&self.text[self.copied..index]);
332        out.push('\\');
333        self.copied = index;
334    }
335
336    fn finish(self) -> Cow<'a, str> {
337        match self.out {
338            None => Cow::Borrowed(self.text),
339            Some(mut out) => {
340                out.push_str(&self.text[self.copied..]);
341                Cow::Owned(out)
342            }
343        }
344    }
345
346    /// The length of the run of `byte` starting at `start`.
347    fn run_length(&self, start: usize, byte: u8) -> usize {
348        self.bytes[start..]
349            .iter()
350            .position(|&other| other != byte)
351            .unwrap_or(self.bytes.len() - start)
352    }
353
354    fn is_mark(&self, index: usize) -> bool {
355        self.line.marks.contains(&index)
356    }
357
358    fn run(&mut self) {
359        let options = self.options;
360        let lines = options.heading
361            || options.bulleted_list
362            || options.numbered_list
363            || options.masked_link;
364        let stops = if lines { &LINE_STOPS } else { &STOPS };
365        let len = self.bytes.len();
366        let mut index = 0;
367        while index < len {
368            match self.bytes[index..]
369                .iter()
370                .position(|&byte| stops[usize::from(byte)])
371            {
372                Some(offset) => index += offset,
373                None => break,
374            }
375            if lines && index >= self.line.end {
376                self.load_line(index);
377            }
378            index = match self.bytes[index] {
379                b':' => self.link(index),
380                b'<' => self.token(index),
381                b'\\' => {
382                    if self.options.backslash {
383                        self.escape_at(index);
384                    }
385                    index + 1
386                }
387                b'*' => self.emphasis(index, b'*', self.options.bold),
388                b'_' => self.emphasis(index, b'_', self.options.underline),
389                b'~' => self.pairs(index, b'~', self.options.strikethrough),
390                b'|' => self.pairs(index, b'|', self.options.spoiler),
391                b'`' => self.backticks(index),
392                b'[' => {
393                    let middle = self.line.link_middle;
394                    if self.options.masked_link && middle != NONE && middle >= index + 2 {
395                        self.escape_at(index);
396                    }
397                    index + 1
398                }
399                _ => {
400                    if self.is_mark(index) {
401                        self.escape_at(index);
402                    }
403                    index + 1
404                }
405            };
406        }
407    }
408
409    /// Prepares the line containing `index`: where it ends, and what its start and masked
410    /// links need escaped.
411    fn load_line(&mut self, index: usize) {
412        let bytes = self.bytes;
413        let previous_end = self.line.end.min(index);
414        let start = bytes[previous_end..index]
415            .iter()
416            .rposition(|&byte| byte == b'\n')
417            .map_or(previous_end, |offset| previous_end + offset + 1);
418        let end = bytes[index..]
419            .iter()
420            .position(|&byte| byte == b'\n')
421            .map_or(bytes.len(), |offset| index + offset + 1);
422        let content_end = if end > start && bytes[end - 1] == b'\n' {
423            end - 1
424        } else {
425            end
426        };
427        let line = &bytes[start..content_end];
428        let mut marks = [NONE; 3];
429        let options = self.options;
430        if options.bulleted_list || options.heading || options.numbered_list {
431            let spaces = line.iter().take_while(|&&byte| byte == b' ').count();
432            // `- item` / `* item`.
433            if options.bulleted_list
434                && matches!(line.get(spaces), Some(b'-' | b'*'))
435                && line.get(spaces + 1) == Some(&b' ')
436            {
437                marks[0] = start + spaces;
438            }
439            // `# Title`, `## Title`, `### Title`, also after up to two spaces and a bullet.
440            if options.heading {
441                let mut at = spaces;
442                if spaces <= 2
443                    && matches!(line.get(at), Some(b'-' | b'*'))
444                    && line.get(at + 1) == Some(&b' ')
445                {
446                    at += 2;
447                    at += line[at..].iter().take_while(|&&byte| byte == b' ').count();
448                }
449                let hashes = line[at..].iter().take_while(|&&byte| byte == b'#').count();
450                if (1..=3).contains(&hashes) && line.get(at + hashes) == Some(&b' ') {
451                    marks[1] = start + at;
452                }
453            }
454            // `1. item`.
455            if options.numbered_list {
456                let digits = line[spaces..]
457                    .iter()
458                    .take_while(|byte| byte.is_ascii_digit())
459                    .count();
460                if digits > 0 && line.get(spaces + digits) == Some(&b'.') {
461                    marks[2] = start + spaces + digits;
462                }
463            }
464        }
465        let mut link_middle = NONE;
466        if options.masked_link
467            && let Some(close) = line.iter().rposition(|&byte| byte == b')')
468            && close >= 3
469        {
470            // The last `](` with at least one byte of URL before the `)`.
471            link_middle = line[..close - 1]
472                .windows(2)
473                .rposition(|pair| pair == b"](")
474                .map_or(NONE, |middle| start + middle);
475        }
476        self.line = Line {
477            end,
478            marks,
479            link_middle,
480        };
481    }
482
483    /// Copies a link (`http://` or `https://` up to the next whitespace) as it is, found at
484    /// its `:`; the scheme before it holds nothing to escape.
485    fn link(&self, index: usize) -> usize {
486        let bytes = self.bytes;
487        let is_link = bytes[index..].starts_with(b"://")
488            && bytes.get(index + 3).is_some_and(|&byte| !is_space(byte))
489            && ((index >= 5 && bytes[index - 5..index].eq_ignore_ascii_case(b"https"))
490                || (index >= 4 && bytes[index - 4..index].eq_ignore_ascii_case(b"http")));
491        if !is_link {
492            return index + 1;
493        }
494        let rest = &bytes[index + 3..];
495        index
496            + 3
497            + rest
498                .iter()
499                .position(|&byte| is_space(byte))
500                .unwrap_or(rest.len())
501    }
502
503    /// Copies a `<…>` token (see the type docs) as it is.
504    fn token(&self, index: usize) -> usize {
505        let rest = &self.bytes[index + 1..];
506        let Some(close) = rest
507            .iter()
508            .position(|&byte| matches!(byte, b'<' | b'>' | b'\n'))
509        else {
510            return index + 1;
511        };
512        if rest[close] != b'>' || close == 0 {
513            return index + 1;
514        }
515        let content = &rest[..close];
516        let protected = if content[0] == b'/' {
517            // `</name sub:id>`: a colon followed by digits at the end.
518            let digits = content
519                .iter()
520                .rev()
521                .take_while(|byte| byte.is_ascii_digit())
522                .count();
523            digits > 0 && content.len() > digits + 1 && content[content.len() - digits - 1] == b':'
524        } else {
525            !content.iter().any(|&byte| is_space(byte))
526                && (matches!(content[0], b'@' | b'#' | b'+')
527                    || content.iter().any(|&byte| matches!(byte, b':' | b'@')))
528        };
529        if protected {
530            index + close + 2
531        } else {
532            index + 1
533        }
534    }
535
536    /// Escapes a run of `*` or `_`: in pairs for bold / underline (`pairs`), a single one for
537    /// italics, or all of it with both.
538    fn emphasis(&mut self, index: usize, byte: u8, pairs: bool) -> usize {
539        let length = self.run_length(index, byte);
540        let single = self.options.italic;
541        for offset in 0..length {
542            let escaped = match (pairs, single) {
543                (true, true) => true,
544                (true, false) => offset < length / 2 * 2,
545                (false, true) => length % 2 == 1 && offset == 0,
546                (false, false) => false,
547            };
548            if escaped || self.is_mark(index + offset) {
549                self.escape_at(index + offset);
550            }
551        }
552        index + length
553    }
554
555    /// Escapes a run of `~` or `|` in pairs.
556    fn pairs(&mut self, index: usize, byte: u8, on: bool) -> usize {
557        let length = self.run_length(index, byte);
558        if on {
559            for offset in 0..length / 2 * 2 {
560                self.escape_at(index + offset);
561            }
562        }
563        index + length
564    }
565
566    /// Escapes `count` bytes from `index`.
567    fn escape_all(&mut self, index: usize, count: usize) {
568        for offset in 0..count {
569            self.escape_at(index + offset);
570        }
571    }
572
573    /// Handles a run of backticks: code delimiters, possibly skipping the code between two.
574    fn backticks(&mut self, index: usize) -> usize {
575        let options = self.options;
576        // Checked before measuring the run: a block may use only the start of a long run, and
577        // measuring all of it at every block would take quadratic time.
578        if !options.code_block_content && self.bytes[index..].starts_with(b"```") {
579            let after = index + 3;
580            let close = self.bytes[after..]
581                .windows(3)
582                .position(|window| window == b"```")
583                .map(|offset| after + offset);
584            if options.code_block {
585                self.escape_all(index, 3);
586            }
587            let Some(close) = close else {
588                return after;
589            };
590            if options.code_block {
591                self.escape_all(close, 3);
592            }
593            return close + 3;
594        }
595        let length = self.run_length(index, b'`');
596        if length == 1 && !options.inline_code_content {
597            let close = self.single_backtick(index + 1);
598            if options.inline_code {
599                self.escape_at(index);
600            }
601            let Some(close) = close else {
602                return index + 1;
603            };
604            if options.inline_code {
605                self.escape_at(close);
606            }
607            return close + 1;
608        }
609        let on = if length >= 3 {
610            options.code_block
611        } else {
612            options.inline_code
613        };
614        if on {
615            self.escape_all(index, length);
616        }
617        index + length
618    }
619
620    /// The next backtick standing alone from `from`, not past a code block when code block
621    /// content is skipped.
622    fn single_backtick(&self, from: usize) -> Option<usize> {
623        let mut index = from;
624        while let Some(offset) = self.bytes[index..].iter().position(|&byte| byte == b'`') {
625            let start = index + offset;
626            let length = self.run_length(start, b'`');
627            if length == 1 {
628                return Some(start);
629            }
630            if length >= 3 && !self.options.code_block_content {
631                return None;
632            }
633            index = start + length;
634        }
635        None
636    }
637}