plannotator-tui 0.15.1

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
#![allow(clippy::expect_used, clippy::indexing_slicing, reason = "tests assert by panicking")]

use super::*;

#[test]
fn splits_top_level_blocks_with_ranges() {
    let src = "# Title\n\nPara one\nstill one.\n\n- a\n- b\n\n```rs\nfn x() {}\n```\n\n---\n";
    let doc = Document::parse_into(src.to_owned(), Blocks::WHOLE);
    let kinds: Vec<_> = doc.blocks.iter().map(|b| b.kind).collect();
    assert_eq!(
        kinds,
        [BlockKind::Heading, BlockKind::Paragraph, BlockKind::List, BlockKind::CodeBlock, BlockKind::Rule]
    );
    assert_eq!(doc.block_text(0), "# Title");
    assert_eq!(doc.block_text(1), "Para one\nstill one.");
    assert_eq!(doc.block_text(3), "```rs\nfn x() {}\n```");
}

#[test]
fn front_matter_is_dropped_and_a_whole_list_is_one_block() {
    let doc = Document::parse_into("---\ntitle: X\n---\n\n- a\n  - nested\n- b\n".to_owned(), Blocks::WHOLE);
    assert_eq!(doc.blocks.len(), 1);
    assert_eq!(doc.blocks.first().map(|b| b.kind), Some(BlockKind::List));
}

fn texts(doc: &Document) -> Vec<&str> {
    (0..doc.blocks.len()).map(|i| doc.block_text(i)).collect()
}

fn items(source: &str) -> Document {
    Document::parse_into(source.to_owned(), Blocks::SPLIT)
}

#[test]
fn each_item_of_a_top_level_list_is_a_block_and_keeps_its_nested_list() {
    let doc = items("Intro.\n\n- a\n  - nested\n- b\n\n1. x\n1. y\n\n- loose\n\n- items\n");
    assert_eq!(texts(&doc), ["Intro.", "- a\n  - nested", "- b", "1. x", "1. y", "- loose", "- items"]);
    let kinds: Vec<_> = doc.blocks.iter().map(|b| b.kind).collect();
    assert_eq!(kinds[1..], [BlockKind::List; 6]);
    let joined: Vec<_> = doc.blocks.iter().map(|b| b.joined).collect();
    assert_eq!(joined, [false, false, true, false, true, false, true]);
    let loose: Vec<_> = doc.blocks.iter().map(|b| b.loose).collect();
    assert_eq!(loose, [false, false, false, false, false, true, true], "the parser's looseness, per list");
    let tops: Vec<_> = doc.blocks.iter().map(|b| b.top).collect();
    assert_eq!(tops, [0, 1, 1, 2, 2, 3, 3]);
    let numbers: Vec<_> = doc.blocks[3..5].iter().map(|b| b.opening.clone()).collect();
    assert_eq!(numbers, [Opening::Number(1), Opening::Number(2)]);
}

#[test]
fn a_quote_splits_into_its_blocks_and_a_definition_list_into_its_terms() {
    let doc = items("> one\n> two\n>\n> - a\n> - b\n\nTerm\n: one\n: two\n\nOther\n: three\n");
    assert_eq!(texts(&doc), ["> one\n> two", "> - a\n> - b", "Term\n: one\n: two", "Other\n: three"]);
    let kinds: Vec<_> = doc.blocks.iter().map(|b| b.kind).collect();
    assert_eq!(
        kinds,
        [BlockKind::BlockQuote, BlockKind::BlockQuote, BlockKind::DefinitionList, BlockKind::DefinitionList]
    );
    let joined: Vec<_> = doc.blocks.iter().map(|b| b.joined).collect();
    assert_eq!(joined, [false, false, false, true], "a quote's blocks keep a row between them");
}

/// An item ends where the next begins, without the blank `>` lines between them.
#[test]
fn a_list_in_a_quote_ends_before_the_blank_line_after_it() {
    let doc = items("> - a\n> - b\n>\n> para\n\n> 1. a\n> 2. b\n>\n> > q\n");
    assert_eq!(texts(&doc), ["> - a\n> - b", "> para", "> 1. a\n> 2. b", "> > q"]);
    let ends: Vec<_> = doc.blocks.windows(2).map(|w| w[0].range.end <= w[1].range.start).collect();
    assert_eq!(ends, [true; 3], "blocks never overlap");
}

