//! A long text cut into PAGES for a card that holds a page at a time (the //! deck's note face, programme cardtrial). A transform over a text (contract //! 2): it names no table and no column. The card says how much it holds — the //! characters a typed line takes and the lines a page takes, the first page //! shorter because the title sits over it — and the text is laid out the way //! a typewriter lays it: words wrapped at the line's end, a word longer than //! a line broken, a blank line between paragraphs kept, no page starting on a //! blank line, and no last page holding one line alone: the line before it //! goes over with it. Worked out when the card is drawn, never stored. use std::ops::Range; /// How much a card's page holds. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PageRoom { /// Characters a line holds. pub columns: usize, /// Lines the first page holds. pub first: usize, /// Lines every later page holds. pub rest: usize, } /// Each page of `text`, as the byte range it covers. An empty text is one /// empty page. pub fn pages(text: &str, room: PageRoom) -> Vec> { let columns = room.columns.max(1); let lines = wrap(text, columns); // Each page as the run of lines it holds, its blank lines at either end // left off. let mut cut: Vec> = Vec::new(); let mut at = 0; while at < lines.len() { // A page never opens on a blank line. while at < lines.len() && lines[at].is_empty() { at += 1; } if at == lines.len() { break; } let holds = if cut.is_empty() { room.first } else { room.rest }.max(1); let end = (at + holds).min(lines.len()); let last = (at..end).rev().find(|&index| !lines[index].is_empty()).unwrap_or(at); cut.push(at..last + 1); at = end; } lone_last_line(&lines, &mut cut, room.rest); let mut pages: Vec> = cut.into_iter().map(|run| lines[run.start].start..lines[run.end - 1].end).collect(); if pages.is_empty() { pages.push(0..0); } pages } /// NO LAST PAGE OF ONE LINE ALONE, where a page holds two: the line before it /// goes over with it, so long as the page it leaves keeps a line of its own. /// The core's rule, so no face works around a lone line itself. fn lone_last_line(lines: &[Range], cut: &mut [Range], rest: usize) { let written = |run: &Range| run.clone().filter(|&index| !lines[index].is_empty()).count(); let [.., before, last] = cut else { return }; if rest < 2 || written(last) != 1 || written(before) < 2 { return; } let moved = before.end - 1; let kept = (before.start..moved).rev().find(|&index| !lines[index].is_empty()).unwrap_or(before.start); *before = before.start..kept + 1; *last = moved..last.end; } /// The text's typed lines, each the byte range of its words; a blank line /// is an empty range. fn wrap(text: &str, columns: usize) -> Vec> { let mut lines = Vec::new(); let mut offset = 0; for paragraph in text.split('\n') { let base = offset; offset += paragraph.len() + 1; let paragraph = paragraph.trim_end(); if paragraph.trim().is_empty() { lines.push(base..base); continue; } let mut line: Option<(usize, usize, usize)> = None; // start, end, chars for (start, word) in words(paragraph) { let (start, end) = (base + start, base + start + word.len()); let width = word.chars().count(); match line { Some((from, _, used)) if used + 1 + width <= columns => line = Some((from, end, used + 1 + width)), _ => { if let Some((from, to, _)) = line.take() { lines.push(from..to); } if width <= columns { line = Some((start, end, width)); } else { // A word longer than a line is broken across lines. let mut piece = start; let mut count = 0; for (index, character) in word.char_indices() { if count == columns { lines.push(piece..start + index); piece = start + index; count = 0; } count += 1; let _ = character; } line = Some((piece, end, count)); } } } } if let Some((from, to, _)) = line { lines.push(from..to); } } lines } /// The words of a line and where each starts. fn words(paragraph: &str) -> impl Iterator { paragraph .split(' ') .scan(0usize, |at, word| { let start = *at; *at += word.len() + 1; Some((start, word)) }) .filter(|(_, word)| !word.is_empty()) } #[cfg(test)] mod tests { use super::*; fn cut(text: &str, columns: usize, first: usize, rest: usize) -> Vec<&str> { pages(text, PageRoom { columns, first, rest }).into_iter().map(|range| &text[range]).collect() } // The page break a reader sees is where the typewriter would have run // out of card: no word split while it fits, the first page shorter by the // title, a paragraph's blank line kept inside a page but never opening one, // and nothing of the text lost or repeated across the pages. #[test] fn a_text_is_cut_where_the_card_runs_out() { let text = "one two three four five six\n\nseven eight nine ten"; assert_eq!(cut(text, 9, 2, 3), vec!["one two three", "four five six", "seven eight nine ten"]); assert_eq!(cut(text, 40, 2, 2), vec!["one two three four five six", "seven eight nine ten"]); assert_eq!(cut(text, 40, 5, 5), vec![text]); assert_eq!(cut("", 10, 3, 3), vec![""]); assert_eq!(cut("abcdefghij", 4, 1, 1), vec!["abcd", "efgh", "ij"]); assert_eq!(cut("naïve café crème", 6, 1, 1), vec!["naïve", "café", "crème"]); let long = "word ".repeat(400); let room = PageRoom { columns: 30, first: 8, rest: 14 }; let words: usize = pages(&long, room).iter().map(|range| long[range.clone()].split_whitespace().count()).sum(); assert_eq!(words, 400, "every word lands on exactly one page"); } // Markdown is stored text to this cutter. Setting happens over the full // source on the phone; a cut inside a delimiter or a fence must remain a // source range, never a rewritten string that loses its context. #[test] fn markdown_cuts_keep_the_stored_source() { let text = "**one two three four**\n```text\nfive six\n```"; assert_eq!(cut(text, 8, 1, 1), vec!["**one", "two", "three", "four**", "```text", "five six", "```"]); let ranges = pages(text, PageRoom { columns: 8, first: 1, rest: 1 }); assert!(ranges.windows(2).all(|pair| pair[0].end <= pair[1].start)); assert_eq!(ranges.iter().map(|r| text[r.clone()].split_whitespace().count()).sum::(), text.split_whitespace().count()); } // A last page of one line alone reads as a page cut short: the line // before it goes over with it — unless the page it leaves would keep // none, or a page holds one line anyway. #[test] fn no_last_page_holds_one_line_alone() { assert_eq!(cut("a b c", 1, 2, 2), vec!["a", "b c"]); assert_eq!(cut("a b c d e", 1, 2, 2), vec!["a b", "c", "d e"]); assert_eq!(cut("a\n\nb c", 1, 2, 2), vec!["a", "b c"], "a page's blank line is left behind, never carried"); assert_eq!(cut("a b c", 1, 1, 1), vec!["a", "b", "c"], "a page of one line has nothing to carry"); assert_eq!(cut("a b", 1, 1, 2), vec!["a", "b"], "the page it would leave keeps none"); let long = "word ".repeat(31); let room = PageRoom { columns: 4, first: 10, rest: 10 }; let cut: Vec<_> = pages(&long, room).iter().map(|range| long[range.clone()].split_whitespace().count()).collect(); assert_eq!(cut, vec![10, 10, 9, 2], "the page before the last gives it one line"); } }