Cotton code
400 lines · 16.4 KB · RustRaw
//! The inline half: one line's content → its styled runs, its syntax marks//! and its hashtags, in byte offsets.//!//! | written            | style       |//! |--------------------|-------------|//! | `**b**`, `__b__`   | bold        |//! | `*i*`, `_i_`       | italic      |//! | `~u~`              | underline   |//! | `~~s~~`            | strike      |//! | `==h==`            | highlight   |//! | `` `c` ``          | code        |//! | `[label](url)`     | link        |//! | `![alt](src)`      | image (its alt drawn; the picture is a later round) |//! | `![alt](src)<!-- {"width":160} -->` | image at a fixed width (the comment a mark) |//! | `[[Title]]`, `[[Title/Heading]]` | note link (its target the run's url) |//! | `https://…`        | link (no marks) |//! | `#tag`, `#a/b`, `#two words#` | tag |//!//! A delimiter opens before a non-space and closes after one, on the same//! line; `_` does not open or close inside a word (`snake_case` stays//! plain). A backslash escapes the next mark.use super::style::Style;#[derive(Debug, Clone, PartialEq)]pub(crate) enum Piece {    /// A styled run of content.    Run { start: usize, end: usize, style: Style, url: Option<String> },    /// A syntax mark, and the whole element it belongs to (a cursor anywhere    /// in the element shows it dim).    Mark { start: usize, end: usize, owner: (usize, usize) },}/// One hashtag found in a text: where it is (bytes, `#` included) and its name.#[derive(Debug, Clone, PartialEq)]pub(crate) struct Found {    pub start: usize,    pub end: usize,    pub name: String,}/// The pairs a delimiter run may be, longest first.const PAIRS: [(&str, Style); 7] = [    ("**", Style::Bold),    ("__", Style::Bold),    ("~~", Style::Strike),    ("==", Style::Highlight),    ("*", Style::Italic),    ("_", Style::Italic),    ("~", Style::Underline),];pub(crate) fn parse(text: &str, from: usize, to: usize, pieces: &mut Vec<Piece>, tags: &mut Vec<Found>) {    let bytes = text.as_bytes();    // A delimiter that found no closer from some position finds none from any    // later one in this range: a line of a thousand stars stays linear.    let mut no_closer: [usize; PAIRS.len()] = [usize::MAX; PAIRS.len()];    let mut i = from;    while i < to {        let c = bytes[i];        match c {            b'\\' if i + 1 < to && bytes[i + 1].is_ascii_punctuation() => {                i += 2;            }            b'`' => {                let run = run_of(bytes, i, to, b'`');                match find_code_close(bytes, i + run, to, run) {                    Some(close) => {                        let owner = (i, close + run);                        pieces.push(Piece::Mark { start: i, end: i + run, owner });                        if close > i + run {                            pieces.push(Piece::Run { start: i + run, end: close, style: Style::Code, url: None });                        }                        pieces.push(Piece::Mark { start: close, end: close + run, owner });                        i = close + run;                    }                    None => i += run,                }            }            b'!' if i + 1 < to && bytes[i + 1] == b'[' => match link_at(text, i + 1, to) {                Some((label_end, end, url)) => {                    // A width comment straight after it belongs to the picture.                    let whole = end + width_comment(text, end, to).map_or(0, |(len, _)| len);                    let owner = (i, whole);                    pieces.push(Piece::Mark { start: i, end: i + 2, owner });                    // Always a run, empty alt too: it carries the address.                    pieces.push(Piece::Run { start: i + 2, end: label_end, style: Style::Image, url: Some(url) });                    pieces.push(Piece::Mark { start: label_end, end: whole, owner });                    i = whole;                }                None => i += 2,            },            b'[' if i + 1 < to && bytes[i + 1] == b'[' && note_link_at(text, i, to).is_some() => {                let (end, target) = note_link_at(text, i, to).unwrap_or_default();                let owner = (i, end);                pieces.push(Piece::Mark { start: i, end: i + 2, owner });                pieces.push(Piece::Run { start: i + 2, end: end - 2, style: Style::NoteLink, url: Some(target) });                pieces.push(Piece::Mark { start: end - 2, end, owner });                i = end;            }            b'[' => match link_at(text, i, to) {                Some((label_end, end, url)) => {                    let owner = (i, end);                    pieces.push(Piece::Mark { start: i, end: i + 1, owner });                    if label_end > i + 1 {                        pieces.push(Piece::Run { start: i + 1, end: label_end, style: Style::Link, url: Some(url) });                        parse(text, i + 1, label_end, pieces, tags);                    }                    pieces.push(Piece::Mark { start: label_end, end, owner });                    i = end;                }                None => i += 1,            },            b'*' | b'_' | b'~' | b'=' => {                let run = run_of(bytes, i, to, c);                let mut matched = false;                for (index, (delim, style)) in PAIRS.iter().enumerate() {                    let len = delim.len();                    if delim.as_bytes()[0] != c || run < len || i >= no_closer[index] {                        continue;                    }                    if !opens(text, i, len, to, c) {                        continue;                    }                    match find_close(text, i + len, to, c, len) {                        Some(close) => {                            let owner = (i, close + len);                            pieces.push(Piece::Mark { start: i, end: i + len, owner });                            pieces.push(Piece::Run { start: i + len, end: close, style: *style, url: None });                            parse(text, i + len, close, pieces, tags);                            pieces.push(Piece::Mark { start: close, end: close + len, owner });                            i = close + len;                            matched = true;                        }                        None => no_closer[index] = i,                    }                    if matched {                        break;                    }                }                if !matched {                    i += run;                }            }            b'#' if tag_may_start(text, i, from) => match tag_at(text, i, to) {                Some((end, name)) => {                    pieces.push(Piece::Run { start: i, end, style: Style::Tag, url: None });                    tags.push(Found { start: i, end, name });                    i = end;                }                None => i += 1,            },            b'h' if url_may_start(text, i, from) => match bare_url(text, i, to) {                Some(end) => {                    pieces.push(Piece::Run { start: i, end, style: Style::Link, url: Some(text[i..end].to_string()) });                    i = end;                }                None => i += 1,            },            _ => i += 1,        }    }}fn run_of(bytes: &[u8], at: usize, to: usize, c: u8) -> usize {    bytes[at..to].iter().take_while(|&&b| b == c).count()}fn find_code_close(bytes: &[u8], from: usize, to: usize, run: usize) -> Option<usize> {    let mut k = from;    while k < to {        if bytes[k] == b'`' {            let here = run_of(bytes, k, to, b'`');            if here == run {                return Some(k);            }            k += here;        } else {            k += 1;        }    }    None}fn char_before(text: &str, at: usize) -> Option<char> {    text[..at].chars().next_back()}fn char_after(text: &str, at: usize) -> Option<char> {    text[at..].chars().next()}/// A delimiter of `len` at `at` may open: a non-space follows, and `_` is/// not inside a word.fn opens(text: &str, at: usize, len: usize, to: usize, c: u8) -> bool {    if at + len >= to {        return false;    }    match char_after(text, at + len) {        Some(next) if !next.is_whitespace() => {}        _ => return false,    }    if c == b'_' {        if let Some(before) = char_before(text, at) {            if before.is_alphanumeric() {                return false;            }        }    }    true}/// Where a delimiter of `len` closes after `from`: a run of `c` after a/// non-space. A single mark skips a run of exactly two (that is the double/// mark's); a longer run closes at its end (`***both***`).fn find_close(text: &str, from: usize, to: usize, c: u8, len: usize) -> Option<usize> {    let bytes = text.as_bytes();    let mut k = from;    while k < to {        if bytes[k] != c {            k += 1;            continue;        }        let here = run_of(bytes, k, to, c);        let fits = if len == 1 { here == 1 || here >= 3 } else { here >= len };        if fits && k > from {            let close = k + here - len;            let before_ok = char_before(text, close).is_some_and(|b| !b.is_whitespace());            let after_ok = c != b'_' || char_after(text, close + len).is_none_or(|a| !a.is_alphanumeric());            if before_ok && after_ok {                return Some(close);            }        }        k += here;    }    None}/// `[label](url)` from the `[` at `at`: (label end, element end, url).pub(crate) fn link_at(text: &str, at: usize, to: usize) -> Option<(usize, usize, String)> {    let bytes = text.as_bytes();    let mut k = at + 1;    let mut depth = 0;    while k < to {        match bytes[k] {            b'\\' => k += 1,            b'[' => depth += 1,            b']' if depth == 0 => break,            b']' => depth -= 1,            _ => {}        }        k += 1;    }    if k >= to || k + 1 >= to || bytes[k + 1] != b'(' {        return None;    }    let label_end = k;    let mut j = k + 2;    let mut parens = 0;    while j < to {        match bytes[j] {            b'(' => parens += 1,            b')' if parens == 0 => {                let url = text[k + 2..j].trim();                let url = url.split_once(char::is_whitespace).map(|(url, _title)| url).unwrap_or(url);                return Some((label_end, j + 1, url.trim_matches(['<', '>']).to_string()));            }            b')' => parens -= 1,            _ => {}        }        j += 1;    }    None}fn tag_may_start(text: &str, at: usize, from: usize) -> bool {    if at == from {        return true;    }    match char_before(text, at) {        // A quote opening an HTML attribute's value (`href="#fn-6f1a2b3c"`, `id='#ref'`) holds an anchor, never a        // tag: notes brought in from HTML carry them by the hundred, and each was filed as a tag named like an id.        Some(q @ ('"' | '\'')) => !text[from..at - q.len_utf8()].trim_end().ends_with('='),        Some(b) => b.is_whitespace() || matches!(b, '(' | '['),        None => false,    }}fn url_may_start(text: &str, at: usize, from: usize) -> bool {    (text[at..].starts_with("https://") || text[at..].starts_with("http://"))        && (at == from || char_before(text, at).is_some_and(|b| !b.is_alphanumeric()))}fn bare_url(text: &str, at: usize, to: usize) -> Option<usize> {    let rest = &text[at..to];    let end = rest.find(|c: char| c.is_whitespace() || c == '<').unwrap_or(rest.len());    let url = rest[..end].trim_end_matches(['.', ',', ';', ':', '!', '?', ')', '\'', '"']);    let scheme = if url.starts_with("https://") { 8 } else { 7 };    (url.len() > scheme).then_some(at + url.len())}/// May `c` be inside a one-word tag? Letters, digits, `_`, `-`, `/` and any/// symbol that is not punctuation (an emoji is a fine tag).fn tag_char(c: char) -> bool {    if c.is_alphanumeric() || matches!(c, '_' | '-' | '/') {        return true;    }    if c.is_ascii() || c.is_whitespace() {        return false;    }    !matches!(c as u32, 0x2000..=0x206F | 0x3000..=0x303F | 0xFF01..=0xFF0F | 0xFF1A..=0xFF20 | 0xFF3B..=0xFF40 | 0xFF5B..=0xFF65 | 0x00A0..=0x00BF)}/// The hashtag at `at` (a `#`): its end and its name, written as it is./// `#one`, `#parent/child`, `#two words#`. A tag begins with a letter (or a/// symbol such as an emoji), never a digit: `#509` is an issue, `#1132-era`/// a reference, `#2024` a year (the owner's Words, 22 Nov 2026: assistants'/// notes cite them by the dozen, and each was filed as a tag). A heading's/// `# ` never reaches here (a space follows it).pub(crate) fn tag_at(text: &str, at: usize, to: usize) -> Option<(usize, String)> {    let first = char_after(text, at + 1)?;    if first.is_whitespace() || first == '#' || !tag_char(first) || first.is_numeric() || matches!(first, '_' | '-' | '/') || at + 1 >= to {        return None;    }    let rest = &text[at + 1..to];    let simple = rest.find(|c: char| !tag_char(c)).unwrap_or(rest.len());    if colour(&rest[..simple]) {        return None;    }    // `#two words#`: the run stopped at a space, and a `#` closes it on this    // line after a non-space, with no other `#` inside, before a boundary.    // Its first word must be a tag itself: `#2024 and C# code` is none.    if rest[simple..].starts_with(' ') && clean(&rest[..simple]).is_some() {        if let Some(close) = rest[simple..].find('#').map(|k| k + simple) {            let inside = &rest[..close];            let after = rest[close + 1..].chars().next();            let before = inside.chars().next_back();            if before.is_some_and(|b| !b.is_whitespace()) && after.is_none_or(|a| a.is_whitespace() || (a.is_ascii_punctuation() && a != '#')) {                if let Some(name) = clean(inside) {                    return Some((at + 1 + close + 1, name));                }            }        }    }    let word = rest[..simple].trim_end_matches(['-', '/']);    let end = at + 1 + word.len();    clean(word).map(|name| (end, name))}/// A colour code: 3, 4, 6 or 8 hex characters, the word ending there, in either case (`#FFF`, `#E9D9B7`, `#FFFFFF`,/// `#3a5f0bff`). Never a tag: design notes, and notes an assistant writes, hold them by the dozen, and each was filed/// as a tag (the owner's Words, 22 Nov 2026). A word of hex LETTERS alone is a colour when it has no lower-case letter/// (`#FFFFFF`, `#BEEF`) or is one letter over and over (`#fff`, `#eeeeee`), and a tag otherwise (`#facade`, `#decade`,/// `#cafe`, `#Bad`): people tag in lower case or capitalised, and colours are written upper case or as a grey. The rule cannot ask who wrote a note: every phone and the server/// read a note's text alone, so the same text always files the same tags.fn colour(word: &str) -> bool {    if !matches!(word.len(), 3 | 4 | 6 | 8) || !word.chars().all(|c| c.is_ascii_hexdigit()) {        return false;    }    let mut letters = word.chars();    let first = letters.next();    word.chars().any(|c| c.is_ascii_digit()) || !word.chars().any(|c| c.is_ascii_lowercase()) || letters.all(|c| Some(c) == first)}/// A tag's name as written: spaces collapsed, empty path parts dropped; none/// when it holds no letter.fn clean(written: &str) -> Option<String> {    let parts: Vec<String> = written        .split('/')        .map(|part| part.split_whitespace().collect::<Vec<_>>().join(" "))        .filter(|part| !part.is_empty())        .collect();    let name = parts.join("/");    (!name.is_empty() && name.chars().any(|c| !c.is_ascii_digit() && c != '/' && c != '-' && c != '_')).then_some(name)}/// `[[target]]` from the `[[` at `at`, on this line: its end (after `]]`)/// and its target as written, trimmed. No `[`, `]` or line break inside; an/// empty target is no link.pub(crate) fn note_link_at(text: &str, at: usize, to: usize) -> Option<(usize, String)> {    let rest = &text[at + 2..to];    let close = rest.find("]]")?;    let inside = &rest[..close];    if inside.contains(['[', ']']) || inside.trim().is_empty() {        return None;    }    Some((at + 2 + close + 2, inside.trim().to_string()))}/// A picture's width comment at `at` (`<!-- {"width":160} -->`, the/// reference app's own form, spaces allowed): its length in bytes and the/// width it says, in points.pub(crate) fn width_comment(text: &str, at: usize, to: usize) -> Option<(usize, f64)> {    let rest = &text[at..to];    let body = rest.strip_prefix("<!--")?;    let close = body.find("-->")?;    let said: serde_json::Value = serde_json::from_str(body[..close].trim()).ok()?;    let width = said.get("width")?.as_f64()?;    Some((4 + close + 3, width))}