/// A line of only `>` that is code stays in its item.
#[test]
fn an_item_keeps_code_that_ends_in_a_line_of_only_a_quote_mark() {
    assert_eq!(texts(&items("- a\n\n      code\n      >\n- b\n")), ["- a\n\n      code\n      >", "- b"]);
    assert_eq!(texts(&items("- ```\n  >\n- b\n")), ["- ```\n  >", "- b"]);
    assert_eq!(texts(&items(">     code\n>     >\n>\n> para\n")), [">     code\n>     >", "> para"]);
}

/// The whole list draws each item, and each term of a definition list, on the row after
/// the one before, tight or loose; a quote keeps a row between its blocks.
#[test]
fn the_items_of_a_list_are_joined_tight_or_loose_and_a_quotes_blocks_are_not() {
    let loose = items("- a\n\n  ```\n  x\n  ```\n- b\n");
    assert_eq!(texts(&loose), ["- a\n\n  ```\n  x\n  ```", "- b"]);
    let quote = items("> # H\n> text\n");
    assert_eq!(texts(&quote), ["> # H", "> text"]);
    assert!(quote.blocks.iter().all(|b| !b.joined));
    for list in [
        "- a\n  more\n- b\n",
        "- # A\n\n- # B\n",
        "- ```\n  x\n  ```\n\n- ```\n  y\n  ```\n",
        "- a\n\n  ```\n  x\n  ```\n- b\n",
        "Term\n: one\n\nOther\n: two\n",
    ] {
        let joined: Vec<_> = items(list).blocks.iter().map(|b| b.joined).collect();
        assert_eq!(joined, [false, true], "{list:?}");
    }
}

#[test]
fn a_list_of_one_item_stays_as_it_is() {
    let source = "- only\n  more\n";
    let doc = items(source);
    assert_eq!(texts(&doc), ["- only\n  more"]);
    assert_eq!(doc.blocks[0].opening, Opening::Plain);
}

/// Annotations keep the top-level block as their hint, so the setting never moves it.
#[test]
fn the_top_level_block_of_an_offset_is_the_same_cut_or_whole() {
    let source = "- a\n- b\n\n> c\n>\n> d\n\nPara";
    let (cut, whole) = (items(source), Document::parse_into(source.to_owned(), Blocks::WHOLE));
    assert_eq!(cut.blocks.len(), 5);
    for offset in 0..source.len() {
        assert_eq!(cut.top_block_containing(offset), whole.top_block_containing(offset), "at {offset}");
    }
    assert_eq!(cut.top_block_containing(source.find('b').expect("b")), Some(0));
    assert_eq!(cut.top_block_containing(source.find("\n>\n").expect("gap") + 1), Some(1));
    assert_eq!(cut.top_block_containing(source.find("Para").expect("para")), Some(2));
    assert_eq!(cut.top_block_containing(source.find("\n\n").expect("blank")), None);
}

/// Issue #162: a pair of rules mid-document is two rules, not front matter.
#[test]
fn rule_pair_mid_document_keeps_the_text_between() {
    let src = "# Title\n\nIntro paragraph.\n\n---\n**Draft**\n\nThis paragraph is not shown.\n\n- neither is this list\n\n---\n\nClosing paragraph.\n";
    let doc = Document::parse(src.to_owned());
    assert_eq!(
        texts(&doc),
        [
            "# Title",
            "Intro paragraph.",
            "---",
            "**Draft**",
            "This paragraph is not shown.",
            "- neither is this list",
            "---",
            "Closing paragraph."
        ]
    );
}

#[test]
fn front_matter_at_the_top_is_dropped_and_later_rules_stay() {
    let src = "---\ntitle: X\n---\n# Heading\n\n---\nkept: yes\n---\n";
    let doc = Document::parse(src.to_owned());
    assert_eq!(texts(&doc), ["# Heading", "---", "kept: yes\n---"]);
    let kinds: Vec<_> = doc.blocks.iter().map(|b| b.kind).collect();
    assert_eq!(kinds, [BlockKind::Heading, BlockKind::Rule, BlockKind::Heading]);
    // Ranges index the whole source, front matter included.
    assert_eq!(doc.blocks.first().map(|b| b.range.clone()), Some(17..26));
    assert_eq!(src.find("# Heading"), Some(17));
    assert_eq!(doc.block_containing(3), None);
}

