Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

16.3 KB
Raw Blame
//! A small parser for Discord-flavoured markdown.

use discord::model::Id;

#[derive(Clone, Debug, Default, PartialEq)]
pub struct Style {
    pub bold: bool,
    pub italic: bool,
    pub underline: bool,
    pub strike: bool,
    pub code: bool,
    /// Index of the spoiler this text belongs to (for click-to-reveal).
    pub spoiler: Option<usize>,
}

#[derive(Clone, Debug, PartialEq)]
pub enum Inline {
    Text(String, Style),
    Link { text: String, url: String, style: Style },
    User(Id),
    Channel(Id),
    Role(Id),
    Emoji { name: String, id: Id, animated: bool },
    /// A Unicode emoji sequence, drawn as a Twemoji image.
    Unicode { seq: String, style: Style },
    Timestamp { unix: i64, style: char },
    Everyone(&'static str),
    /// `</name:id>` slash-command mention, shown as "/name".
    Command(String),
    /// `<id:customize>` etc: server navigation shortcuts.
    Nav(&'static str),
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LineKind {
    Normal,
    Heading(u8),
    Quote,
    /// "- item" / "* item", nested by two-space indents (depth 0–2).
    Bullet(u8),
    /// "1. item" (number, depth).
    Numbered(u32, u8),
    Subtext,
}

#[derive(Clone, Debug, PartialEq)]
pub enum Block {
    Line { kind: LineKind, inlines: Vec<Inline> },
    Code { lang: String, code: String },
}

pub fn parse(src: &str) -> Vec<Block> {
    let mut blocks = Vec::new();
    let mut spoilers = 0usize;
    let mut rest = src;
    loop {
        if let Some(start) = rest.find("```") {
            if let Some(len) = rest[start + 3..].find("```") {
                parse_lines(&rest[..start], &mut blocks, &mut spoilers);
                let inner = &rest[start + 3..start + 3 + len];
                let (lang, code) = match inner.split_once('\n') {
                    Some((first, body)) if !first.is_empty() && !first.contains(' ') && first.len() < 20 => (first, body),
                    _ => ("", inner),
                };
                blocks.push(Block::Code { lang: lang.to_string(), code: code.trim_matches('\n').to_string() });
                rest = &rest[start + 3 + len + 3..];
                continue;
            }
        }
        parse_lines(rest, &mut blocks, &mut spoilers);
        return blocks;
    }
}

fn parse_lines(text: &str, blocks: &mut Vec<Block>, spoilers: &mut usize) {
    let text = text.strip_prefix('\n').unwrap_or(text);
    let text = text.strip_suffix('\n').unwrap_or(text);
    if text.is_empty() {
        return;
    }
    // Discord's lists (simple-markdown): consecutive items form one list
    // per indent level whose first item decides bullets or numbers, and the
    // numbers count up from the first one ("- a / 1. b" is two bullets).
    let mut lists: [Option<(bool, u32)>; 3] = [None; 3];
    for line in text.split('\n') {
        let (kind, body) = if let Some(b) = line.strip_prefix("### ") {
            (LineKind::Heading(3), b)
        } else if let Some(b) = line.strip_prefix("## ") {
            (LineKind::Heading(2), b)
        } else if let Some(b) = line.strip_prefix("# ") {
            (LineKind::Heading(1), b)
        } else if let Some(b) = line.strip_prefix("-# ") {
            (LineKind::Subtext, b)
        } else if let Some(b) = line.strip_prefix("> ") {
            (LineKind::Quote, b)
        } else if line == ">" {
            (LineKind::Quote, "")
        } else if let Some((kind, b)) = list_item(line) {
            (kind, b)
        } else {
            (LineKind::Normal, line)
        };
        let kind = match kind {
            LineKind::Bullet(d) | LineKind::Numbered(_, d) => {
                let d = d as usize;
                for deeper in lists.iter_mut().skip(d + 1) {
                    *deeper = None;
                }
                let start = match kind {
                    LineKind::Numbered(n, _) => (true, n),
                    _ => (false, 1),
                };
                let (ordered, n) = lists[d].get_or_insert(start);
                let out = if *ordered { LineKind::Numbered(*n, d as u8) } else { LineKind::Bullet(d as u8) };
                *n += 1;
                out
            }
            other => {
                lists = [None; 3];
                other
            }
        };
        blocks.push(Block::Line { kind, inlines: parse_inline(body, spoilers) });
    }
}

/// A list line: "- x", "* x", "1. x", indented two spaces per level.
fn list_item(line: &str) -> Option<(LineKind, &str)> {
    let body = line.trim_start_matches(' ');
    let depth = (((line.len() - body.len()) / 2).min(2)) as u8;
    if let Some(b) = body.strip_prefix("- ").or_else(|| body.strip_prefix("* ")) {
        return Some((LineKind::Bullet(depth), b));
    }
    let digits = body.chars().take_while(|c| c.is_ascii_digit()).count();
    if (1..=9).contains(&digits) {
        if let Some(b) = body[digits..].strip_prefix(". ") {
            return Some((LineKind::Numbered(body[..digits].parse().ok()?, depth), b));
        }
    }
    None
}

#[derive(Clone, Copy, PartialEq)]
enum Marker {
    Bold,
    Underline,
    Strike,
    Spoiler,
    Italic,
    ItalicUnderscore,
}

fn starts(chars: &[char], i: usize, s: &str) -> bool {
    let mut j = i;
    for c in s.chars() {
        if chars.get(j) != Some(&c) {
            return false;
        }
        j += 1;
    }
    true
}

fn find(chars: &[char], from: usize, s: &str) -> Option<usize> {
    (from..chars.len()).find(|&i| starts(chars, i, s))
}

fn marker_at(chars: &[char], i: usize) -> Option<(&'static str, Marker)> {
    const MARKERS: [(&str, Marker); 6] = [
        ("**", Marker::Bold),
        ("__", Marker::Underline),
        ("~~", Marker::Strike),
        ("||", Marker::Spoiler),
        ("*", Marker::Italic),
        ("_", Marker::ItalicUnderscore),
    ];
    MARKERS.into_iter().find(|(m, _)| starts(chars, i, m))
}

fn active(st: &Style, m: Marker) -> bool {
    match m {
        Marker::Bold => st.bold,
        Marker::Underline => st.underline,
        Marker::Strike => st.strike,
        Marker::Spoiler => st.spoiler.is_some(),
        Marker::Italic | Marker::ItalicUnderscore => st.italic,
    }
}

fn toggle(st: &mut Style, m: Marker, spoilers: &mut usize) {
    match m {
        Marker::Bold => st.bold = !st.bold,
        Marker::Underline => st.underline = !st.underline,
        Marker::Strike => st.strike = !st.strike,
        Marker::Spoiler => {
            st.spoiler = match st.spoiler {
                Some(_) => None,
                None => {
                    *spoilers += 1;
                    Some(*spoilers - 1)
                }
            }
        }
        Marker::Italic | Marker::ItalicUnderscore => st.italic = !st.italic,
    }
}

fn parse_angle(chars: &[char]) -> Option<(Inline, usize)> {
    let end = chars.iter().take(120).position(|c| *c == '>')?;
    let inner: String = chars[1..end].iter().collect();
    let len = end + 1;
    let digits = |s: &str| s.parse::<u64>().ok().map(Id);

    let inline = if let Some(cmd) = inner.strip_prefix('/') {
        // </name:id> or </name sub:id>
        let (name, id) = cmd.rsplit_once(':')?;
        digits(id)?;
        Inline::Command(name.to_string())
    } else if let Some(nav) = inner.strip_prefix("id:") {
        Inline::Nav(match nav {
            "customize" => "Channels & Roles",
            "browse" => "Browse Channels",
            "guide" => "Server Guide",
            "home" => "Server Guide",
            "linked-roles" => "Linked Roles",
            _ => return None,
        })
    } else if let Some(r) = inner.strip_prefix("@&") {
        Inline::Role(digits(r)?)
    } else if let Some(u) = inner.strip_prefix("@!").or_else(|| inner.strip_prefix('@')) {
        Inline::User(digits(u)?)
    } else if let Some(c) = inner.strip_prefix('#') {
        Inline::Channel(digits(c)?)
    } else if let Some(t) = inner.strip_prefix("t:") {
        let (unix, style) = match t.split_once(':') {
            Some((u, s)) => (u, s.chars().next().unwrap_or('f')),
            None => (t, 'f'),
        };
        Inline::Timestamp { unix: unix.parse().ok()?, style }
    } else if inner.starts_with(':') || inner.starts_with("a:") {
        let animated = inner.starts_with("a:");
        let body = inner.trim_start_matches("a:").trim_start_matches(':');
        let (name, id) = body.split_once(':')?;
        Inline::Emoji { name: name.to_string(), id: digits(id)?, animated }
    } else if inner.starts_with("http://") || inner.starts_with("https://") {
        Inline::Link { text: inner.clone(), url: inner, style: Style::default() }
    } else {
        return None;
    };
    Some((inline, len))
}

/// `[text](https://url)`
fn parse_masked(chars: &[char]) -> Option<(String, String, usize)> {
    let close = chars.iter().take(200).position(|c| *c == ']' || *c == '\n')?;
    if chars[close] != ']' || chars.get(close + 1) != Some(&'(') {
        return None;
    }
    let url_start = close + 2;
    let url_len = chars[url_start..].iter().take(500).position(|c| *c == ')' || c.is_whitespace())?;
    if chars[url_start + url_len] != ')' {
        return None;
    }
    let url: String = chars[url_start..url_start + url_len].iter().collect();
    if !(url.starts_with("https://") || url.starts_with("http://")) {
        return None;
    }
    let text: String = chars[1..close].iter().collect();
    Some((text, url, url_start + url_len + 1))
}

pub fn parse_inline(s: &str, spoilers: &mut usize) -> Vec<Inline> {
    let chars: Vec<char> = s.chars().collect();
    let mut out = Vec::new();
    let mut buf = String::new();
    let mut st = Style::default();
    let mut i = 0;

    macro_rules! flush {
        () => {
            if !buf.is_empty() {
                out.push(Inline::Text(std::mem::take(&mut buf), st.clone()));
            }
        };
    }

    while i < chars.len() {
        let c = chars[i];

        if c == '\\' && chars.get(i + 1).is_some_and(|n| n.is_ascii_punctuation()) {
            buf.push(chars[i + 1]);
            i += 2;
            continue;
        }

        if c == '`' {
            let fence = if starts(&chars, i, "``") { "``" } else { "`" };
            if let Some(end) = find(&chars, i + fence.len(), fence) {
                flush!();
                let code: String = chars[i + fence.len()..end].iter().collect();
                out.push(Inline::Text(code, Style { code: true, ..st.clone() }));
                i = end + fence.len();
                continue;
            }
        }

        if c == '<' {
            if let Some((inline, len)) = parse_angle(&chars[i..]) {
                flush!();
                out.push(inline);
                i += len;
                continue;
            }
        }

        if c == '[' {
            if let Some((text, url, len)) = parse_masked(&chars[i..]) {
                flush!();
                // Formatting inside the link text: [**bold**](…), [*it*](…).
                let mut style = st.clone();
                let mut text = text.trim().to_string();
                for (mark, bold) in [("**", true), ("__", false), ("*", false), ("_", false)] {
                    if text.len() > 2 * mark.len() && text.starts_with(mark) && text.ends_with(mark) {
                        text = text[mark.len()..text.len() - mark.len()].to_string();
                        if bold {
                            style.bold = true;
                        } else if mark == "__" {
                            style.underline = true;
                        } else {
                            style.italic = true;
                        }
                    }
                }
                out.push(Inline::Link { text, url, style });
                i += len;
                continue;
            }
        }

        if (starts(&chars, i, "https://") || starts(&chars, i, "http://"))
            && (i == 0 || !chars[i - 1].is_alphanumeric())
        {
            let mut j = i;
            while j < chars.len() && !chars[j].is_whitespace() && chars[j] != '<' && chars[j] != '>' {
                j += 1;
            }
            // A ')' ends the link only when it closes nothing inside it.
            let opened = chars[i..j].iter().filter(|c| **c == '(').count();
            let mut closed = chars[i..j].iter().filter(|c| **c == ')').count();
            while j > i {
                let last = chars[j - 1];
                let strip = match last {
                    '.' | ',' | '!' | '?' | ':' | ';' | '\'' | '"' | ']' | '*' | '~' | '|' => true,
                    ')' => opened < closed,
                    _ => false,
                };
                if !strip {
                    break;
                }
                if last == ')' {
                    closed -= 1;
                }
                j -= 1;
            }
            flush!();
            let url: String = chars[i..j].iter().collect();
            out.push(Inline::Link { text: url.clone(), url, style: st.clone() });
            i = j;
            continue;
        }

        if c == '@' {
            if let Some(word) = ["@everyone", "@here"].into_iter().find(|w| starts(&chars, i, w)) {
                flush!();
                out.push(Inline::Everyone(word));
                i += word.len();
                continue;
            }
        }

        if let Some(len) = crate::emoji::emoji_len(&chars, i) {
            flush!();
            out.push(Inline::Unicode { seq: chars[i..i + len].iter().collect(), style: st.clone() });
            i += len;
            continue;
        }

        if let Some((m, kind)) = marker_at(&chars, i) {
            let len = m.chars().count();
            let is_active = active(&st, kind);
            let word_ok = kind != Marker::ItalicUnderscore || i == 0 || !chars[i - 1].is_alphanumeric();
            let can_open = !is_active
                && word_ok
                && find(&chars, i + len, m).is_some_and(|e| e > i + len);
            if is_active || can_open {
                flush!();
                toggle(&mut st, kind, spoilers);
                i += len;
                continue;
            }
        }

        buf.push(c);
        i += 1;
    }
    flush!();
    out
}

/// True if a parsed message is only emoji (Discord shows these "jumbo").
pub fn is_emoji_only(blocks: &[Block]) -> bool {
    let mut count = 0;
    for b in blocks {
        let Block::Line { inlines, .. } = b else { return false };
        for i in inlines {
            match i {
                Inline::Unicode { .. } | Inline::Emoji { .. } => count += 1,
                Inline::Text(t, _) if t.trim().is_empty() => {}
                _ => return false,
            }
        }
    }
    (1..=27).contains(&count)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unicode_emoji_split_out() {
        let mut n = 0;
        let v = parse_inline("hi 🦀🦀", &mut n);
        assert_eq!(v.len(), 3);
        assert!(matches!(&v[1], Inline::Unicode { seq, .. } if seq == "🦀"));
        assert!(is_emoji_only(&parse("🦀 🦀")));
        assert!(!is_emoji_only(&parse("hi 🦀")));
    }

    fn texts(v: &[Inline]) -> Vec<(String, Style)> {
        v.iter()
            .filter_map(|i| match i {
                Inline::Text(t, s) => Some((t.clone(), s.clone())),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn bold_and_italic() {
        let mut n = 0;
        let v = parse_inline("a **b** *c* d", &mut n);
        let t = texts(&v);
        assert_eq!(t[1].0, "b");
        assert!(t[1].1.bold);
        assert_eq!(t[3].0, "c");
        assert!(t[3].1.italic);
    }

    #[test]
    fn lone_asterisk_is_text() {
        let mut n = 0;
        let v = parse_inline("2*3 = 6", &mut n);
        assert_eq!(v, vec![Inline::Text("2*3 = 6".into(), Style::default())]);
    }

    #[test]
    fn snake_case_not_italic() {
        let mut n = 0;
        let v = parse_inline("my_var_name", &mut n);
        assert_eq!(v, vec![Inline::Text("my_var_name".into(), Style::default())]);
    }

    #[test]
    fn mentions_links_emoji() {
        let mut n = 0;
        let v = parse_inline("hi <@123> see https://x.com/a. <:wave:456>", &mut n);
        assert!(v.contains(&Inline::User(Id(123))));
        assert!(v.iter().any(|i| matches!(i, Inline::Link { url, .. } if url == "https://x.com/a")));
        assert!(v.iter().any(|i| matches!(i, Inline::Emoji { id, .. } if *id == Id(456))));
    }

    #[test]
    fn code_block() {
        let b = parse("before\n```rust\nfn x() {}\n```\nafter");
        assert_eq!(b.len(), 3);
        assert_eq!(b[1], Block::Code { lang: "rust".into(), code: "fn x() {}".into() });
    }
}