//! 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};
use super::inline::Piece;
use super::style::{self, Kind, Style};
use super::Offsets;
/// One `[[…]]` in a text, in UTF-16 (the whole element, brackets included).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Link {
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).
pub fn links(text: &str) -> Vec {
let offsets = Offsets::new(text);
let mut out = Vec::new();
for line in style::lines(text) {
let (pieces, _) = style::inline_of(text, &line);
for piece in pieces {
if let Piece::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.
pub fn title_key(title: &str) -> String {
title.split_whitespace().collect::>().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).
pub fn split<'a>(target: &'a str, is_title: impl Fn(&str) -> bool) -> (&'a str, Option<&'a str>) {
if is_title(target) {
return (target, None);
}
if let Some((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.
pub fn renamed(text: &str, old: &str, new: &str, is_title: impl Fn(&str) -> bool) -> Option {
let old_key = title_key(old);
if old_key.is_empty() || new.trim().is_empty() || old_key == title_key(new) && old.trim() == new.trim() {
return None;
}
let mut out = String::with_capacity(text.len());
let mut at = 0usize;
let mut changed = false;
for line in style::lines(text) {
let (pieces, _) = style::inline_of(text, &line);
for piece in pieces {
let Piece::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,
}
};
if let Some(with) = replaced {
out.push_str(&text[at..start]);
out.push_str(&with);
at = end;
changed = true;
}
}
}
if !changed {
return None;
}
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.
pub fn 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) {
return None;
}
let before = &text[line.start..at];
let open = before.rfind("[[")?;
let typed = &before[open + 2..];
if typed.contains(']') || typed.contains('[') {
return None;
}
// 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 {
return None;
}
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()))
}