#[test]
fn unclosed_rule_at_the_top_is_content() {
    let doc = Document::parse("---\ntitle: X\n\nBody.\n".to_owned());
    assert_eq!(texts(&doc), ["---", "title: X", "Body."]);
    // A blank second line is not front matter either, and does not move it further down.
    let doc = Document::parse("---\n\nBody.\n\n---\nmiddle\n---\n".to_owned());
    assert_eq!(texts(&doc), ["---", "Body.", "---", "middle\n---"]);
}

#[test]
fn rule_under_a_paragraph_is_a_setext_heading() {
    let doc = Document::parse("Intro\n---\nbody\n\nMore\n---\n".to_owned());
    assert_eq!(texts(&doc), ["Intro\n---", "body", "More\n---"]);
    let kinds: Vec<_> = doc.blocks.iter().map(|b| b.kind).collect();
    assert_eq!(kinds, [BlockKind::Heading, BlockKind::Paragraph, BlockKind::Heading]);
}

#[test]
fn an_agent_message_has_no_front_matter() {
    let text = "---\ntitle: X\n---\nReply.\n";
    let message = |provenance| DocumentSource::new(text.to_owned(), "m", true, provenance);
    let reply = Document::of(&message(Provenance::AgentMessage {
        host: "claude-code".into(),
        session: None,
        message_id: None,
    }));
    assert_eq!(texts(&reply), ["---", "title: X\n---", "Reply."]);
    assert_eq!(texts(&Document::of(&message(Provenance::Stdin))), ["---", "title: X\n---", "Reply."]);
    let file = Document::of(&DocumentSource::file("a.md".into(), text.to_owned()));
    assert_eq!(texts(&file), ["Reply."]);
}

/// Split, a top-level table's header and each body row are a block, drawn row after row;
/// a table in a list item stays in its item.
#[test]
fn each_row_of_a_top_level_table_is_a_block_when_split() {
    let source = "| a | b |\n|---|---|\n| x | y |\n| z | w |\n\n- item\n\n  | c |\n  |---|\n  | v |\n";
    let rows = Blocks { tables: Cut::Split, ..Blocks::WHOLE };
    let doc = Document::parse_into(source.to_owned(), rows);
    assert_eq!(texts(&doc), ["| a | b |", "| x | y |", "| z | w |", "- item\n\n  | c |\n  |---|\n  | v |"]);
    let joined: Vec<_> = doc.blocks.iter().map(|b| b.joined).collect();
    assert_eq!(joined, [false, true, true, false]);
    let tops: Vec<_> = doc.blocks.iter().map(|b| b.top).collect();
    assert_eq!(tops, [0, 0, 0, 1]);
    let header = Document::parse_into("| a |\n|---|\n".to_owned(), rows);
    assert_eq!(texts(&header), ["| a |\n|---|"], "a table of only a header stays as it is");
}

/// A definition list ends where its last definition ends, whole or split, however many terms
/// it has: the paragraph after it is a block of its own and part of no other.
#[test]
fn a_definition_list_ends_where_its_last_definition_ends() {
    let cases: [(&str, &[&str], &[&str]); 3] = [
        (
            "Term\n: a\n\nTerm2\n: b\n\nAfter",
            &["Term\n: a\n\nTerm2\n: b", "After"],
            &["Term\n: a", "Term2\n: b", "After"],
        ),
        ("Term\n: a\n\nAfter", &["Term\n: a", "After"], &["Term\n: a", "After"]),
        // `B` carries on definition `a`, so the list has one term.
        ("A\n: a\nB\n: b\n\nAfter", &["A\n: a\nB\n: b", "After"], &["A\n: a\nB\n: b", "After"]),
    ];
    for (source, whole, split) in cases {
        for (blocks, expected) in [(Blocks::WHOLE, whole), (Blocks::SPLIT, split)] {
            let doc = Document::parse_into(source.to_owned(), blocks);
            assert_eq!(texts(&doc), expected, "{source:?} cut {blocks:?}");
            let tops: Vec<_> = doc.blocks.iter().map(|b| b.top).collect();
            assert_eq!(tops.last(), Some(&1), "{source:?} cut {blocks:?}");
            assert_eq!(doc.top_block_containing(source.len() - 1), Some(1));
        }
    }
}

