Cotton code
534 lines · 20.6 KB · RustRaw
//! The styling half: a text and a cursor → one block per line and the styled//! spans over it. Both phones draw exactly these.//!//! A line is, in this order of reading: inside or opening a code fence//! (```` ``` ```` or `~~~`), a heading (`#`…`######` and a space), a divider//! (three or more `-`, `*` or `_` alone), a quote (`>`), a check item//! (`- [ ] `, `- [x] `), a bulleted item (`- `, `* `, `+ `), a numbered//! item (`1. `, `1) `), blank, else a paragraph. The first line with words,//! when it is a heading, is the TITLE.//!//! Every span says how it LOOKS: `text` (styled content), `dim` (a syntax//! mark the cursor is in), `hidden` (a syntax mark away from the cursor),//! `glyph` (drawn as a glyph instead of its characters: a bullet, a box, a//! ticked box, a rule). With no cursor (reading) every mark is hidden.//! Spans may overlap (a bold word in a link is two spans); the phone applies//! them all.use serde::{Deserialize, Serialize};use super::inline::{self, Found, Piece};use super::table::{self, Table};use super::{line_ranges, Offsets};#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum Kind {    Paragraph,    Blank,    Heading,    Bullet,    Numbered,    Check,    Quote,    Divider,    /// A fence line, opening or closing (```` ``` ````).    Fence,    /// A line inside a code block.    Code,    /// A table's header or body row.    Table,    /// A table's delimiter line (`| --- | :-: |`): drawn as no row.    TableRule,    /// A line that is one picture alone (`![words](src)`): drawn inline at    /// the full text width, its address on the block.    Picture,}impl Kind {    pub fn is_item(self) -> bool {        matches!(self, Kind::Bullet | Kind::Numbered | Kind::Check)    }}#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum Style {    /// The note's title (its first line, a heading): drawn large.    Title,    Heading,    Bold,    Italic,    Underline,    Strike,    Highlight,    Code,    CodeBlock,    Link,    Image,    /// `[[Title]]`: a link to another note, its target the span's url.    NoteLink,    Tag,    Quote,    /// A numbered item's number, drawn as written in the secondary colour.    Number,    /// A ticked item's words: drawn quieter, struck.    Done,    /// A syntax mark (`**`, `# `, `> `, `](url)`); its look says dim or hidden.    Mark,    /// Leading whitespace of an item or an indented line: always hidden, the    /// block's `depth` indents it.    Indent,}#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum Look {    Text,    Dim,    Hidden,    Glyph,}#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum Glyph {    Bullet,    Box,    Ticked,    Rule,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Block {    /// UTF-16 range of the line, without its line break.    pub start: u32,    pub end: u32,    pub kind: Kind,    /// Where the line's words start, after its marker and indent.    pub content: u32,    /// Indent level: 0 at the margin.    pub depth: u8,    /// 1–6 for a heading.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub level: Option<u8>,    /// A check item: ticked or not.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub checked: Option<bool>,    /// A numbered item's number, as written.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub number: Option<u64>,    /// The first line with words, a heading: the note's title.    #[serde(default, skip_serializing_if = "std::ops::Not::not")]    pub title: bool,    /// A picture line's address, as written.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub src: Option<String>,    /// A picture line's width: `small`, `medium` or `full`.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub width: Option<String>,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Span {    pub start: u32,    pub end: u32,    pub style: Style,    pub look: Look,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub level: Option<u8>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub glyph: Option<Glyph>,    /// A link's or an image's address.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub url: Option<String>,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Styled {    pub blocks: Vec<Block>,    pub spans: Vec<Span>,    /// Every table, its rows and cells, for the phone to draw as a grid.    pub tables: Vec<Table>,}/// One line read, in bytes.#[derive(Debug, Clone)]pub(crate) struct Line {    pub start: usize,    pub end: usize,    pub kind: Kind,    /// After the leading whitespace.    pub indent_end: usize,    /// After the marker (and its space): where the words start.    pub content: usize,    pub depth: u8,    pub level: Option<u8>,    pub checked: Option<bool>,    pub number: Option<u64>,    /// The `>` count of a quote.    pub quotes: u8,    pub title: bool,    /// For a fence, code or table line: the byte range of its whole block.    pub block: Option<(usize, usize)>,    /// A table row's place: 0 the header, then the body rows.    pub row: Option<usize>,}/// Read every line of `text`.pub(crate) fn lines(text: &str) -> Vec<Line> {    let ranges = line_ranges(text);    let mut out: Vec<Line> = Vec::with_capacity(ranges.len());    let mut fence: Option<(u8, usize, usize)> = None; // (char, length, index of the opening line)    let mut titled = false;    for (start, end) in ranges {        let line = &text[start..end];        let (cols, ws) = leading(line);        let indent_end = start + ws;        let rest = &line[ws..];        let depth = ((cols + 2) / 4).min(12) as u8;        let mut read = Line { start, end, kind: Kind::Paragraph, indent_end, content: indent_end, depth, level: None, checked: None, number: None, quotes: 0, title: false, block: None, row: None };        if let Some((mark, len, opened)) = fence {            let run = rest.bytes().take_while(|&b| b == mark).count();            if cols < 4 && run >= len && rest[run..].trim().is_empty() {                read.kind = Kind::Fence;                fence = None;                let block = (out[opened].start, end);                for earlier in out.iter_mut().skip(opened) {                    earlier.block = Some(block);                }                read.block = Some(block);            } else {                read.kind = Kind::Code;                read.content = start;                read.depth = 0;            }            out.push(read);            continue;        }        let first = rest.bytes().next();        if cols < 4 && matches!(first, Some(b'`') | Some(b'~')) {            let mark = first.unwrap();            let run = rest.bytes().take_while(|&b| b == mark).count();            if run >= 3 && !(mark == b'`' && rest[run..].contains('`')) {                read.kind = Kind::Fence;                read.content = end;                fence = Some((mark, run, out.len()));                titled = true;                out.push(read);                continue;            }        }        if rest.trim().is_empty() {            read.kind = Kind::Blank;            read.content = end;        } else if let Some(level) = heading(rest).filter(|_| cols < 4) {            read.kind = Kind::Heading;            read.level = Some(level as u8);            let after = (indent_end + level + 1).min(end);            read.content = after + text[after..end].len() - text[after..end].trim_start().len();            read.depth = 0;        } else if cols < 4 && divider(rest) {            read.kind = Kind::Divider;            read.content = end;        } else if rest.starts_with('>') {            let mut k = 0;            let bytes = rest.as_bytes();            let mut quotes = 0u8;            while k < bytes.len() && (bytes[k] == b'>' || (bytes[k] == b' ' && k + 1 < bytes.len() && bytes[k + 1] == b'>')) {                if bytes[k] == b'>' {                    quotes = quotes.saturating_add(1);                }                k += 1;            }            if k < bytes.len() && bytes[k] == b' ' {                k += 1;            }            read.kind = Kind::Quote;            read.quotes = quotes;            read.content = indent_end + k;        } else if let Some((marker, checked)) = check(rest) {            read.kind = Kind::Check;            read.checked = Some(checked);            read.content = indent_end + marker;        } else if let Some(marker) = bullet(rest) {            read.kind = Kind::Bullet;            read.content = indent_end + marker;        } else if let Some((marker, number)) = numbered(rest) {            read.kind = Kind::Numbered;            read.number = Some(number);            read.content = indent_end + marker;        } else if rest.starts_with("![")            && inline::link_at(text, indent_end + 1, end).is_some_and(|(_, close, _)| {                let after = close + inline::width_comment(text, close, end).map_or(0, |(len, _)| len);                text[after..end].trim().is_empty()            })        {            read.kind = Kind::Picture;        }        if !titled && !matches!(read.kind, Kind::Blank) {            titled = true;            read.title = read.kind == Kind::Heading;        }        out.push(read);    }    // An unclosed fence runs to the end of the text.    if let Some((_, _, opened)) = fence {        let block = (out[opened].start, text.len());        for earlier in out.iter_mut().skip(opened) {            earlier.block = Some(block);        }    }    tables(text, &mut out);    out}/// Mark the tables among paragraphs: a header holding a `|`, a delimiter/// line of as many cells, then the rows that follow.fn tables(text: &str, lines: &mut [Line]) {    let mut k = 0;    while k + 1 < lines.len() {        let head = &lines[k];        let rule = &lines[k + 1];        let fits = head.kind == Kind::Paragraph            && text[head.start..head.end].contains('|')            && matches!(rule.kind, Kind::Paragraph | Kind::Divider | Kind::Bullet)            && table::delimiter(text, rule.start, rule.end).is_some_and(|align| align.len() == table::cells(text, head.start, head.end).len());        if !fits {            k += 1;            continue;        }        let mut last = k + 1;        while last + 1 < lines.len() && lines[last + 1].kind == Kind::Paragraph && text[lines[last + 1].start..lines[last + 1].end].contains('|') {            last += 1;        }        let block = (lines[k].start, lines[last].end);        let was_title = lines[k].title;        for (place, line) in lines[k..=last].iter_mut().enumerate() {            line.kind = if place == 1 { Kind::TableRule } else { Kind::Table };            line.row = match place {                0 => Some(0),                1 => None,                n => Some(n - 1),            };            line.block = Some(block);            line.depth = 0;            line.content = line.start;            line.indent_end = line.start;            line.title = false;        }        let _ = was_title;        k = last + 1;    }}/// (columns, bytes) of leading spaces and tabs; a tab is four columns.fn leading(line: &str) -> (usize, usize) {    let mut cols = 0;    let mut bytes = 0;    for b in line.bytes() {        match b {            b' ' => cols += 1,            b'\t' => cols += 4,            _ => break,        }        bytes += 1;    }    (cols, bytes)}/// A heading's level: 1–6 `#` then a space or the end of the line.pub(crate) fn heading(rest: &str) -> Option<usize> {    let run = rest.bytes().take_while(|&b| b == b'#').count();    ((1..=6).contains(&run) && (rest.len() == run || rest.as_bytes()[run] == b' ' || rest.as_bytes()[run] == b'\t')).then_some(run)}fn divider(rest: &str) -> bool {    let trimmed = rest.trim_end();    let Some(mark) = trimmed.bytes().next().filter(|b| matches!(b, b'-' | b'*' | b'_')) else { return false };    trimmed.bytes().all(|b| b == mark || b == b' ' || b == b'\t') && trimmed.bytes().filter(|&b| b == mark).count() >= 3}/// A check item's marker length (`- [ ] `) and whether it is ticked.fn check(rest: &str) -> Option<(usize, bool)> {    let b = rest.as_bytes();    if b.len() >= 5 && matches!(b[0], b'-' | b'*' | b'+') && b[1] == b' ' && b[2] == b'[' && matches!(b[3], b' ' | b'x' | b'X') && b[4] == b']' && (b.len() == 5 || b[5] == b' ') {        Some(((b.len()).min(6), b[3] != b' '))    } else {        None    }}fn bullet(rest: &str) -> Option<usize> {    let b = rest.as_bytes();    if !b.is_empty() && matches!(b[0], b'-' | b'*' | b'+') && (b.len() == 1 || b[1] == b' ') {        Some(b.len().min(2))    } else {        None    }}fn numbered(rest: &str) -> Option<(usize, u64)> {    let digits = rest.bytes().take_while(u8::is_ascii_digit).count();    let b = rest.as_bytes();    if (1..=9).contains(&digits) && b.len() > digits && matches!(b[digits], b'.' | b')') && (b.len() == digits + 1 || b[digits + 1] == b' ') {        let number = rest[..digits].parse().ok()?;        Some(((digits + 2).min(b.len()), number))    } else {        None    }}/// Every span of one line's words (its content), in bytes, with the tags it/// holds. Exposed to [`super::derive`] and [`super::format`].pub(crate) fn inline_of(text: &str, line: &Line) -> (Vec<Piece>, Vec<Found>) {    let mut pieces = Vec::new();    let mut tags = Vec::new();    if line.kind == Kind::Table {        for cell in table::cells(text, line.start, line.end) {            inline::parse(text, cell.start, cell.end, &mut pieces, &mut tags);        }        return (pieces, tags);    }    if !matches!(line.kind, Kind::Code | Kind::Fence | Kind::Divider | Kind::Blank | Kind::TableRule) && line.content < line.end {        inline::parse(text, line.content, line.end, &mut pieces, &mut tags);    }    (pieces, tags)}fn add(spans: &mut Vec<Span>, offsets: &Offsets, start: usize, end: usize, style: Style, look: Look) {    if end > start {        spans.push(Span { start: offsets.u16(start), end: offsets.u16(end), style, look, level: None, glyph: None, url: None });    }}/// The styled text: blocks and spans for `text` with the cursor at `cursor`/// (UTF-16; `None` when reading).pub fn style(text: &str, cursor: Option<u32>) -> Styled {    let offsets = Offsets::new(text);    let cursor = cursor.map(|unit| super::byte_at(text, unit));    let read = lines(text);    let mut blocks = Vec::with_capacity(read.len());    let mut spans = Vec::new();    let near = |owner: (usize, usize)| cursor.is_some_and(|at| at >= owner.0 && at <= owner.1);    let mark_look = |owner: (usize, usize)| if near(owner) { Look::Dim } else { Look::Hidden };    let u = |byte: usize| offsets.u16(byte);    for line in &read {        blocks.push(Block {            start: u(line.start),            end: u(line.end),            kind: line.kind,            content: u(line.content),            depth: line.depth,            level: line.level,            checked: line.checked,            number: line.number,            title: line.title,            src: (line.kind == Kind::Picture).then(|| inline::link_at(text, line.indent_end + 1, line.end).map(|(_, _, url)| url)).flatten(),            width: (line.kind == Kind::Picture).then(|| picture_width(text, line).to_string()),        });        let whole = (line.start, line.end);        match line.kind {            Kind::Blank => {}            Kind::Fence => add(&mut spans, &offsets, line.start, line.end, Style::Mark, mark_look(line.block.unwrap_or(whole))),            Kind::Code => add(&mut spans, &offsets, line.start, line.end, Style::CodeBlock, Look::Text),            Kind::Divider => {                let look = if near(whole) { Look::Dim } else { Look::Glyph };                spans.push(Span { start: u(line.start), end: u(line.end), style: Style::Mark, look, level: None, glyph: (look == Look::Glyph).then_some(Glyph::Rule), url: None });            }            Kind::Heading => {                add(&mut spans, &offsets, line.start, line.content, Style::Mark, mark_look(whole));                let style = if line.title { Style::Title } else { Style::Heading };                if line.content < line.end {                    spans.push(Span { start: u(line.content), end: u(line.end), style, look: Look::Text, level: line.level, glyph: None, url: None });                }            }            Kind::Quote => {                add(&mut spans, &offsets, line.start, line.content, Style::Mark, mark_look(whole));                add(&mut spans, &offsets, line.content, line.end, Style::Quote, Look::Text);            }            Kind::Bullet | Kind::Check => {                add(&mut spans, &offsets, line.start, line.indent_end, Style::Indent, Look::Hidden);                let glyph = match line.checked {                    None => Glyph::Bullet,                    Some(false) => Glyph::Box,                    Some(true) => Glyph::Ticked,                };                spans.push(Span { start: u(line.indent_end), end: u(line.content), style: Style::Mark, look: Look::Glyph, level: None, glyph: Some(glyph), url: None });                if line.checked == Some(true) {                    add(&mut spans, &offsets, line.content, line.end, Style::Done, Look::Text);                }            }            Kind::Numbered => {                add(&mut spans, &offsets, line.start, line.indent_end, Style::Indent, Look::Hidden);                add(&mut spans, &offsets, line.indent_end, line.content, Style::Number, Look::Text);            }            Kind::TableRule => add(&mut spans, &offsets, line.start, line.end, Style::Mark, mark_look(line.block.unwrap_or(whole))),            Kind::Table => {                // The pipes and the space around them are marks; the cells' words are not.                let look = mark_look(line.block.unwrap_or(whole));                let mut at = line.start;                for cell in table::cells(text, line.start, line.end) {                    add(&mut spans, &offsets, at, cell.start, Style::Mark, look);                    at = cell.end;                }                add(&mut spans, &offsets, at, line.end, Style::Mark, look);            }            Kind::Paragraph | Kind::Picture => {}        }        for piece in inline_of(text, line).0 {            match piece {                Piece::Run { start, end, style, url } if end > start => spans.push(Span { start: u(start), end: u(end), style, look: Look::Text, level: None, glyph: None, url }),                Piece::Run { .. } => {}                Piece::Mark { start, end, owner } => {                    if end > start {                        spans.push(Span { start: u(start), end: u(end), style: Style::Mark, look: mark_look(owner), level: None, glyph: None, url: None });                    }                }            }        }    }    let mut tables = Vec::new();    let mut k = 0;    while k < read.len() {        if read[k].kind != Kind::Table {            k += 1;            continue;        }        let block = read[k].block.unwrap_or((read[k].start, read[k].end));        let mut rows = Vec::new();        let mut align = Vec::new();        while k < read.len() && read[k].block == Some(block) && matches!(read[k].kind, Kind::Table | Kind::TableRule) {            match read[k].kind {                Kind::TableRule => align = table::delimiter(text, read[k].start, read[k].end).unwrap_or_default(),                _ => rows.push((read[k].start, read[k].end)),            }            k += 1;        }        tables.push(table::to_table(text, &offsets, &rows, align, block));    }    Styled { blocks, spans, tables }}/// The fixed widths a picture is drawn at, and the points each writes in/// the reference app's comment (full writes none).pub const WIDTHS: [(&str, Option<u32>); 3] = [("small", Some(160)), ("medium", Some(320)), ("full", None)];/// The fixed width a written width (points) is drawn at: under 240 small,/// under 480 medium, else full.pub fn width_of(points: f64) -> &'static str {    if points < 240.0 {        "small"    } else if points < 480.0 {        "medium"    } else {        "full"    }}/// A picture line's fixed width, from its comment.pub(crate) fn picture_width(text: &str, line: &Line) -> &'static str {    inline::link_at(text, line.indent_end + 1, line.end)        .and_then(|(_, close, _)| inline::width_comment(text, close, line.end))        .map_or("full", |(_, points)| width_of(points))}