use std::borrow::Cow;
use crate::Record;
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Section {
All,
Commented,
Bare,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum BareStyle {
Block,
Quoted,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Descriptor {
Colour,
Kind,
Author,
Date,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Numbering {
None,
Global,
PerPage,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Escaping {
None,
Block,
Full,
Literal,
}
#[derive(Clone, Debug)]
pub struct Style {
pub order: Vec<Section>,
pub heading_all: Cow<'static, str>,
pub heading_commented: Cow<'static, str>,
pub heading_bare: Cow<'static, str>,
pub bullet: Cow<'static, str>,
pub indent: Cow<'static, str>,
pub quote: Cow<'static, str>,
pub page_label: Cow<'static, str>,
pub item_suffix: Cow<'static, str>,
pub bare: BareStyle,
pub numbering: Numbering,
pub descriptors: Vec<Descriptor>,
pub paragraph_gap: bool,
pub escape_comment: Escaping,
pub escape_covered: Escaping,
}
impl Default for Style {
fn default() -> Self {
Style {
order: vec![Section::All],
heading_all: Cow::Borrowed("## Comments"),
heading_commented: Cow::Borrowed("## Detailed comments"),
heading_bare: Cow::Borrowed("## Highlights"),
bullet: Cow::Borrowed("- "),
indent: Cow::Borrowed(" "),
quote: Cow::Borrowed("> "),
page_label: Cow::Borrowed("Page #"),
item_suffix: Cow::Borrowed(":"),
bare: BareStyle::Block,
numbering: Numbering::None,
descriptors: vec![],
paragraph_gap: true,
escape_comment: Escaping::Block,
escape_covered: Escaping::Full,
}
}
}
pub fn render(records: &[Record], style: &Style) -> String {
let numbered = assign_numbers(records, style);
let mut out = String::new();
for section in &style.order {
let items: Vec<&(Option<usize>, &Record)> = numbered
.iter()
.filter(|(_, r)| belongs(r, *section))
.collect();
if items.is_empty() {
continue;
}
let heading: &str = match section {
Section::All => &style.heading_all,
Section::Commented => &style.heading_commented,
Section::Bare => &style.heading_bare,
};
if !heading.is_empty() {
out.push_str(heading);
out.push_str("\n\n");
}
for (n, r) in items {
if r.comment.is_none() && style.bare == BareStyle::Quoted {
out.push_str(&render_quoted(r, *n, style));
} else {
out.push_str(&render_block(r, *n, style));
}
}
}
out
}
fn assign_numbers<'a>(records: &'a [Record], style: &Style) -> Vec<(Option<usize>, &'a Record)> {
let mut out = Vec::with_capacity(records.len());
let mut global = 0usize;
let mut per_page: Vec<(usize, usize)> = Vec::new();
for r in records {
let n = match style.numbering {
Numbering::None => None,
Numbering::Global => {
global += 1;
Some(global)
}
Numbering::PerPage => match per_page.iter_mut().find(|(p, _)| *p == r.page) {
Some((_, count)) => {
*count += 1;
Some(*count)
}
None => {
per_page.push((r.page, 1));
Some(1)
}
},
};
out.push((n, r));
}
out
}
fn belongs(r: &Record, section: Section) -> bool {
match section {
Section::All => true,
Section::Commented => r.comment.is_some(),
Section::Bare => r.comment.is_none(),
}
}
fn render_quoted(r: &Record, n: Option<usize>, style: &Style) -> String {
let text = r
.covered_text
.as_deref()
.map(|t| escape(t, style.escape_covered))
.unwrap_or_default();
format!(
"{}{}{}{} \"{text}\"\n\n",
style.bullet,
number_prefix(n),
locator_with(r, style),
style.item_suffix,
)
}
pub(crate) fn render_block(r: &Record, n: Option<usize>, style: &Style) -> String {
let mut out = format!(
"{}{}{}{}\n",
style.bullet,
number_prefix(n),
locator_with(r, style),
style.item_suffix,
);
if let Some(text) = r.covered_text.as_deref() {
let text = escape(text, style.escape_covered);
out.push_str(&format!("{}{}{text}\n\n", quote_indent(style), style.quote));
}
let paras: Vec<String> = r
.comment
.as_deref()
.unwrap_or("")
.split('\n')
.map(str::trim)
.filter(|p| !p.is_empty())
.map(|p| escape(p, style.escape_comment))
.collect();
if style.escape_comment == Escaping::Literal && !paras.is_empty() && r.covered_text.is_none() {
out.push('\n');
}
let literal_indent = if style.escape_comment == Escaping::Literal {
" "
} else {
""
};
for (i, para) in paras.iter().enumerate() {
if i > 0 && style.paragraph_gap {
out.push('\n');
}
out.push_str(&format!("{}{literal_indent}{para}\n", style.indent));
}
out.push('\n');
out
}
fn quote_indent(style: &Style) -> String {
" ".repeat(style.bullet.chars().count())
}
fn number_prefix(n: Option<usize>) -> String {
match n {
Some(n) => format!("[{n}] "),
None => String::new(),
}
}
pub(crate) fn locator(r: &Record, style: &Style) -> String {
match &r.section {
Some(s) => format!("{}{} ({s})", style.page_label, r.page),
None => format!("{}{}", style.page_label, r.page),
}
}
fn locator_with(r: &Record, style: &Style) -> String {
let mut out = locator(r, style);
let parts: Vec<String> = style
.descriptors
.iter()
.filter_map(|d| match d {
Descriptor::Colour => r.color.clone(),
Descriptor::Kind => Some(r.kind.clone()),
Descriptor::Author => r.author.clone(),
Descriptor::Date => r.modified.as_deref().and_then(crate::date::human),
})
.collect();
if !parts.is_empty() {
out.push_str(&format!(" ({})", parts.join(", ")));
}
out
}
fn escape(text: &str, level: Escaping) -> String {
match level {
Escaping::None | Escaping::Literal => text.to_string(),
Escaping::Block => escape_leading(text, LEAD_ALL),
Escaping::Full => escape_leading(&escape_inline(text), LEAD_ONLY_BLOCK),
}
}
const LEAD_ALL: &[char] = &['#', '>', '-', '+', '*', '=', '`', '~', '_'];
const LEAD_ONLY_BLOCK: &[char] = &['#', '-', '+', '='];
fn escape_leading(text: &str, markers: &[char]) -> String {
let mut out = String::with_capacity(text.len() + 2);
for (i, line) in text.split('\n').enumerate() {
if i > 0 {
out.push('\n');
}
let trimmed = line.trim_start();
let lead = &line[..line.len() - trimmed.len()];
let digits: String = trimmed.chars().take_while(|c| c.is_ascii_digit()).collect();
if !digits.is_empty() {
let rest = &trimmed[digits.len()..];
if rest.starts_with('.') || rest.starts_with(')') {
out.push_str(lead);
out.push_str(&digits);
out.push('\\');
out.push_str(rest);
continue;
}
}
if trimmed.starts_with(|c: char| markers.contains(&c)) {
out.push_str(lead);
out.push('\\');
out.push_str(trimmed);
} else {
out.push_str(line);
}
}
out
}
fn escape_inline(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
if matches!(
c,
'\\' | '`' | '*' | '_' | '[' | ']' | '<' | '>' | '&' | '~' | '|'
) {
out.push('\\');
}
out.push(c);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Record;
fn rec(page: usize, kind: &str, covered: Option<&str>, comment: Option<&str>) -> Record {
Record {
page,
kind: kind.to_string(),
covered_text: covered.map(str::to_string),
comment: comment.map(str::to_string),
author: None,
modified: None,
color: None,
section: None,
rect: [0.0; 4],
link: String::new(),
diagnostics: Vec::new(),
}
}
#[test]
fn renders_one_flat_list_by_default() {
let records = vec![
rec(3, "highlight", Some("text"), Some("Comment")),
rec(4, "note", None, Some("note")),
];
assert_eq!(
render(&records, &Style::default()),
"## Comments\n\n- Page #3:\n > text\n\n Comment\n\n- Page #4:\n note\n\n"
);
}
#[test]
fn the_quote_sits_at_the_bullet_width() {
let r = rec(1, "highlight", Some("t"), Some("c"));
assert!(render_block(&r, None, &Style::default()).contains("\n > t"));
assert!(
render_block(
&r,
None,
&Style {
bullet: " * ".into(),
..Style::default()
}
)
.contains("\n > t")
);
assert!(
render_block(
&r,
None,
&Style {
bullet: "".into(),
..Style::default()
}
)
.contains("\n> t")
);
}
#[test]
fn bare_items_render_as_blocks_by_default() {
assert_eq!(
render(
&[rec(2, "highlight", Some("universe"), None)],
&Style::default()
),
"## Comments\n\n- Page #2:\n > universe\n\n\n"
);
}
#[test]
fn quoted_bare_style_is_available() {
assert_eq!(
render(
&[rec(2, "highlight", Some("universe"), None)],
&Style {
bare: BareStyle::Quoted,
..Style::default()
}
),
"## Comments\n\n- Page #2: \"universe\"\n\n"
);
}
#[test]
fn an_empty_heading_emits_none() {
assert_eq!(
render(
&[rec(1, "note", None, Some("x"))],
&Style {
heading_all: "".into(),
..Style::default()
}
),
"- Page #1:\n x\n\n"
);
}
#[test]
fn sections_remain_available_and_ordered() {
let records = vec![
rec(1, "highlight", Some("b"), None),
rec(2, "note", None, Some("c")),
];
assert_eq!(
render(
&records,
&Style {
order: vec![Section::Commented, Section::Bare],
..Style::default()
}
),
"## Detailed comments\n\n- Page #2:\n c\n\n## Highlights\n\n- Page #1:\n > b\n\n\n"
);
}
#[test]
fn empty_sections_are_omitted() {
let out = render(
&[rec(1, "highlight", Some("x"), Some("y"))],
&Style {
order: vec![Section::Commented, Section::Bare],
..Style::default()
},
);
assert!(out.starts_with("## Detailed comments"));
assert!(!out.contains("## Highlights"));
}
#[test]
fn descriptors_appear_in_the_order_given() {
let mut r = rec(3, "highlight", Some("t"), Some("c"));
r.color = Some("#ffff00".to_string());
r.author = Some("Renée".to_string());
r.modified = Some("D:20260902091617+01'00'".to_string());
assert_eq!(
render(
&[r],
&Style {
descriptors: vec![
Descriptor::Colour,
Descriptor::Kind,
Descriptor::Author,
Descriptor::Date,
],
..Style::default()
}
),
"## Comments\n\n- Page #3 (#ffff00, highlight, Renée, 2026-09-02 09:16):\n > t\n\n c\n\n"
);
}
#[test]
fn descriptors_omit_what_the_record_lacks() {
let out = render(
&[rec(3, "note", None, Some("c"))],
&Style {
descriptors: vec![Descriptor::Colour, Descriptor::Kind, Descriptor::Date],
..Style::default()
},
);
assert!(out.contains("- Page #3 (note):"));
}
#[test]
fn no_descriptors_means_no_parentheses() {
let mut r = rec(3, "highlight", Some("t"), Some("c"));
r.color = Some("#ffff00".to_string());
assert!(render(&[r], &Style::default()).contains("- Page #3:"));
}
#[test]
fn reproduces_the_target_layout() {
let mut r = rec(3, "highlight", Some("text"), Some("Comment"));
r.color = Some("#ffff00".to_string());
assert_eq!(
render(
&[r],
&Style {
indent: "".into(),
page_label: "Page ".into(),
item_suffix: "".into(),
descriptors: vec![Descriptor::Colour, Descriptor::Kind],
..Style::default()
}
),
"## Comments\n\n- Page 3 (#ffff00, highlight)\n > text\n\nComment\n\n"
);
}
#[test]
fn numbers_globally_in_reading_order() {
let records = vec![
rec(1, "highlight", Some("a"), Some("c")),
rec(2, "highlight", Some("b"), Some("c")),
];
let out = render(
&records,
&Style {
numbering: Numbering::Global,
..Style::default()
},
);
assert!(out.contains("- [1] Page #1:"));
assert!(out.contains("- [2] Page #2:"));
}
#[test]
fn per_page_numbering_restarts_on_each_page() {
let records = vec![
rec(1, "highlight", Some("a"), Some("c")),
rec(1, "note", None, Some("c")),
rec(2, "highlight", Some("b"), Some("c")),
];
let out = render(
&records,
&Style {
numbering: Numbering::PerPage,
..Style::default()
},
);
assert!(out.contains("- [1] Page #1:"));
assert!(out.contains("- [2] Page #1:"));
assert!(out.contains("- [1] Page #2:"));
}
#[test]
fn numbers_are_assigned_before_sectioning() {
let records = vec![
rec(1, "highlight", Some("a"), Some("c")),
rec(2, "highlight", Some("bare"), None),
];
let out = render(
&records,
&Style {
order: vec![Section::Bare, Section::Commented],
numbering: Numbering::Global,
..Style::default()
},
);
assert!(out.find("- [2] Page #2:").unwrap() < out.find("- [1] Page #1:").unwrap());
}
#[test]
fn block_escaping_neutralises_line_leading_markers() {
let r = rec(1, "note", None, Some("# h\n- i\n1. i\n> q\n*em* kept"));
assert_eq!(
render_block(&r, None, &Style::default()),
"- Page #1:\n \\# h\n\n \\- i\n\n 1\\. i\n\n \\> q\n\n \\*em* kept\n\n"
);
}
#[test]
fn full_escaping_covers_inline_markers_too() {
let r = rec(1, "highlight", Some("*star* [1](r) & <b>"), None);
assert_eq!(
render_block(&r, None, &Style::default()),
"- Page #1:\n > \\*star\\* \\[1\\](r) \\& \\<b\\>\n\n\n"
);
}
#[test]
fn full_escaping_does_not_double_escape() {
let out = render_block(
&rec(1, "highlight", Some("*star*"), None),
None,
&Style::default(),
);
assert!(out.contains("> \\*star\\*"), "got {out:?}");
assert!(!out.contains("\\\\"), "double escape in {out:?}");
}
#[test]
fn escaping_none_passes_text_through() {
assert_eq!(
render_block(
&rec(1, "note", None, Some("# heading")),
None,
&Style {
escape_comment: Escaping::None,
..Style::default()
}
),
"- Page #1:\n # heading\n\n"
);
}
#[test]
fn literal_escaping_forces_a_blank_line_first() {
assert_eq!(
render_block(
&rec(1, "note", None, Some("# not a heading")),
None,
&Style {
escape_comment: Escaping::Literal,
..Style::default()
}
),
"- Page #1:\n\n # not a heading\n\n"
);
}
#[test]
fn formats_a_single_line_comment() {
let r = rec(3, "highlight", Some("universe"), Some("strange choice"));
assert_eq!(
render_block(&r, None, &Style::default()),
"- Page #3:\n > universe\n\n strange choice\n\n"
);
}
#[test]
fn formats_a_multi_line_comment_the_same_way() {
let r = rec(
16,
"highlight",
Some("Z_s,"),
Some("Not clear what this is.\nAlso, you changed from t to s?"),
);
assert_eq!(
render_block(&r, None, &Style::default()),
"- Page #16:\n > Z\\_s,\n\n Not clear what this is.\n\n Also, you changed from t to s?\n\n"
);
}
#[test]
fn formats_a_comment_with_no_covered_text() {
let r = rec(5, "note", None, Some("Define portfolios first"));
assert_eq!(
render_block(&r, None, &Style::default()),
"- Page #5:\n Define portfolios first\n\n"
);
}
#[test]
fn drops_blank_paragraphs_from_a_comment() {
let r = rec(19, "highlight", Some("forecasts"), Some("one?\n\n\ntwo?"));
assert_eq!(
render_block(&r, None, &Style::default()),
"- Page #19:\n > forecasts\n\n one?\n\n two?\n\n"
);
}
#[test]
fn paragraph_gap_can_be_turned_off() {
assert_eq!(
render_block(
&rec(1, "note", None, Some("one\ntwo")),
None,
&Style {
paragraph_gap: false,
..Style::default()
}
),
"- Page #1:\n one\n two\n\n"
);
}
#[test]
fn locator_includes_the_section_when_known() {
let mut r = rec(19, "highlight", None, Some("x"));
r.section = Some("4.2 Protocol".to_string());
assert_eq!(locator(&r, &Style::default()), "Page #19 (4.2 Protocol)");
}
#[test]
fn locator_falls_back_to_the_page_alone() {
let r = rec(19, "highlight", None, Some("x"));
assert_eq!(locator(&r, &Style::default()), "Page #19");
}
}