plannotator-tui 0.15.1

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
//! Document model: the source text split into Markdown blocks with byte ranges.
//!
//! The parser is `pulldown-cmark`; this module only walks its event stream and records where
//! each top-level block starts and ends, and, as [`Blocks`] asks, where the items of a
//! top-level list, quote or definition list, or the rows of a top-level table, do.
//! Everything downstream (rendering, anchoring, hit-testing) is keyed by block index and byte
//! range. Nothing here knows what a heading or a list *is*.

use std::ops::Range;
use std::sync::OnceLock;

use plannotator_tui_schema::{DocumentSource, Provenance};
use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag};
use serde::{Deserialize, Serialize};

mod items;

use items::Items;

/// `[ui.blocks]`: how much of a document one block is, for moving, commenting and
/// clearing, per kind of top-level block. The default cuts as Plannotator does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub(crate) struct Blocks {
    /// Each item of a list is a block, and keeps the lists nested in it.
    pub(crate) lists: Cut,
    /// Each block inside a quote is a block.
    pub(crate) quotes: Cut,
    /// Each term of a definition list is a block, with its definitions.
    pub(crate) definitions: Cut,
    /// The header of a table is a block, and each row below it.
    pub(crate) tables: Cut,
}

/// Whether a kind of top-level block is one block or is split into its items or rows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum Cut {
    Whole,
    Split,
}

impl Blocks {
    /// Every kind whole: a top-level block is always one block.
    #[cfg(test)]
    pub(crate) const WHOLE: Self =
        Self { lists: Cut::Whole, quotes: Cut::Whole, definitions: Cut::Whole, tables: Cut::Whole };
    /// Every kind split into its items.
    pub(crate) const SPLIT: Self =
        Self { lists: Cut::Split, quotes: Cut::Split, definitions: Cut::Split, tables: Cut::Split };
}

impl Default for Blocks {
    fn default() -> Self {
        Self { quotes: Cut::Whole, tables: Cut::Whole, ..Self::SPLIT }
    }
}

static BLOCKS: OnceLock<Blocks> = OnceLock::new();

/// Cut every document this process opens as `blocks` says. The first call wins; tests and
/// headless runs get the default.
pub(crate) fn install(blocks: Blocks) {
    let _ = BLOCKS.set(blocks);
}

fn installed() -> Blocks {
    BLOCKS.get().copied().unwrap_or_default()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BlockKind {
    Heading,
    Paragraph,
    List,
    CodeBlock,
    BlockQuote,
    Table,
    DefinitionList,
    Rule,
    Html,
    Other,
}

impl BlockKind {
    /// Code and tables keep their columns; everything else word-wraps.
    pub(crate) fn preserves_columns(self) -> bool {
        matches!(self, BlockKind::CodeBlock | BlockKind::Table)
    }
}

#[derive(Debug, Clone)]
pub(crate) struct Block {
    pub(crate) range: Range<usize>,
    /// An item's kind is its container's: a list item is a `List` block, a row a `Table`.
    pub(crate) kind: BlockKind,
    pub(crate) opening: Opening,
    /// Index of the top-level Markdown block this one is, or is an item or row of.
    /// Annotations keep it as their block hint, so the hint doesn't depend on [`Blocks`].
    pub(crate) top: usize,
    /// Whether the block is drawn right under the one before it, with no row between: an
    /// item of a list or a term of a definition list after the first, as the whole list
    /// draws them, or a table row after the header.
    pub(crate) joined: bool,
    /// An item of a loose list. The list's looseness decides how each item's text is drawn,
    /// and an item read on its own may look tight.
    pub(crate) loose: bool,
}

/// What a block's opening tag says beyond its kind, passed on for the renderer's house style.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) enum Opening {
    #[default]
    Plain,
    /// A heading's level, 1 to 6.
    Heading(u8),
    /// A code block's info string: the words after the opening fence, empty for none.
    Code(Box<str>),
    /// An ordered list item's number in its list, which its own marker may not say: a list
    /// written `1.` `1.` `1.` counts 1, 2, 3.
    Number(u64),
}