/// However its last definition ends, in a link reference definition, an empty definition,
/// an empty quote or an empty list item, a definition list keeps all of it and stops at the
/// blank line before the paragraph after it.
#[test]
fn a_definition_list_keeps_a_last_definition_that_ends_in_no_text() {
    for source in [
        "Term\n: see [x][r]\n\n  [r]: http://x\n\nAfter",
        "Term\n:\n\nAfter",
        "Term\n: a\n\n  >\n\nAfter",
        "Term\n: a\n\n  - b\n  -\n\nAfter",
        "Term\n: a\n\nTerm2\n:\n\nAfter",
    ] {
        let list = source.find("\n\nAfter").expect("after");
        for blocks in [Blocks::WHOLE, Blocks::SPLIT] {
            let doc = Document::parse_into(source.to_owned(), blocks);
            let what = format!("{source:?} cut {blocks:?}: {:?}", texts(&doc));
            assert!(doc.blocks.len() >= 2, "{what}");
            let (last_term, after) = (&doc.blocks[doc.blocks.len() - 2], &doc.blocks[doc.blocks.len() - 1]);
            assert_eq!(doc.blocks[0].range.start, 0, "{what}");
            assert_eq!(last_term.range.end, list, "{what}");
            assert_eq!(&source[after.range.clone()], "After", "{what}");
            assert_eq!((last_term.top, after.top), (0, 1), "{what}");
        }
    }
}

/// A note saved on a whole definition list as it used to be cut, over the paragraph after it,
/// still lands on that list once the text above it changes: the quote is in the document
/// four times, two of them with the same text around them, and the block hint picks the
/// one the note was made on.
#[test]
fn a_note_saved_over_a_definition_list_and_the_paragraph_after_finds_it_again() {
    use plannotator_tui_schema::{Anchor, Kind, Resolution, SourceRange, resolve};
    let section = "## S\n\nTerm\n: a\n\nTerm2\n: b\n\nAfter\n\n";
    let quote = "Term\n: a\n\nTerm2\n: b\n\nAfter";
    let saved_on = section.repeat(4);
    let third = section.len() * 2 + section.find("Term").expect("term");
    let range = SourceRange { start: third, end: third + quote.len(), version: "v1".into() };
    // Heading, list and paragraph in each section: the third list was top-level block 7.
    let anchor = Anchor::new(quote, &saved_on, range, Kind::Comment, Some(7));
    let edited = format!("Intro.\n\n{saved_on}");
    let moved = "Intro.\n\n".len() + third;
    for blocks in [Blocks::WHOLE, Blocks::SPLIT] {
        let doc = Document::parse_into(edited.clone(), blocks);
        let found = resolve(&anchor, &edited, |o| doc.top_block_containing(o));
        assert_eq!(found, Resolution::Range(moved..moved + quote.len()), "{blocks:?}");
        let on: Vec<_> = (0..doc.blocks.len())
            .filter(|&i| doc.overlaps(i, &(moved..moved + quote.len())))
            .map(|i| (doc.blocks[i].top, doc.blocks[i].kind))
            .collect();
        let list = BlockKind::DefinitionList;
        let expected: &[(usize, BlockKind)] = match blocks.definitions {
            Cut::Whole => &[(8, list), (9, BlockKind::Paragraph)],
            Cut::Split => &[(8, list), (8, list), (9, BlockKind::Paragraph)],
        };
        assert_eq!(on, expected, "{blocks:?}");
    }
}

/// By default a document is cut as Plannotator cuts it: each item of a list and each term
/// of a definition list is a block, a quote and a table are one.
#[test]
fn by_default_lists_and_definitions_are_split_and_a_quote_is_whole() {
    let doc = Document::parse(
        "- a\n- b\n\n> one\n>\n> two\n\nTerm\n: one\n\nOther\n: two\n\n| a |\n|---|\n| x |\n".to_owned(),
    );
    assert_eq!(
        texts(&doc),
        ["- a", "- b", "> one\n>\n> two", "Term\n: one", "Other\n: two", "| a |\n|---|\n| x |"]
    );
}