//! What a note is CALLED and what it SAYS on a list, and what it is FILED//! under — all derived from its one Markdown text, never stored by hand.//!//! **Title.** The first line with words, when it is a heading (any level),//! is the title: its words with the marks taken off. A note whose first line//! is anything else — a paragraph, a list, a link, a quote, a code block —//! has no title, and its list row draws no bold line.//!//! **Preview.** The lines after the title (all of them when there is none),//! skipping blank lines, dividers and fence lines, each as its plain words://! no `#`, `>`, list marker or checkbox, a link as its label, an image as its//! alt, a bare address as itself, a hashtag as its name (no `#`). Up to two lines under//! a title, three without; each line at most [`PREVIEW_LINE`] characters (the//! phone wraps and clamps to `preview_lines`).//!//! **Tags.** Every hashtag outside code, in the order first written, one per//! name compared without case (the first spelling is kept). `#a/b` is the tag//! `a/b`, nested under `a`.//!//! **An old note** keeps its title in the `title` column and its words in//! `body`. It opens as one text with no migration: the stored title as the//! first heading (or its first line made one, when the body already starts//! with those words), then the body, untouched.usesuper::style::{self, Kind, Line};usesuper::inline::Piece;usesuper::style::Style;/// The longest preview line handed to a list row, in characters.pubconst PREVIEW_LINE: usize = 240;#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]pubstructDerived { #[serde(default, skip_serializing_if = "Option::is_none")]pub title: Option<String>,/// Plain lines joined by `\n`; empty for a note with nothing under its title.pub preview: String,/// How many lines the row draws the preview in: 2 under a title, else 3.pub preview_lines: u8,pub tags: Vec<String>,pub words: u64,/// The first picture's address, for a row that draws one. #[serde(default, skip_serializing_if = "Option::is_none")]pub picture: Option<String>,/// Checkboxes, and how many are ticked. #[serde(default)]pub checks: u32, #[serde(default)]pub checks_done: u32,/// Lines with words (the title one of them): Info's paragraphs. #[serde(default)]pub paragraphs: u32,}/// A line's words, the marks taken off.fn plain(text: &str, line: &Line) -> String { words_of(text, line, false)}/// A line's words as a list row says them: the marks off, and a tag as its/// name (`#home/garden` → `home/garden`, `#two words#` → `two words`).fn said(text: &str, line: &Line) -> String { words_of(text, line, true)}fn words_of(text: &str, line: &Line, bare_tags: bool) -> String {if matches!(line.kind, Kind::Blank | Kind::Divider | Kind::Fence | Kind::TableRule) {returnString::new(); }if line.kind == Kind::Table {let cells: Vec<String> = super::table::cells(text, line.start, line.end) .into_iter() .map(|cell| {let one = Line { content: cell.start, end: cell.end, kind: Kind::Paragraph, ..line.clone() }; words_of(text, &one, bare_tags) }) .filter(|words| !words.is_empty()) .collect();return cells.join(" · "); }if line.kind == Kind::Code {return text[line.start..line.end].trim().to_string(); }let (pieces, _) = style::inline_of(text, line);letmut cut: Vec<(usize, usize)> = pieces .iter() .flat_map(|piece| match piece {Piece::Mark { start, end, .. } => vec![(*start, *end)],Piece::Run { start, end, style: Style::Tag, .. } if bare_tags => {letmut hashes = vec![(*start, *start + 1)];if *end > *start + 1 && text.as_bytes()[*end - 1] == b'#' { hashes.push((*end - 1, *end)); } hashes }Piece::Run { .. } => vec![], }) .collect(); cut.sort();letmut out = String::new();letmut at = line.content;for (start, end) in cut {if start > at { out.push_str(&text[at..start]); } at = at.max(end); }if at < line.end { out.push_str(&text[at..line.end]); }// Escapes read as the mark they escape.letmut unescaped = String::with_capacity(out.len());letmut chars = out.chars().peekable();whileletSome(c) = chars.next() {if c == '\\' && chars.peek().is_some_and(char::is_ascii_punctuation) {continue; } unescaped.push(c); }let words = unescaped.trim();// A heading's closing hashes (`# Title #`) are marks too.if line.kind == Kind::Heading {let closed = words.trim_end_matches('#');if closed.len() < words.len() && (closed.is_empty() || closed.ends_with(' ')) {return closed.trim_end().to_string(); } } words.to_string()}/// A line's plain words (the marks off), for the writing rule's other parts.pub(crate) fn plain_words(text: &str, line: &Line) -> String { plain(text, line)}fn cap(line: String) -> String {match line.char_indices().nth(PREVIEW_LINE) {Some((at, _)) => line[..at].trim_end().to_string(),None => line, }}/// The note's title: its first line with words, when that is a heading.pubfn title(text: &str) -> Option<String> {let lines = style::lines(text); lines.iter().find(|line| line.title).map(|line| plain(text, line)).filter(|words| !words.is_empty())}/// Title, preview, tags and word count in one reading.pubfn derive(text: &str) -> Derived {let lines = style::lines(text);let titled = lines.iter().position(|line| line.title);let title = titled.map(|at| plain(text, &lines[at])).filter(|words| !words.is_empty());let preview_lines: u8 = if title.is_some() { 2 } else { 3 };letmut preview: Vec<String> = Vec::new();letmut words = 0u64;letmut picture = None;let (mut checks, mut checks_done, mut paragraphs) = (0u32, 0u32, 0u32);for (index, line) in lines.iter().enumerate() {ifletSome(ticked) = line.checked { checks += 1; checks_done += u32::from(ticked); }if line.kind == Kind::Picture {if picture.is_none() { picture = super::inline::link_at(text, line.indent_end + 1, line.end).map(|(_, _, url)| url); }continue; }let said = plain(text, line);let row = self::said(text, line); words += said.split_whitespace().count() as u64;if !said.is_empty() && line.kind != Kind::Code || line.kind == Kind::Fence && line.content == line.end && line.block.is_some_and(|(start, _)| start == line.start) { paragraphs += 1; }ifSome(index) == titled && title.is_some() {continue; }if preview.len() < preview_lines as usize && !row.is_empty() { preview.push(cap(row)); } }Derived { title, preview: preview.join("\n"), preview_lines, tags: tags_in(text, &lines), words, picture, checks, checks_done, paragraphs }}/// Every hashtag in `text`, outside code, first spelling kept.pubfn tags(text: &str) -> Vec<String> { tags_in(text, &style::lines(text))}fn tags_in(text: &str, lines: &[Line]) -> Vec<String> {letmut seen = std::collections::BTreeSet::new();letmut out = Vec::new();for line in lines {let (pieces, found) = style::inline_of(text, line);for tag in found {// A tag inside inline code is no tag: code's runs hold it.let in_code = pieces.iter().any(|piece| matches!(piece, Piece::Run { start, end, style: style::Style::Code, .. } if *start <= tag.start && tag.end <= *end));if !in_code && seen.insert(tag_key(&tag.name)) { out.push(tag.name); } } } out}/// `text` with the tag `name` taken off wherever it is written (outside code),/// each spelling compared by [`tag_key`]; a tag under it (`#name/more`) stays./// The space before a removed tag goes with it, and a line left with no words/// goes too, so a tag line at a note's foot leaves nothing behind.pubfn untag(text: &str, name: &str) -> String {let key = tag_key(name.trim().trim_start_matches('#').trim_end_matches('#').trim());let lines = style::lines(text);letmut cuts: Vec<(usize, usize)> = Vec::new();for line in &lines {let (pieces, found) = style::inline_of(text, line);for tag in found {let in_code = pieces.iter().any(|piece| matches!(piece, Piece::Run { start, end, style: style::Style::Code, .. } if *start <= tag.start && tag.end <= *end));if in_code || tag_key(&tag.name) != key {continue; }letmut start = tag.start;while start > line.start && text.as_bytes()[start - 1] == b' ' { start -= 1; }// At the line's start the space after goes instead.letmut end = tag.end;if start == line.start {while end < line.end && text.as_bytes()[end] == b' ' { end += 1; } } cuts.push((start, end)); } }if cuts.is_empty() {return text.to_string(); }letmut out = String::with_capacity(text.len());letmut at = 0;for (start, end) in cuts { out.push_str(&text[at..start]); at = end; } out.push_str(&text[at..]);// Lines that held only the tag go, with their line break; a note's foot loses its trailing blank lines.let was_blank: Vec<bool> = text.split('\n').map(|l| l.trim().is_empty()).collect();let kept: Vec<&str> = out.split('\n').enumerate().filter(|(i, l)| !l.trim().is_empty() || was_blank.get(*i).copied().unwrap_or(true)).map(|(_, l)| l).collect();let joined = kept.join("\n");let trimmed = joined.trim_end_matches('\n');if text.ends_with('\n') && !trimmed.is_empty() { format!("{trimmed}\n") } else { trimmed.to_string() }}/// The key a tag is compared by: lowercased, so `#Work` and `#work` are one.pubfn tag_key(name: &str) -> String { name.to_lowercase()}/// The tag a nested tag folds under (`a/b/c` → `a/b`); none at the top.pubfn tag_parent(name: &str) -> Option<&str> { name.rsplit_once('/').map(|(parent, _)| parent)}/// The text an old note opens as: its stored title as the first heading,/// then its body as written. A note already written as one text (no stored/// title, or a body whose title is that title) opens as its body.pubfn opened_text(stored_title: Option<&str>, body: &str) -> String {let named = stored_title.map(str::trim).unwrap_or_default();if named.is_empty() || title(body).as_deref() == Some(named) {return body.to_string(); }let lines = style::lines(body);ifletSome(first) = lines.iter().find(|line| line.kind != Kind::Blank) {if first.kind == Kind::Paragraph && plain(body, first) == named {return format!("{}# {}", &body[..first.start], &body[first.start..]); } }if body.trim().is_empty() { format!("# {named}\n") } else { format!("# {named}\n\n{body}") }}/// The title column kept in step with the text, for every other surface/// that reads a note (search, an assistant, the old deck): the derived title,/// or empty.pubfn stored_title(text: &str) -> String { title(text).unwrap_or_default()}/// Every picture address the text points at (``), in order.pubfn pictures(text: &str) -> Vec<String> {let lines = style::lines(text);letmut out = Vec::new();for line in &lines {for piece in style::inline_of(text, line).0 {ifletPiece::Run { style: style::Style::Image, url: Some(url), .. } = piece { out.push(url); } }if line.kind == Kind::Picture {ifletSome((_, _, url)) = super::inline::link_at(text, line.indent_end + 1, line.end) {if !out.contains(&url) { out.push(url); } } } } out}/// An old note's attached pictures, drawn inline after its text in their/// old order: each one the text does not already show goes on its own line/// at the end. Run twice, it adds nothing (a picture already in the text is/// never added again), so the first edit writing this into the body neither/// loses nor doubles one.pubfn with_pictures(text: &str, attached: &[String]) -> String {let shown = pictures(text);letmut out = text.to_string();for src in attached {if shown.contains(src) || out.contains(&format!("]({src})")) {continue; }if !out.is_empty() { out.truncate(out.trim_end_matches('\n').len()); out.push_str("\n\n"); } out.push_str(&format!("\n")); } out}