fn opening_of(tag: &Tag<'_>) -> Opening {
    match tag {
        Tag::Heading { level, .. } => Opening::Heading(*level as u8),
        Tag::CodeBlock(CodeBlockKind::Fenced(info)) => Opening::Code(info.trim().into()),
        Tag::CodeBlock(CodeBlockKind::Indented) => Opening::Code("".into()),
        _ => Opening::Plain,
    }
}

#[derive(Debug, Clone)]
pub(crate) struct Document {
    pub(crate) source: String,
    pub(crate) blocks: Vec<Block>,
}

/// The option set `tui-markdown` enables, so block boundaries agree with its renderer.
pub(crate) fn parse_options() -> Options {
    Options::ENABLE_STRIKETHROUGH
        | Options::ENABLE_TASKLISTS
        | Options::ENABLE_HEADING_ATTRIBUTES
        | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS
        | Options::ENABLE_SUPERSCRIPT
        | Options::ENABLE_SUBSCRIPT
        | Options::ENABLE_MATH
        | Options::ENABLE_FOOTNOTES
        | Options::ENABLE_DEFINITION_LIST
        | Options::ENABLE_GFM
        | Options::ENABLE_TABLES
}

impl Document {
    /// A file's text: YAML front matter at the top is metadata and is not shown.
    pub(crate) fn parse(source: String) -> Self {
        Self::parse_into(source, installed())
    }

    /// [`Document::parse`], cut as `blocks` says whatever is installed.
    pub(crate) fn parse_into(source: String, blocks: Blocks) -> Self {
        let blocks = split_blocks(&source, true, blocks);
        Self { source, blocks }
    }

    /// The document for `source`. Only a file or a Workspaces document can carry front
    /// matter; an agent's message or piped text is all content, even when it opens with `---`.
    pub(crate) fn of(source: &DocumentSource) -> Self {
        let front_matter =
            matches!(source.provenance, Provenance::File { .. } | Provenance::Workspace { .. });
        let blocks = split_blocks(&source.content, front_matter, installed());
        Self { source: source.content.clone(), blocks }
    }

    /// Source text of block `index`. Empty for an out-of-range index.
    pub(crate) fn block_text(&self, index: usize) -> &str {
        self.blocks.get(index).map_or("", |b| &self.source[b.range.clone()])
    }

    /// The block whose range contains `offset`.
    pub(crate) fn block_containing(&self, offset: usize) -> Option<usize> {
        self.blocks.iter().position(|b| b.range.contains(&offset))
    }

    /// Whether `range` covers any of block `index`. A note belongs to every block it covers:
    /// one made on a whole list is on each of its items.
    pub(crate) fn overlaps(&self, index: usize, range: &Range<usize>) -> bool {
        self.blocks.get(index).is_some_and(|block| {
            if range.is_empty() {
                block.range.contains(&range.start)
            } else {
                range.start < block.range.end && block.range.start < range.end
            }
        })
    }

    /// The top-level Markdown block whose range contains `offset`, the space between two of
    /// its items included: the same index whatever [`Blocks`] the document was cut into.
    pub(crate) fn top_block_containing(&self, offset: usize) -> Option<usize> {
        let after = self.blocks.partition_point(|b| b.range.start <= offset);
        let block = self.blocks.get(after.checked_sub(1)?)?;
        let inside =
            offset < block.range.end || self.blocks.get(after).is_some_and(|next| next.top == block.top);
        inside.then_some(block.top)
    }
}

fn kind_of(tag: &Tag<'_>) -> BlockKind {
    match tag {
        Tag::Heading { .. } => BlockKind::Heading,
        Tag::Paragraph => BlockKind::Paragraph,
        Tag::List(_) => BlockKind::List,
        Tag::CodeBlock(_) => BlockKind::CodeBlock,
        Tag::BlockQuote(_) => BlockKind::BlockQuote,
        Tag::Table(_) => BlockKind::Table,
        Tag::HtmlBlock => BlockKind::Html,
        Tag::DefinitionList => BlockKind::DefinitionList,
        _ => BlockKind::Other,
    }
}

