//! NOTE LINKS — `[[Title]]` and `[[Title/Heading]]` in a note's text: where//! each stands, what it names, the link being typed, and the rewrite that//! keeps links right when a note's title changes. Pure: which note a title//! opens is the core's to say ([`split`] asks it through `is_title`).//!//! The text keeps the title as written (the reference app's own form, so an//! export reads anywhere); a link is matched to a title without case.use serde::{Deserialize, Serialize};usesuper::inline::Piece;usesuper::style::{self, Kind, Style};usesuper::Offsets;/// One `[[…]]` in a text, in UTF-16 (the whole element, brackets included).#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructLink {pub start: u32,pub end: u32,/// What is written between the brackets, trimmed.pub target: String,}/// Every note link in `text`, in order (none inside code).pubfn links(text: &str) -> Vec<Link> {let offsets = Offsets::new(text);letmut out = Vec::new();for line in style::lines(text) {let (pieces, _) = style::inline_of(text, &line);for piece in pieces {ifletPiece::Run { start, end, style: Style::NoteLink, url: Some(target) } = piece { out.push(Link { start: offsets.u16(start - 2), end: offsets.u16(end + 2), target }); } } } out}/// The key a title is matched by: lowercased, spaces collapsed.pubfn title_key(title: &str) -> String { title.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase()}/// A target read as (title, heading): the whole target when it is a title;/// else, split at its last `/`, the part before when that is one; else the/// whole target (a link to no note yet).pubfn split<'a>(target: &'a str, is_title: implFn(&str) -> bool) -> (&'a str, Option<&'a str>) {if is_title(target) {return (target, None); }ifletSome((title, heading)) = target.rsplit_once('/') {let (title, heading) = (title.trim(), heading.trim());if !title.is_empty() && !heading.is_empty() && is_title(title) {return (title, Some(heading)); } } (target, None)}/// `text` with every link that names `old` (`[[old]]`, `[[old/heading]]`)/// naming `new` instead; none when no link names it. `[[old/x]]` where/// `old/x` is itself a title (`is_title`) is left alone.pubfn renamed(text: &str, old: &str, new: &str, is_title: implFn(&str) -> bool) -> Option<String> {let old_key = title_key(old);if old_key.is_empty() || new.trim().is_empty() || old_key == title_key(new) && old.trim() == new.trim() {returnNone; }letmut out = String::with_capacity(text.len());letmut at = 0usize;letmut changed = false;for line in style::lines(text) {let (pieces, _) = style::inline_of(text, &line);for piece in pieces {letPiece::Run { start, end, style: Style::NoteLink, url: Some(target) } = piece else { continue };let replaced = if title_key(&target) == old_key {Some(new.trim().to_string()) } else {match target.rsplit_once('/') {Some((title, heading)) if title_key(title) == old_key && !is_title(&target) => Some(format!("{}/{}", new.trim(), heading.trim())), _ => None, } };ifletSome(with) = replaced { out.push_str(&text[at..start]); out.push_str(&with); at = end; changed = true; } } }if !changed {returnNone; } out.push_str(&text[at..]);Some(out)}/// The link being typed at `cursor` (UTF-16): an open `[[` before the cursor/// on its line with no `]]` between, outside code. Answers the UTF-16 range/// to replace (from the `[[` to the cursor, and a `]]` straight after the/// cursor) and what is typed so far.pubfn typing(text: &str, cursor: u32) -> Option<(u32, u32, String)> {let at = super::byte_at(text, cursor);let lines = style::lines(text);let line = lines.iter().find(|line| line.start <= at && at <= line.end)?;if matches!(line.kind, Kind::Code | Kind::Fence) {returnNone; }let before = &text[line.start..at];let open = before.rfind("[[")?;let typed = &before[open + 2..];if typed.contains(']') || typed.contains('[') {returnNone; }// Inside inline code it is no link.let in_code = style::inline_of(text, line).0.iter().any(|piece| matches!(piece, Piece::Run { start, end, style: Style::Code, .. } if *start <= line.start + open && line.start + open < *end));if in_code {returnNone; }let offsets = Offsets::new(text);let close = if text[at..line.end].starts_with("]]") { at + 2 } else { at };Some((offsets.u16(line.start + open), offsets.u16(close), typed.trim_start().to_string()))}