plannotator-tui 0.15.0

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
//! The items of a top-level list, quote or definition list, or the rows of a top-level
//! table, as blocks of their own when [`Blocks`] splits that kind.

use std::ops::Range;

use pulldown_cmark::Tag;

use super::{Block, BlockKind, Blocks, Cut, Opening, kind_of};

/// The items of the top-level block being walked, when it is a list, quote, definition
/// list or table its [`Blocks`] splits: each child of a list or quote, each definition list
/// term with its definitions, a table's header and each of its rows.
#[derive(Default)]
pub(super) struct Items {
    /// The block's kind; any other kind has no items.
    kind: Option<BlockKind>,
    /// The next number of an ordered list.
    number: Option<u64>,
    /// Whether text sits in a paragraph right in a list item: the parser's word that the
    /// list is loose.
    paragraphs: bool,
    children: Vec<Item>,
}

struct Item {
    start: usize,
    /// Where the last text, code or other content inside the item ends. A container's own
    /// end may run on over blank lines and the next line's `>`.
    content: Option<usize>,
    opening: Opening,
}

impl Items {
    /// The items of the top-level block `tag` opens, cut as `blocks` says.
    pub(super) fn of(tag: &Tag<'_>, blocks: Blocks) -> Self {
        let kind = Some(kind_of(tag)).filter(|kind| {
            let cut = match kind {
                BlockKind::List => blocks.lists,
                BlockKind::BlockQuote => blocks.quotes,
                BlockKind::DefinitionList => blocks.definitions,
                BlockKind::Table => blocks.tables,
                _ => Cut::Whole,
            };
            cut == Cut::Split
        });
        let number = match tag {
            Tag::List(start) => *start,
            _ => None,
        };
        Self { kind, number, paragraphs: false, children: Vec::new() }
    }

    /// A child of the block opens at `range`.
    pub(super) fn start(&mut self, tag: &Tag<'_>, range: &Range<usize>) {
        let opening = match (self.kind, tag) {
            (Some(BlockKind::List), Tag::Item) => match self.number.as_mut() {
                Some(next) => {
                    *next += 1;
                    Opening::Number(*next - 1)
                }
                None => Opening::Plain,
            },
            (Some(BlockKind::BlockQuote), _)
            | (Some(BlockKind::DefinitionList), Tag::DefinitionListTitle)
            | (Some(BlockKind::Table), Tag::TableHead | Tag::TableRow) => Opening::Plain,
            // A term's definitions belong to the term.
            _ => {
                self.inside(Some(tag), range);
                return;
            }
        };
        self.children.push(Item { start: range.start, content: None, opening });
        self.inside(Some(tag), range);
    }

    /// A grandchild of the block opens: a paragraph right in a list item makes the list loose.
    pub(super) fn inner(&mut self, tag: &Tag<'_>) {
        if self.kind == Some(BlockKind::List) && matches!(tag, Tag::Paragraph) {
            self.paragraphs = true;
        }
    }

    /// An event at `range` inside the block's current child: a tag it opens, or `None` for
    /// text, code, a rule and the like.
    pub(super) fn inside(&mut self, tag: Option<&Tag<'_>>, range: &Range<usize>) {
        let container = matches!(
            tag,
            Some(
                Tag::List(_)
                    | Tag::Item
                    | Tag::BlockQuote(_)
                    | Tag::DefinitionList
                    | Tag::DefinitionListDefinition
                    | Tag::FootnoteDefinition(_)
            )
        );
        if let Some(item) = self.children.last_mut().filter(|_| !container) {
            item.content = Some(item.content.map_or(range.end, |end| end.max(range.end)));
        }
    }

    /// A rule or HTML directly inside a quote is one of its items.
    pub(super) fn leaf(&mut self, range: &Range<usize>) {
        if self.kind == Some(BlockKind::BlockQuote) {
            self.children.push(Item {
                start: range.start,
                content: Some(range.end),
                opening: Opening::Plain,
            });
        }
    }

    /// The block's items, when it has more than one: each from the start of its first line,
    /// so its text keeps the marker or `>` before it and parses as the same kind of block,
    /// to the end of its content.
    pub(super) fn blocks(&self, source: &str, whole: &Block) -> Option<Vec<Block>> {
        if self.children.len() < 2 {
            return None;
        }
        let starts: Vec<usize> =
            self.children.iter().map(|item| line_start(source, item.start).max(whole.range.start)).collect();
        let ends: Vec<usize> = self
            .children
            .iter()
            .zip(&starts)
            .enumerate()
            .map(|(index, (item, &start))| {
                let next = starts.get(index + 1).copied().unwrap_or(whole.range.end);
                // An empty item is its marker line.
                let end = item.content.unwrap_or_else(|| line_end(source, start));
                let end = end.clamp(start, next);
                source.get(start..end).map_or(end, |text| start + text.trim_end_matches(['\n', '\r']).len())
            })
            .collect();
        // The renderer starts each item of a list and each term of a definition list on the
        // line after the one before, tight or loose: no row between them. A table's rows are
        // its lines shared out. A quote's blocks keep the row between them.
        let joined =
            matches!(self.kind, Some(BlockKind::List | BlockKind::DefinitionList | BlockKind::Table));
        let blocks = self.children.iter().zip(starts.iter().zip(&ends)).enumerate().map(
            |(index, (item, (&start, &end)))| Block {
                range: start..end,
                kind: whole.kind,
                opening: item.opening.clone(),
                top: whole.top,
                joined: index > 0 && joined,
                loose: self.paragraphs,
            },
        );
        Some(blocks.collect())
    }
}

fn line_start(source: &str, at: usize) -> usize {
    source.get(..at).and_then(|before| before.rfind('\n')).map_or(0, |newline| newline + 1)
}

fn line_end(source: &str, at: usize) -> usize {
    source.get(at..).and_then(|after| after.find('\n')).map_or(source.len(), |newline| at + newline)
}