/// Bytes of the YAML front matter that opens `source`, or 0 when it has none. Front matter
/// starts on the first line and must close; `pulldown-cmark` takes a metadata block at any
/// unindented `---` line, so it is only asked about the first one.
fn front_matter_len(source: &str) -> usize {
    if !source.starts_with("---") {
        return 0;
    }
    match Parser::new_ext(source, Options::ENABLE_YAML_STYLE_METADATA_BLOCKS).into_offset_iter().next() {
        Some((Event::Start(Tag::MetadataBlock(_)), range)) if range.start == 0 => range.end,
        _ => 0,
    }
}

/// Walk the event stream and cut the source at depth-zero block boundaries, and at the
/// items of a top-level list, quote or definition list, or the rows of a top-level table,
/// when `cut` asks. Front matter, when `front_matter` allows it, is never a block; every
/// later `---` is Markdown.
fn split_blocks(source: &str, front_matter: bool, cut: Blocks) -> Vec<Block> {
    let mut blocks = Vec::new();
    let mut depth = 0usize;
    let mut open: Option<(usize, BlockKind, Opening)> = None;
    let mut items = Items::default();
    let mut tops = 0;

    let body = if front_matter { front_matter_len(source) } else { 0 };
    let mut options = parse_options();
    options.remove(Options::ENABLE_YAML_STYLE_METADATA_BLOCKS);
    for (event, range) in Parser::new_ext(&source[body..], options).into_offset_iter() {
        let range = range.start + body..range.end + body;
        let leaf = |kind| Block {
            range: range.clone(),
            kind,
            opening: Opening::Plain,
            top: tops,
            joined: false,
            loose: false,
        };
        match event {
            Event::Start(tag) => {
                if depth == 0 {
                    open = Some((range.start, kind_of(&tag), opening_of(&tag)));
                    items = Items::of(&tag, cut);
                } else if depth == 1 {
                    items.start(&tag, &range);
                } else {
                    if depth == 2 {
                        items.inner(&tag);
                    }
                    items.inside(Some(&tag), &range);
                }
                depth += 1;
            }
            Event::End(_) => {
                depth = depth.saturating_sub(1);
                if depth == 0
                    && let Some((start, kind, opening)) = open.take()
                {
                    let whole = Block {
                        range: start..items.end(kind, start, range.end),
                        kind,
                        opening,
                        top: tops,
                        joined: false,
                        loose: false,
                    };
                    match items.blocks(source, &whole) {
                        Some(each) => blocks.extend(each),
                        None => blocks.push(whole),
                    }
                    tops += 1;
                }
            }
            Event::Rule if depth == 0 => {
                blocks.push(leaf(BlockKind::Rule));
                tops += 1;
            }
            // Any other depth-zero leaf (rare: stray html/text) becomes its own block.
            _ if depth == 0 => {
                blocks.push(leaf(BlockKind::Other));
                tops += 1;
            }
            _ if depth == 1 => items.leaf(&range),
            _ => items.inside(None, &range),
        }
    }

    // A definition list never runs into the block after it, nor keeps the blank lines before.
    let starts: Vec<usize> = blocks.iter().skip(1).map(|b| b.range.start).collect();
    for (block, next) in blocks.iter_mut().zip(starts) {
        if block.kind == BlockKind::DefinitionList {
            block.range.end = block.range.end.min(next).max(block.range.start);
        }
    }
    // Trailing newlines are not part of a block's text: quotes stay stable across files
    // that differ only in final-newline conventions.
    for block in &mut blocks {
        let text = &source[block.range.clone()];
        let trimmed = match block.kind {
            BlockKind::DefinitionList => text.trim_end_matches([' ', '\t', '\n', '\r']),
            _ => text.trim_end_matches(['\n', '\r']),
        };
        block.range.end = block.range.start + trimmed.len();
    }
    blocks.retain(|b| !b.range.is_empty());
    // Count the top-level blocks that are left, so a block's `top` is its index when whole.
    let mut previous = None;
    let mut top = 0;
    for block in &mut blocks {
        if previous != Some(block.top) {
            top += usize::from(previous.is_some());
            previous = Some(block.top);
        }
        block.top = top;
    }
    blocks
}

#[cfg(test)]
mod tests;