prov_graph/link.rs
1//! Link text — the raw strings a relation field holds, the wikilinks embedded
2//! in body prose, and the path arithmetic around them.
3//!
4//! A link target as written in metadata is either a bare path or a
5//! markdown-style labeled link (`[Design](docs/design.md)`), and its path may be
6//! **relative** to the document (`notes/a.md`), **workspace-absolute** from the
7//! root (`/Blog/Blog.md`), or wrapped in Markdown **angle brackets** when it
8//! contains spaces (`</Creative Writing/index.md>`, `[Notes](</My Notes/x.md>)`).
9//! This is prov's *link-syntax layer* — the analogue of `fig`'s format
10//! layer: it recognizes the conventions a real workspace mixes and round-trips
11//! them on write (spaces re-acquire their brackets). A [`Wikilink`] is the
12//! body-text counterpart (`[[notes/a.md]]`, `[[colophon:ajp7eq|My file]]`).
13//! Everything here is *lexical*: no filesystem
14//! access, no symlink resolution, and no markdown-structure awareness (a `[[…]]`
15//! inside a code span is still scanned) — resolution and code-fence discipline
16//! belong to the traversal and validation layers, which can report what they
17//! find.
18
19use std::ops::Range;
20use std::path::{Path, PathBuf};
21
22/// A parsed link string: an optional human label and the target it points at.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct Link {
25 /// The display label, when written as `[label](target)` or `[[target|label]]`.
26 pub label: Option<String>,
27 /// The target exactly as written (a relative path, an `id:<id>` handle, or a
28 /// URL for overlay relations that point off-workspace).
29 pub target: String,
30 /// `true` when the scalar was written as an Obsidian wikilink
31 /// (`[[target]]` / `[[target|label]]`) rather than a markdown link or bare
32 /// target — preserved so [`render`](Link::render) round-trips the wrapper.
33 pub wikilink: bool,
34}
35
36impl Link {
37 /// Parse a raw link string. `[label](target)` yields both parts; anything
38 /// else is a bare target with no label. A target wrapped in Markdown angle
39 /// brackets (`<…>`, used when it contains spaces) is unwrapped *only* when
40 /// it appears as the URL portion of a successfully parsed `[label](<target>)`
41 /// — never when it wraps a bare, unlabeled value, which stays byte-literal
42 /// (diaryx reads a bare `<…>` as a literal path, angle brackets and all: see
43 /// [`parse_path_only`](Link::parse_path_only) and the `link_style` render
44 /// tests). A `[[target]]` / `[[target|label]]` Obsidian wikilink scalar is
45 /// also recognized here; use [`parse_path_only`](Link::parse_path_only) when
46 /// the caller's value is a frontmatter *path* field that must not
47 /// reinterpret a literal `[[…]]` string as a wikilink.
48 pub fn parse(raw: &str) -> Self {
49 Self::parse_impl(raw, true)
50 }
51
52 /// [`parse`](Link::parse), but never treats `"[[target]]"` as an Obsidian
53 /// wikilink — such a value is left exactly as written (a bare literal, or,
54 /// if it happens to also match `[label](target)`, a markdown link). This is
55 /// the opt-out a frontmatter *path* field needs: diaryx's own path-value
56 /// parser has no wikilink convention at all, so a workspace that stores a
57 /// literal `"[[…]]"`-shaped string in a path property (unusual, but legal
58 /// input data) must round-trip it untouched rather than have `parse`
59 /// silently reinterpret it as a link. Every other rule of `parse` —
60 /// `[label](target)` splitting, balanced parens, angle-bracket unwrapping of
61 /// a parsed URL — applies unchanged.
62 pub fn parse_path_only(raw: &str) -> Self {
63 Self::parse_impl(raw, false)
64 }
65
66 /// Shared implementation behind [`parse`](Link::parse) and
67 /// [`parse_path_only`](Link::parse_path_only); `wikilink` gates the
68 /// `[[target]]` recognition branch.
69 fn parse_impl(raw: &str, wikilink: bool) -> Self {
70 let raw = raw.trim();
71 // A wikilink scalar — `[[target]]` / `[[target|label]]` — the Obsidian
72 // wrapper permitted in metadata as well as body prose. Skipped entirely
73 // by `parse_path_only`.
74 if wikilink && let Some(inner) = raw.strip_prefix("[[").and_then(|r| r.strip_suffix("]]")) {
75 let (target, label) = match inner.split_once('|') {
76 Some((target, label)) => (target.trim(), Some(label.trim().to_string())),
77 None => (inner.trim(), None),
78 };
79 return Self {
80 label,
81 target: target.to_string(),
82 wikilink: true,
83 };
84 }
85 if let Some((label, target)) = split_markdown_link(raw) {
86 return Self {
87 label: Some(label),
88 target,
89 wikilink: false,
90 };
91 }
92 // Bare value: stored byte-literal, angle brackets and all. Unlike the
93 // markdown-link branch above, there is no URL position here to unwrap —
94 // a bare `<…>`-shaped string is data, not delimiters (see `parse`'s doc
95 // comment and the C2 regression tests).
96 Self {
97 label: None,
98 target: raw.to_string(),
99 wikilink: false,
100 }
101 }
102
103 /// Render back to a writable link string. A labeled link keeps its label and
104 /// wraps the URL in Markdown angle brackets when it holds a space or paren
105 /// (so `]` / `)` in the path cannot break parsing); a bare target is emitted
106 /// verbatim — brackets belong *inside* `[label](…)`, never around a bare
107 /// value (matching diaryx, which reads a bare `<…>` as a literal path).
108 pub fn render(&self) -> String {
109 match (&self.label, self.wikilink) {
110 (Some(label), true) => format!("[[{}|{label}]]", self.target),
111 (None, true) => format!("[[{}]]", self.target),
112 (Some(label), false) => format!("[{label}]({})", emit_target(&self.target)),
113 (None, false) => self.target.clone(),
114 }
115 }
116
117 /// This link with a different target, keeping the label and wrapper. The
118 /// rename path uses this so `[Design](old.md)` becomes `[Design](new.md)`,
119 /// never a bare `new.md`.
120 pub fn with_target(&self, target: impl Into<String>) -> Self {
121 Self {
122 label: self.label.clone(),
123 target: target.into(),
124 wikilink: self.wikilink,
125 }
126 }
127
128 /// This link with a different display label, keeping the target and wrapper.
129 /// The retitle path uses this so `[Old Title](id:abc)` becomes
130 /// `[New Title](id:abc)` when the target is renamed — the label follows the
131 /// title while the (id or path) target stays exactly as written.
132 pub fn with_label(&self, label: impl Into<String>) -> Self {
133 Self {
134 label: Some(label.into()),
135 target: self.target.clone(),
136 wikilink: self.wikilink,
137 }
138 }
139
140 /// `true` when the target points off-workspace (a URL or mail address)
141 /// rather than at a file — such links are never resolved against the
142 /// filesystem or rewritten by moves.
143 pub fn is_external(&self) -> bool {
144 self.target.contains("://") || self.target.starts_with("mailto:")
145 }
146
147 /// `true` when the target names no document at all, only a place inside the
148 /// one it is written in: a target that is *entirely* a locator (`#3`,
149 /// `#section-one`).
150 ///
151 /// The counterpart of [`locator`](Self::locator)'s leading-`#` rule (see
152 /// [`split_locator`]). Such a reference says nothing about where anything
153 /// lives, so nothing here can be resolved against the filesystem and nothing
154 /// may rewrite it: it is byte-literal, exactly as `docs/reference-styles.md`
155 /// promises. Resolution reports it as
156 /// [`Target::SameDocument`](crate::graph::Target::SameDocument), never as a
157 /// sibling file whose name begins with `#`.
158 pub fn is_same_document(&self) -> bool {
159 !self.is_external() && self.target.starts_with(LOCATOR_SEPARATOR)
160 }
161
162 /// The **sub-document locator** this target carries — the text after a `#`,
163 /// naming a place *inside* a document rather than a document.
164 ///
165 /// A locator is carried, never resolved. prov strips it before resolving the
166 /// target and re-attaches it on rewrite, which is the same contract §4 gives
167 /// an external URL: recognized by syntax, never validated. What it *means*
168 /// is the workspace's business — a verse number in a chapter, a heading
169 /// slug, a line range — so a locator naming nothing is not a `check`
170 /// finding. That is the price of not teaching prov every document format's
171 /// internal address space.
172 ///
173 /// `None` for an external target (a URL's fragment belongs to the URL) and
174 /// for a target that is *only* a locator (`#3`), which stays byte-literal —
175 /// see [`split_locator`].
176 pub fn locator(&self) -> Option<&str> {
177 if self.is_external() {
178 return None;
179 }
180 split_locator(&self.target).1
181 }
182
183 /// This link's target with any [`locator`](Self::locator) removed — the part
184 /// that names a *document*, and so the only part that resolves.
185 pub fn addressed_target(&self) -> &str {
186 if self.is_external() {
187 return &self.target;
188 }
189 split_locator(&self.target).0
190 }
191
192 /// This link with its document part replaced, **preserving the locator**.
193 ///
194 /// The rewrite passes (rename, re-relativize, restyle) use this rather than
195 /// [`with_target`](Self::with_target), which sets the target verbatim: a
196 /// move changes where a document lives, never which part of it was pointed
197 /// at.
198 pub fn with_path(&self, path: impl Into<String>) -> Self {
199 self.with_target(join_locator(path, self.locator()))
200 }
201
202 /// What this link's `id:`-scheme target names — local, foreign, or
203 /// malformed. `None` when the target carries no id scheme at all (a path,
204 /// an alias, a URL).
205 ///
206 /// Any [`locator`](Self::locator) is stripped first, so `id:abc1234#2-3`
207 /// names the same document as `id:abc1234`.
208 pub fn id_ref(&self) -> Option<IdRef> {
209 strip_id_scheme(self.addressed_target()).map(parse_id_body)
210 }
211
212 /// The stable ID this link names, when the target uses the `id:<id>`
213 /// scheme (or the legacy `colophon:<id>` spelling) — the
214 /// location-independent alternative to a relative path. Such targets
215 /// resolve through the workspace's ID registry, never against the
216 /// filesystem, and are deliberately *not* rewritten by moves: staying valid
217 /// across moves is their entire point.
218 ///
219 /// **Local ids only.** A cross-workspace `id:<workspace>/<id>` yields
220 /// `None`, because the registry this would be resolved against is not the
221 /// one that issued the id — see [`id_ref`](Self::id_ref). Callers asking
222 /// "must a move leave this alone?" want [`is_path_target`](Self::is_path_target),
223 /// which covers every id form.
224 pub fn id_target(&self) -> Option<crate::identity::Id> {
225 match self.id_ref() {
226 Some(IdRef::Local(id)) => Some(id),
227 _ => None,
228 }
229 }
230
231 /// The workspace and id this link names, when it is a cross-workspace
232 /// reference (`id:<workspace>/<id>`).
233 pub fn foreign_target(&self) -> Option<(String, crate::identity::Id)> {
234 match self.id_ref() {
235 Some(IdRef::Foreign { workspace, id }) => Some((workspace, id)),
236 _ => None,
237 }
238 }
239
240 /// Whether this link's target is a **path** — the only kind that says where
241 /// its target lives, and so the only kind a move may rewrite.
242 ///
243 /// False for an external URL, for every `id:` reference alike (local,
244 /// foreign, and malformed), and for a
245 /// [same-document](Self::is_same_document) reference: none of them encodes a
246 /// location, so re-relativizing one could only damage it. This is the
247 /// predicate the rename, re-relativize and restyle passes filter on.
248 pub fn is_path_target(&self) -> bool {
249 !self.is_external() && !self.is_same_document() && self.id_ref().is_none()
250 }
251}
252
253/// Try to split `raw` as a Markdown link `[label](target)` (or, when the URL
254/// holds a space or paren, `[label](<target>)`). Returns the label and the
255/// unwrapped target, or `None` when `raw` doesn't have this shape.
256///
257/// Ports diaryx_core's `link_parser::try_parse_markdown_link` byte-for-byte
258/// (see module doc comment) rather than re-deriving it, because its two
259/// corrected behaviors are exactly what C2/C3 need and diaryx's test suite is
260/// the ground truth for their edge cases:
261/// - The label is whatever sits between the first `[` and the first `]`
262/// immediately followed by `(` — *not* whatever precedes the last `)` in the
263/// whole string, so trailing prose after the link (`"[Title](/a.md) note"`)
264/// never gets swept into the target.
265/// - The target's closing paren is found by depth-counting (see
266/// [`find_closing_paren`]), so a target containing its own parens
267/// (`/file (1).md`, even nested) still closes at the right `)`; any text
268/// after that `)` is deliberately never inspected — tolerated, not merely
269/// permitted.
270/// - Angle brackets are only unwrapped here, on the URL of a link that already
271/// parsed as `[label](…)` — never on a bare value (that's C2; see
272/// [`Link::parse`]'s doc comment and `parse_impl`'s bare-value branch).
273fn split_markdown_link(raw: &str) -> Option<(String, String)> {
274 if !raw.starts_with('[') {
275 return None;
276 }
277 let close_bracket = raw.find(']')?;
278 if !raw[close_bracket..].starts_with("](") {
279 return None;
280 }
281 let label = raw[1..close_bracket].to_string();
282 let after = &raw[close_bracket + 2..];
283 let target = if let Some(inner) = after.strip_prefix('<') {
284 // `](<target>)`: the closing `>` must be immediately followed by `)` —
285 // otherwise this isn't really an angle-bracketed URL and the whole
286 // markdown-link parse fails (falls through to the bare branch).
287 let close_angle = inner.find('>')?;
288 if inner.get(close_angle + 1..close_angle + 2) != Some(")") {
289 return None;
290 }
291 inner[..close_angle].to_string()
292 } else {
293 let close_paren = find_closing_paren(after)?;
294 after[..close_paren].to_string()
295 };
296 Some((label, target))
297}
298
299/// Find the byte offset of the `)` that balances the *implicit* open paren at
300/// the start of a Markdown link URL — i.e. the first `)` encountered at
301/// nesting depth zero, treating every `(` as opening one more level. A target
302/// with no closing paren at all (an unterminated link) yields `None`.
303///
304/// This is the crux of the C3 fix: the old code demanded the link be the very
305/// end of the input (`raw.strip_suffix(')')` on the whole trimmed string), so
306/// `"[Title](/a.md) trailing junk"` fell through to a bare target holding the
307/// entire string. Scanning for the *matching* close paren instead — and never
308/// examining what follows it — makes the split correct both for a target
309/// containing its own balanced parens (`/file (1).md`, `/file (a (b)).md`) and
310/// for trailing prose after the link.
311fn find_closing_paren(s: &str) -> Option<usize> {
312 let mut depth = 0u32;
313 for (i, c) in s.char_indices() {
314 match c {
315 '(' => depth += 1,
316 ')' => {
317 if depth == 0 {
318 return Some(i);
319 }
320 depth -= 1;
321 }
322 _ => {}
323 }
324 }
325 None
326}
327
328/// The writable spelling of a Markdown-link URL: wrapped in angle brackets when
329/// it holds a space or parenthesis (which would otherwise break `[label](url)`),
330/// bare otherwise. For URLs *inside* `[label](…)` only.
331fn emit_target(target: &str) -> String {
332 if target.contains([' ', '(', ')']) {
333 format!("<{target}>")
334 } else {
335 target.to_string()
336 }
337}
338
339/// The write style for links a workspace authors — prov's analogue of
340/// diaryx's `LinkFormat`, and read from the same place: the `link_format` key in
341/// the root document's frontmatter (a fact declared *in* the workspace, not an
342/// app-private config). Every link prov writes (autofix today; create/rename
343/// in time) uses this, so a repair never introduces a foreign style.
344#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
345pub enum LinkStyle {
346 /// `[Title](/path/file.md)` — workspace-absolute Markdown link. diaryx's
347 /// default, and the most portable/self-documenting.
348 #[default]
349 MarkdownRoot,
350 /// `[Title](../path/file.md)` — relative Markdown link.
351 MarkdownRelative,
352 /// `/path/file.md` — bare workspace-absolute path.
353 PlainRoot,
354 /// `../path/file.md` — bare relative path.
355 PlainRelative,
356}
357
358impl LinkStyle {
359 /// This style's notation (bracketed Markdown vs bare path) and path
360 /// resolution — the two orthogonal axes the config `references.notation` /
361 /// `references.path_style` keys expose (see [`Notation`] / [`PathStyle`]).
362 /// `LinkStyle` is the fused internal carrier; these split it back out.
363 pub fn axes(self) -> (Notation, PathStyle) {
364 match self {
365 Self::MarkdownRoot => (Notation::Markdown, PathStyle::Root),
366 Self::MarkdownRelative => (Notation::Markdown, PathStyle::Relative),
367 Self::PlainRoot => (Notation::Bare, PathStyle::Root),
368 Self::PlainRelative => (Notation::Bare, PathStyle::Relative),
369 }
370 }
371
372 /// The fused [`LinkStyle`] for a bracketed-vs-bare notation and a path
373 /// resolution. `Wikilink` has no bare/bracketed distinction, so it maps
374 /// through the Markdown family (only the path-text shape matters for it).
375 pub fn from_axes(notation: Notation, path_style: PathStyle) -> Self {
376 match (notation, path_style) {
377 (Notation::Markdown | Notation::Wikilink, PathStyle::Root) => Self::MarkdownRoot,
378 (Notation::Markdown | Notation::Wikilink, PathStyle::Relative) => {
379 Self::MarkdownRelative
380 }
381 (Notation::Bare, PathStyle::Root) => Self::PlainRoot,
382 (Notation::Bare, PathStyle::Relative) => Self::PlainRelative,
383 }
384 }
385}
386
387/// The syntactic form a reference is written in — the config-facing notation
388/// axis (`references.notation`), orthogonal to [`PathStyle`]. This is the clean
389/// split of what the internal [`Wrapper`] + `plain_`/`markdown_` [`LinkStyle`]
390/// prefix fused: `Bare` is a path with no brackets, `Markdown` is `[Title](…)`,
391/// `Wikilink` is `[[…]]`.
392#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
393pub enum Notation {
394 /// `[Title](target)`.
395 #[default]
396 Markdown,
397 /// `[[target]]` / `[[target|Title]]`.
398 Wikilink,
399 /// A bare `target`, no brackets — what the old `plain_*` link formats wrote.
400 Bare,
401}
402
403impl Notation {
404 /// Parse the `references.notation` config spelling; unknown → `None`.
405 pub fn from_config_str(value: &str) -> Option<Self> {
406 match value {
407 "markdown" => Some(Self::Markdown),
408 "wikilink" => Some(Self::Wikilink),
409 "bare" => Some(Self::Bare),
410 _ => None,
411 }
412 }
413
414 /// The `references.notation` config spelling.
415 pub fn as_config_str(self) -> &'static str {
416 match self {
417 Self::Markdown => "markdown",
418 Self::Wikilink => "wikilink",
419 Self::Bare => "bare",
420 }
421 }
422
423 /// The internal [`Wrapper`] this notation renders through. `Markdown` and
424 /// `Bare` share the Markdown wrapper (the bracket-vs-bare choice lives in the
425 /// path style); `Wikilink` is its own wrapper.
426 pub fn wrapper(self) -> Wrapper {
427 match self {
428 Self::Wikilink => Wrapper::Wikilink,
429 Self::Markdown | Self::Bare => Wrapper::Markdown,
430 }
431 }
432
433 /// Recover the notation from a fused [`Wrapper`] + [`LinkStyle`] — the inverse
434 /// direction, for serializing an internal style back to config.
435 pub fn from_wrapper(wrapper: Wrapper, style: LinkStyle) -> Self {
436 match wrapper {
437 Wrapper::Wikilink => Self::Wikilink,
438 Wrapper::Markdown => style.axes().0,
439 }
440 }
441}
442
443/// The path-resolution a reference uses for a path target — the config-facing
444/// `references.path_style` axis, orthogonal to [`Notation`]. Applies to path
445/// targets only (id/alias ignore it).
446///
447/// Two resolutions, and deliberately not three. A `canonical` style once emitted
448/// a *workspace*-relative path with no leading slash (`path/file.md`), which
449/// [`resolve`] reads as *directory*-relative — so a canonical link resolved to
450/// what it named only from a document at the workspace root, and silently
451/// misresolved everywhere else. The ambiguity of a bare path is settled by
452/// committing to one meaning rather than by tagging it: **bare is
453/// directory-relative**, and a workspace-relative reference is spelled
454/// [`Root`](Self::Root), with the slash that says so. `prov convert <root>
455/// link_format markdown_root -r` restyles a workspace that used the old value.
456#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
457pub enum PathStyle {
458 /// Workspace-absolute: `/path/file.md`.
459 #[default]
460 Root,
461 /// Relative to the referring document: `../file.md`.
462 Relative,
463}
464
465impl PathStyle {
466 /// Parse the `references.path_style` config spelling; unknown → `None`.
467 pub fn from_config_str(value: &str) -> Option<Self> {
468 match value {
469 "root" => Some(Self::Root),
470 "relative" => Some(Self::Relative),
471 _ => None,
472 }
473 }
474
475 /// The `references.path_style` config spelling.
476 pub fn as_config_str(self) -> &'static str {
477 match self {
478 Self::Root => "root",
479 Self::Relative => "relative",
480 }
481 }
482}
483
484/// Format a link to `target` (a workspace-relative canonical path) as written in
485/// the document at `from`, in `style`, with `title` (used only by the Markdown
486/// styles). This is what keeps an authored link native to the workspace.
487pub fn format_link(style: LinkStyle, from: &Path, target: &Path, title: &str) -> String {
488 let canonical = target.to_string_lossy();
489 match style {
490 LinkStyle::MarkdownRoot => {
491 format!("[{title}]({})", emit_target(&format!("/{canonical}")))
492 }
493 LinkStyle::MarkdownRelative => {
494 let rel = relative(from.parent().unwrap_or(Path::new("")), target);
495 format!("[{title}]({})", emit_target(&rel))
496 }
497 LinkStyle::PlainRoot => format!("/{canonical}"),
498 LinkStyle::PlainRelative => relative(from.parent().unwrap_or(Path::new("")), target),
499 }
500}
501
502/// A human title generated from a path's file stem: `_`/`-` become spaces and
503/// each word is capitalized (`utility_index.md` → `Utility Index`). The fallback
504/// when a target document declares no `title`.
505pub fn path_to_title(path: &Path) -> String {
506 let stem = path
507 .file_stem()
508 .and_then(|s| s.to_str())
509 .unwrap_or_default();
510 stem.split(['_', '-', ' '])
511 .filter(|w| !w.is_empty())
512 .map(|word| {
513 let mut chars = word.chars();
514 match chars.next() {
515 Some(first) => first.to_ascii_uppercase().to_string() + chars.as_str(),
516 None => String::new(),
517 }
518 })
519 .collect::<Vec<_>>()
520 .join(" ")
521}
522
523/// Turn a human title into a filesystem-friendly filename stem — the readable
524/// slug prov derives when a document is created by title (`prov new "My
525/// Great Note"` → `my-great-note`). The rough inverse of
526/// [`path_to_title`]: lowercase, runs of whitespace and separators
527/// (space / `-` / `_` / `/`) collapsed to a single `-`, and any other
528/// punctuation dropped. Unicode letters and digits are kept, so a non-ASCII
529/// title still yields a legible name. A title with no slug-able characters (pure
530/// punctuation) falls back to `"untitled"` so the result is always a valid stem.
531///
532/// The point is prov's legibility contract (DESIGN §1): a title-first
533/// authoring flow that still leaves *readable paths* in the tree and in
534/// path-addressed links — unlike an opaque `note-3.md`.
535pub fn slug(title: &str) -> String {
536 let mut out = String::with_capacity(title.len());
537 let mut pending_dash = false;
538 for ch in title.chars() {
539 if ch.is_alphanumeric() {
540 if pending_dash {
541 out.push('-');
542 pending_dash = false;
543 }
544 out.extend(ch.to_lowercase());
545 } else if ch.is_whitespace() || matches!(ch, '-' | '_' | '/') {
546 // Defer the separator: only emitted if a kept character follows, so
547 // leading, trailing, and repeated separators never reach `out`.
548 pending_dash = !out.is_empty();
549 }
550 // Any other character (punctuation, symbols) is dropped.
551 }
552 if out.is_empty() {
553 "untitled".to_string()
554 } else {
555 out
556 }
557}
558
559/// The character that begins a [sub-document locator](Link::locator) on a link
560/// target.
561pub const LOCATOR_SEPARATOR: char = '#';
562
563/// Split a target into the part naming a document and its locator.
564///
565/// Splits at the **first** separator, so a locator may itself contain one. Two
566/// targets deliberately have no locator:
567///
568/// - one with no `#` at all — the ordinary case;
569/// - one whose `#` is the *first* character (`#3`). That is a same-document
570/// reference, and reading it as a locator on an empty path would resolve the
571/// link to the containing *directory* — a silent retarget where doing nothing
572/// is correct.
573///
574/// Purely syntactic: callers that must not split an external URL's fragment
575/// guard with [`Link::is_external`] first, as [`Link::locator`] does.
576///
577/// The cost of the convention is a document whose *filename* contains `#`,
578/// which can no longer be linked by path. That is the same trade every URL and
579/// Markdown implementation makes, and the character is rare in filenames where
580/// a locator is not.
581pub fn split_locator(target: &str) -> (&str, Option<&str>) {
582 match target.split_once(LOCATOR_SEPARATOR) {
583 Some((doc, locator)) if !doc.is_empty() => (doc, Some(locator)),
584 _ => (target, None),
585 }
586}
587
588/// Re-attach a locator to a document target — the inverse of [`split_locator`].
589/// `None` returns the target unchanged, so this is safe on a target that never
590/// had one.
591pub fn join_locator(target: impl Into<String>, locator: Option<&str>) -> String {
592 let mut target = target.into();
593 if let Some(locator) = locator {
594 target.push(LOCATOR_SEPARATOR);
595 target.push_str(locator);
596 }
597 target
598}
599
600/// The target scheme marking a link-by-ID: `id:<id>`.
601pub const ID_SCHEME: &str = "id:";
602
603/// The legacy scheme (`colophon:<id>`), still recognized on read so existing
604/// workspaces keep resolving. New links are authored with [`ID_SCHEME`].
605pub const LEGACY_ID_SCHEME: &str = "colophon:";
606
607/// Strip the ID scheme from a target, accepting the current `id:` spelling or
608/// the legacy `colophon:` one. `None` when the target names no ID.
609pub fn strip_id_scheme(target: &str) -> Option<&str> {
610 target
611 .strip_prefix(ID_SCHEME)
612 .or_else(|| target.strip_prefix(LEGACY_ID_SCHEME))
613}
614
615/// Render an ID as a link target (`id:<id>`).
616pub fn id_target(id: &crate::identity::Id) -> String {
617 format!("{ID_SCHEME}{id}")
618}
619
620/// The character separating the workspace qualifier from the id in a
621/// cross-workspace reference (`id:<workspace>/<id>`).
622pub const WORKSPACE_SEPARATOR: char = '/';
623
624/// Render a cross-workspace reference as a link target (`id:<workspace>/<id>`).
625pub fn foreign_id_target(workspace: &str, id: &crate::identity::Id) -> String {
626 format!("{ID_SCHEME}{workspace}{WORKSPACE_SEPARATOR}{id}")
627}
628
629/// Whether `name` is a usable workspace self-name.
630///
631/// The constraint comes entirely from where the name is *written*: it is the
632/// qualifier in an `id:<workspace>/<id>` target, so it may not contain the
633/// [`WORKSPACE_SEPARATOR`] that divides it from the id, the `:` that ends the
634/// scheme, or whitespace (a target is a single scalar; a space would make it
635/// two). Anything else is the user's business — this is a name for humans to
636/// *choose*. [`identity::mint_workspace_id`](crate::identity::mint_workspace_id) (reached by `prov id
637/// --workspace`) can mint an opaque one for an owner with no naming authority
638/// to lean on, but only when asked: a minted name satisfies this predicate like
639/// any other, and nothing here can tell the two apart.
640///
641/// It lives beside the grammar it is a constraint on rather than in
642/// `prov-config` with the [`workspace_id`] key, because it is not a policy
643/// choice — every clause above is dictated by how [`IdRef`] parses, and a config
644/// layer that spelled its own version of this could drift from the parser that
645/// decides what a reference actually means.
646///
647/// Deliberately *not* checked: uniqueness across workspaces. Nothing here can
648/// see another workspace, so a collision is undetectable from inside; it is the
649/// resolving host's problem, and the host is the only thing with the evidence to
650/// notice ([`crate::peer`]). A minted name buys its uniqueness with width
651/// instead — the only currency available to something that cannot check.
652///
653/// [`workspace_id`]: crate::graph::ReadSettings::workspace_id
654pub fn is_valid_workspace_id(name: &str) -> bool {
655 !name.is_empty()
656 && !name
657 .chars()
658 .any(|c| c == WORKSPACE_SEPARATOR || c == ':' || c.is_whitespace())
659}
660
661/// What an `id:`-scheme target names.
662///
663/// The scheme carries three distinguishable things, and keeping them apart is
664/// the whole point: a reference prov can resolve, one it deliberately cannot,
665/// and one that is broken. See `docs/reference-styles.md`.
666#[derive(Debug, Clone, PartialEq, Eq)]
667pub enum IdRef {
668 /// `id:<id>` — a document in *this* workspace, resolved through the registry.
669 Local(crate::identity::Id),
670 /// `id:<workspace>/<id>` — a document in the workspace named `workspace`.
671 ///
672 /// prov resolves this only when `workspace` is the reading workspace's own
673 /// [`workspace_id`](crate::graph::ReadSettings::workspace_id), in which case it
674 /// *is* local and is treated as such. Any other name is somewhere prov
675 /// cannot see: the library holds no map from a workspace name to a location
676 /// (that is a fact about a device, not about an archive), so the reference is
677 /// carried, never rewritten, and never reported broken.
678 Foreign {
679 /// The workspace qualifier, exactly as written.
680 workspace: String,
681 /// The id, exactly as written. **Not** check-verified: the foreign
682 /// workspace owns its id space and need not be a prov workspace at all
683 /// (a diaryx ARK blade is a different length and alphabet), so applying
684 /// prov's check character here would reject valid references.
685 id: crate::identity::Id,
686 },
687 /// The `id:` scheme with a body that is no reference at all — an empty half
688 /// (`id:`, `id:/x`, `id:ws/`) or more than one separator (`id:a/b/c`).
689 ///
690 /// Deliberately its own case rather than falling through to a path: the
691 /// author wrote `id:`, so silently resolving the text as a filename would
692 /// turn a typo into a dangling path and hide what actually went wrong.
693 Malformed,
694}
695
696/// Parse the body of an `id:`-scheme target (the text after the scheme).
697fn parse_id_body(body: &str) -> IdRef {
698 let Some((workspace, id)) = body.split_once(WORKSPACE_SEPARATOR) else {
699 return if body.is_empty() {
700 IdRef::Malformed
701 } else {
702 IdRef::Local(crate::identity::Id(body.to_string()))
703 };
704 };
705 if workspace.is_empty() || id.is_empty() || id.contains(WORKSPACE_SEPARATOR) {
706 return IdRef::Malformed;
707 }
708 IdRef::Foreign {
709 workspace: workspace.to_string(),
710 id: crate::identity::Id(id.to_string()),
711 }
712}
713
714/// The syntactic wrapper a reference is written in — the first of the two style
715/// axes (see `docs/reference-styles.md`).
716#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
717pub enum Wrapper {
718 /// The diaryx/markdown family: `[Title](target)` or a bare target, with the
719 /// exact path rendering governed by [`ReferenceStyle::path_style`].
720 #[default]
721 Markdown,
722 /// The Obsidian wikilink: `[[target]]` / `[[target|label]]`.
723 Wikilink,
724}
725
726impl Wrapper {
727 /// Parse the `reference_wrapper` config spelling; unknown → `None`.
728 pub fn from_config_str(value: &str) -> Option<Self> {
729 match value {
730 "markdown" => Some(Self::Markdown),
731 "wikilink" => Some(Self::Wikilink),
732 _ => None,
733 }
734 }
735
736 /// The `reference_wrapper` config spelling.
737 pub fn as_config_str(self) -> &'static str {
738 match self {
739 Self::Markdown => "markdown",
740 Self::Wikilink => "wikilink",
741 }
742 }
743}
744
745/// What a reference addresses its target *by* — the second style axis.
746#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
747pub enum Addressing {
748 /// By path — rewritten on every move; rendering follows
749 /// [`ReferenceStyle::path_style`].
750 #[default]
751 Path,
752 /// By durable `id:<id>` handle — move-stable; authoring one registers the
753 /// target (the link-by-id trigger).
754 Id,
755 /// By the target's title/name, resolved nominally through the title index —
756 /// readable but not move/rename-safe, and never registers. Implies
757 /// [`Wrapper::Wikilink`].
758 Alias,
759}
760
761impl Addressing {
762 /// Parse the `reference_target` config spelling; unknown → `None`.
763 pub fn from_config_str(value: &str) -> Option<Self> {
764 match value {
765 "path" => Some(Self::Path),
766 "id" => Some(Self::Id),
767 "alias" => Some(Self::Alias),
768 _ => None,
769 }
770 }
771
772 /// The `reference_target` config spelling.
773 pub fn as_config_str(self) -> &'static str {
774 match self {
775 Self::Path => "path",
776 Self::Id => "id",
777 Self::Alias => "alias",
778 }
779 }
780}
781
782/// How a durable reference is spelled: a [`Wrapper`], an [`Addressing`], whether
783/// an `id` link carries a title label, and the path rendering used when
784/// addressing by path. This is the per-workspace default *and* the per-relation
785/// override (see [`crate::relation::Relation::style`]).
786#[derive(Debug, Clone, Copy, PartialEq, Eq)]
787pub struct ReferenceStyle {
788 /// The syntactic wrapper.
789 pub wrapper: Wrapper,
790 /// What the reference addresses its target by.
791 pub addressing: Addressing,
792 /// Whether an `id` wikilink carries a `|Title` label (a maintained cache of
793 /// the target's title). Ignored for markdown (its `[Title]` is intrinsic)
794 /// and for `alias` (the target string *is* the title).
795 pub label: bool,
796 /// Path rendering for [`Addressing::Path`] — ignored otherwise.
797 pub path_style: LinkStyle,
798}
799
800impl Default for ReferenceStyle {
801 /// Markdown path links in the default [`LinkStyle`] — the pre-existing
802 /// behavior, so an unconfigured workspace is unchanged.
803 fn default() -> Self {
804 Self {
805 wrapper: Wrapper::Markdown,
806 addressing: Addressing::Path,
807 label: false,
808 path_style: LinkStyle::default(),
809 }
810 }
811}
812
813impl ReferenceStyle {
814 /// Normalize impossible combinations: `alias` has no markdown spelling (there
815 /// is no locator to put in `[Title](…)`), so a markdown+alias request becomes
816 /// wikilink+alias.
817 pub fn normalized(mut self) -> Self {
818 if self.addressing == Addressing::Alias {
819 self.wrapper = Wrapper::Wikilink;
820 }
821 self
822 }
823
824 /// Whether authoring in this style is a *link-by-id* — the trigger that
825 /// registers the target. Only `id` addressing registers.
826 pub fn registers(self) -> bool {
827 self.addressing == Addressing::Id
828 }
829}
830
831/// Render a durable reference from the document at `from` to `to` (titled
832/// `title`) in `style`. `id` must be `Some` when the style addresses by id
833/// (the caller registers the target first); it is ignored otherwise. Returns the
834/// exact scalar to store in metadata (a wikilink scalar keeps its `[[…]]` — the
835/// metadata writer is responsible for any format-level quoting).
836pub fn format_reference(
837 style: ReferenceStyle,
838 from: &Path,
839 to: &Path,
840 id: Option<&crate::identity::Id>,
841 title: &str,
842) -> String {
843 let style = style.normalized();
844 match style.addressing {
845 // No id available (identity off / does not register on link) degrades to
846 // a path link, mirroring the pre-existing `authored_target` fallback.
847 Addressing::Id => match id {
848 Some(id) => wrap(style.wrapper, &id_target(id), title, style.label),
849 None => format_path(
850 Wrapper::Markdown,
851 style.path_style,
852 from,
853 to,
854 title,
855 style.label,
856 ),
857 },
858 Addressing::Alias => wrap_alias(title),
859 Addressing::Path => format_path(
860 style.wrapper,
861 style.path_style,
862 from,
863 to,
864 title,
865 style.label,
866 ),
867 }
868}
869
870/// Render a path reference in `wrapper` at `path_style`.
871fn format_path(
872 wrapper: Wrapper,
873 path_style: LinkStyle,
874 from: &Path,
875 to: &Path,
876 title: &str,
877 label: bool,
878) -> String {
879 match wrapper {
880 // Preserve the exact markdown/plain behavior (labeled vs bare) that
881 // `LinkStyle` already encodes — the `label` axis does not apply here.
882 Wrapper::Markdown => format_link(path_style, from, to, title),
883 Wrapper::Wikilink => wrap(
884 Wrapper::Wikilink,
885 &path_text(path_style, from, to),
886 title,
887 label,
888 ),
889 }
890}
891
892/// The bare path *text* a path reference points at, in the shape `path_style`
893/// selects: workspace-absolute (`/canonical`), relative, or canonical.
894pub fn path_text(path_style: LinkStyle, from: &Path, to: &Path) -> String {
895 match path_style {
896 LinkStyle::MarkdownRoot | LinkStyle::PlainRoot => format!("/{}", to.to_string_lossy()),
897 LinkStyle::MarkdownRelative | LinkStyle::PlainRelative => {
898 relative(from.parent().unwrap_or(Path::new("")), to)
899 }
900 }
901}
902
903/// Wrap a resolved `target` (already scheme-/path-formatted) in `wrapper`,
904/// attaching `title` as a label when `with_label`. A markdown reference without
905/// a label is emitted bare (`id:xxx`) — the diaryx-shaped id link.
906fn wrap(wrapper: Wrapper, target: &str, title: &str, with_label: bool) -> String {
907 match (wrapper, with_label) {
908 (Wrapper::Wikilink, true) => format!("[[{target}|{title}]]"),
909 (Wrapper::Wikilink, false) => format!("[[{target}]]"),
910 (Wrapper::Markdown, true) => format!("[{title}]({})", emit_target(target)),
911 (Wrapper::Markdown, false) => emit_target(target),
912 }
913}
914
915/// An alias reference: the title itself, as a bare-name wikilink.
916fn wrap_alias(title: &str) -> String {
917 format!("[[{title}]]")
918}
919
920/// A wikilink embedded in a document's body: `[[target]]` or, with an Obsidian
921/// pipe label, `[[target|label]]`.
922///
923/// This is the body-text sibling of a metadata [`Link`]. The `target` is either
924/// a path (`[[notes/a.md]]`, the identity-free Diaryx-style link that moves
925/// rewrite) or a `colophon:<id>` reference (`[[colophon:ajp7eq]]`, the
926/// location-independent Obsidian-style link that moves leave alone — the
927/// registry update is its maintenance). Which one a workspace mints is a policy
928/// choice; discovering the span is not, so the scanner is neutral between them.
929///
930/// [`span`](Wikilink::span) is the byte range of the whole `[[…]]` construct in
931/// the source body — exactly what a rewrite replaces, so a path retarget can
932/// splice a new target back in without re-parsing the prose around it.
933#[derive(Debug, Clone, PartialEq, Eq)]
934pub struct Wikilink {
935 /// The target as written between `[[` and the `|` (or the closing `]]`),
936 /// trimmed of surrounding whitespace.
937 pub target: String,
938 /// The display label after `|`, when written `[[target|label]]`.
939 pub label: Option<String>,
940 /// Byte range of the entire `[[…]]` span within the scanned body.
941 pub span: Range<usize>,
942}
943
944impl Wikilink {
945 /// Build a wikilink from the raw inner text (between `[[` and `]]`) and its
946 /// span. Splits an Obsidian `target|label` on the first `|`; an empty target
947 /// (e.g. `[[]]` or `[[ | x ]]`) is not a link and yields `None`.
948 fn from_inner(inner: &str, span: Range<usize>) -> Option<Self> {
949 let (target, label) = match inner.split_once('|') {
950 Some((target, label)) => (target.trim(), Some(label.trim().to_string())),
951 None => (inner.trim(), None),
952 };
953 if target.is_empty() {
954 return None;
955 }
956 Some(Self {
957 target: target.to_string(),
958 label,
959 span,
960 })
961 }
962
963 /// Render back to `[[target]]` / `[[target|label]]`. Surrounding whitespace
964 /// inside the brackets is not preserved — the rendered form is canonical.
965 pub fn render(&self) -> String {
966 match &self.label {
967 Some(label) => format!("[[{}|{label}]]", self.target),
968 None => format!("[[{}]]", self.target),
969 }
970 }
971
972 /// This wikilink with a different target, keeping the label — the move path
973 /// uses it to rewrite a *path* target while leaving the display text intact.
974 /// (ID targets are never rewritten; that is the whole point of using one.)
975 pub fn with_target(&self, target: impl Into<String>) -> Self {
976 Self {
977 target: target.into(),
978 label: self.label.clone(),
979 span: self.span.clone(),
980 }
981 }
982
983 /// The stable ID this wikilink names, when its target uses the `id:<id>`
984 /// scheme (or the legacy `colophon:<id>` spelling) — `None` for a plain path
985 /// target. Mirrors [`Link::id_target`], including its locator handling:
986 /// `[[id:abc1234#2]]` names the document `abc1234`.
987 pub fn id_target(&self) -> Option<crate::identity::Id> {
988 strip_id_scheme(split_locator(&self.target).0).map(|id| crate::identity::Id(id.to_string()))
989 }
990}
991
992/// Scan body prose for every `[[…]]` wikilink, in source order, each carrying
993/// its byte span. Purely lexical: unclosed `[[` is ignored, the first following
994/// `]]` closes the span, and no markdown structure (code spans, escapes) is
995/// interpreted — a higher layer decides whether a match in a code fence counts.
996pub fn parse_wikilinks(body: &str) -> Vec<Wikilink> {
997 let mut out = Vec::new();
998 let mut base = 0; // byte offset of `rest` within `body`
999 let mut rest = body;
1000 while let Some(open_rel) = rest.find("[[") {
1001 let open = base + open_rel;
1002 let after_open = open + 2;
1003 let Some(close_rel) = body[after_open..].find("]]") else {
1004 break; // no closing delimiter anywhere ahead — nothing more to find
1005 };
1006 let close = after_open + close_rel;
1007 if let Some(link) = Wikilink::from_inner(&body[after_open..close], open..close + 2) {
1008 out.push(link);
1009 }
1010 base = close + 2;
1011 rest = &body[base..];
1012 }
1013 out
1014}
1015
1016/// Keep only the wikilinks in `links` whose span does not overlap any of
1017/// `code_spans` — the code-awareness DESIGN §8 asks for: a `[[…]]` that is
1018/// really code (inside a fenced/inline code span) must never be treated as a
1019/// link.
1020///
1021/// **Caveat:** this only helps for a `links` list in which every real
1022/// wikilink was already found as its own match. It cannot rescue a real
1023/// `[[…]]` that [`parse_wikilinks`]' greedy "next `]]` wins" scan has already
1024/// merged into one bogus match together with an unrelated `[[` earlier in
1025/// the same code span — by the time that happens, the real link was never
1026/// emitted as a separate [`Wikilink`] to keep. [`scan_wikilinks`] avoids the
1027/// problem at the source (it never lets a lexical scan cross a code span in
1028/// the first place) and is what `census`/`check`/rename actually use; reach
1029/// for this function only when you already have a trustworthy `Vec<Wikilink>`
1030/// (e.g. from a segment [`scan_wikilinks`] itself produced) and just need the
1031/// range check.
1032pub fn exclude_code_spans(links: Vec<Wikilink>, code_spans: &[Range<usize>]) -> Vec<Wikilink> {
1033 links
1034 .into_iter()
1035 .filter(|link| {
1036 !code_spans
1037 .iter()
1038 .any(|cs| cs.start < link.span.end && link.span.start < cs.end)
1039 })
1040 .collect()
1041}
1042
1043/// Scan `body` for wikilinks the way `census`/`check`/the rename machinery
1044/// actually should — never [`parse_wikilinks`] directly. When `path`'s
1045/// extension names a format `twig` understands, every code span (fenced/inline
1046/// code, raw escapes) is treated as opaque *before* the lexical `[[`…`]]` scan
1047/// ever sees it: each prose run between code spans is scanned on its own and the
1048/// results stitched back into `body`-relative spans. For an unrecognized
1049/// extension — or if the parse fails — this is exactly [`parse_wikilinks`] over
1050/// the whole body, the same behavior as before code-awareness existed.
1051///
1052/// The span is **lexical either way**: twig has no wikilink concept, so it
1053/// supplies the mask and nothing more. A caller about to *rewrite* what a span
1054/// covers wants [`parsed_link_spans`] instead, which reports only spans twig
1055/// itself identified as links.
1056///
1057/// Scanning prose runs *separately*, rather than scanning the whole body and
1058/// filtering the results (what [`exclude_code_spans`] alone can do), matters:
1059/// [`parse_wikilinks`]' greedy scan finds each `[[` a *later* `]]`, code or
1060/// not, closes — so one stray `[[` in a code block (a Python
1061/// `[[float('inf')] * width ...]`, DESIGN §8's motivating example, life-sized)
1062/// can eat every `]]` after it, including a real `[[gone.md]]` further down
1063/// the body, merging them into one bogus match that swallows the real link
1064/// whole. No post-hoc filter can get that link back — it was never emitted
1065/// as its own match. Keeping code spans out of the scan in the first place
1066/// is the only fix; this function is that fix.
1067pub fn scan_wikilinks(path: &Path, body: &str) -> Vec<Wikilink> {
1068 match code_spans_for(path, body) {
1069 Some(spans) if !spans.is_empty() => scan_outside_spans(body, &merge_spans(spans)),
1070 _ => parse_wikilinks(body),
1071 }
1072}
1073
1074/// One link found in body prose: the parsed [`Link`] (target, label, and whether
1075/// it was an Obsidian `[[…]]` wikilink or a markdown/djot `[label](target)`
1076/// link) together with the byte [`span`](BodyLink::span) of the whole construct
1077/// — exactly what a rewrite replaces. The unifying body-link currency: census,
1078/// `check`, and the rename machinery all consume this, blind to which syntax the
1079/// link was written in.
1080#[derive(Debug, Clone, PartialEq, Eq)]
1081pub struct BodyLink {
1082 /// The parsed link — [`render`](Link::render) reproduces its original
1083 /// wrapper, so a retargeted `[[a]]` stays a wikilink and a `[t](a)` stays a
1084 /// markdown link.
1085 pub link: Link,
1086 /// Byte range of the whole link construct within the scanned body.
1087 pub span: Range<usize>,
1088}
1089
1090impl BodyLink {
1091 /// The stable ID this link names, if any — [`Link::id_target`] on the inner
1092 /// link. ID targets are never rewritten by a move.
1093 pub fn id_target(&self) -> Option<crate::identity::Id> {
1094 self.link.id_target()
1095 }
1096
1097 /// Whether this link's target is a path — [`Link::is_path_target`] on the
1098 /// inner link. The predicate the body-rewrite passes filter on.
1099 pub fn is_path_target(&self) -> bool {
1100 self.link.is_path_target()
1101 }
1102}
1103
1104/// Scan `body` for **every** link a move or a check must account for — Obsidian
1105/// `[[…]]` wikilinks *and* markdown/djot `[label](target)` links — each as a
1106/// [`BodyLink`] in source order. This is the single body-scan seam
1107/// `census`/`check`/rename use; it supersedes the wikilink-only
1108/// [`scan_wikilinks`] for callers that must also see markdown/djot links.
1109///
1110/// Two syntaxes, two finders, both code-aware:
1111/// - **Wikilinks** come from the lexical [`scan_wikilinks`] scan (code spans
1112/// excluded at the source, so a `[[` inside a fence can never eat a later real
1113/// link).
1114/// - **Markdown/djot links** come from `twig`'s parser
1115/// ([`crate::content::link_spans`]): it reports the span of each real `link`
1116/// node, so a `[x](y)` in a code fence, an autolink, or bracket text that is
1117/// not a link is never returned. Each span holds exactly one link, so parsing
1118/// it with [`Link::parse`] cannot over-reach across a stray `)` — the
1119/// balanced-paren hazard the lexical parser has is structurally absent here.
1120/// Only inline `[label](target)` links are kept (a successful markdown parse);
1121/// reference-style and autolink forms are left for a later pass.
1122///
1123/// Falls back to wikilinks only when the extension names no `twig` grammar or the
1124/// parse fails — the same graceful degradation [`scan_wikilinks`] already has.
1125pub fn scan_body_links(path: &Path, body: &str) -> Vec<BodyLink> {
1126 let mut out: Vec<BodyLink> = scan_wikilinks(path, body)
1127 .into_iter()
1128 .map(|wl| BodyLink {
1129 link: Link {
1130 label: wl.label,
1131 target: wl.target,
1132 wikilink: true,
1133 },
1134 span: wl.span,
1135 })
1136 .collect();
1137 for span in parsed_link_spans(path, body) {
1138 let link = Link::parse(&body[span.clone()]);
1139 // Keep only inline `[label](target)` links (a labeled markdown parse):
1140 // reference/autolink spans parse to a bare or external target and are
1141 // skipped. Defensively drop a span overlapping a wikilink we already have.
1142 if link.label.is_none() || link.wikilink {
1143 continue;
1144 }
1145 if out
1146 .iter()
1147 .any(|b| b.span.start < span.end && span.start < b.span.end)
1148 {
1149 continue;
1150 }
1151 out.push(BodyLink { link, span });
1152 }
1153 out.sort_by_key(|b| b.span.start);
1154 out
1155}
1156
1157/// The spans of markdown/djot inline links in `body`, via `twig` — empty when
1158/// `path`'s extension names no grammar `twig` understands or the parse fails
1159/// (the same degrade-to-lexical rule as `code_spans_for`).
1160///
1161/// **The "twig says it is a link" predicate.** These spans come from twig's own
1162/// `link` nodes, so a span here is a link an actual parser recognized, and each
1163/// holds exactly one link. That is a materially stronger claim than
1164/// [`scan_wikilinks`] can make about a `[[…]]`: twig has no wikilink concept, so
1165/// it only supplies the *code mask* there and the span itself is still lexical.
1166/// The gap matters wherever a repair is going to *write* — a lexical span may sit
1167/// in prose that merely looks like a link, and DESIGN §8's whole objection to
1168/// editing body prose is that `[[float('inf')] * width]` must never be
1169/// "repaired". So `validate`'s body-link remedies are offered for a span in this
1170/// set and no other.
1171pub fn parsed_link_spans(path: &Path, body: &str) -> Vec<Range<usize>> {
1172 let Some(format) = crate::content::ContentFormat::from_extension(path) else {
1173 return Vec::new();
1174 };
1175 crate::content::link_spans(body, format).unwrap_or_default()
1176}
1177
1178/// Sort-then-merge overlapping/adjacent ranges. `code_spans_for`'s sources
1179/// don't currently nest or overlap (code-block/verbatim/raw nodes are AST
1180/// leaves), but merging first keeps [`scan_outside_spans`] correct even if
1181/// that ever changes, and collapses touching spans into one gap-free skip.
1182fn merge_spans(mut spans: Vec<Range<usize>>) -> Vec<Range<usize>> {
1183 spans.sort_by_key(|s| s.start);
1184 let mut out: Vec<Range<usize>> = Vec::with_capacity(spans.len());
1185 for span in spans {
1186 match out.last_mut() {
1187 Some(prev) if span.start <= prev.end => prev.end = prev.end.max(span.end),
1188 _ => out.push(span),
1189 }
1190 }
1191 out
1192}
1193
1194/// Run [`parse_wikilinks`] independently on each run of `body` outside
1195/// `code_spans` (sorted, non-overlapping), then shift each match's span back
1196/// to `body`-relative coordinates before stitching the runs' results
1197/// together in source order. This is what keeps a `[[` inside a code span
1198/// from ever being in the same scan as prose that follows it.
1199fn scan_outside_spans(body: &str, code_spans: &[Range<usize>]) -> Vec<Wikilink> {
1200 let mut out = Vec::new();
1201 let mut cursor = 0;
1202 for span in code_spans {
1203 if cursor < span.start {
1204 out.extend(shift_spans(
1205 parse_wikilinks(&body[cursor..span.start]),
1206 cursor,
1207 ));
1208 }
1209 cursor = cursor.max(span.end);
1210 }
1211 if cursor < body.len() {
1212 out.extend(shift_spans(parse_wikilinks(&body[cursor..]), cursor));
1213 }
1214 out
1215}
1216
1217fn shift_spans(links: Vec<Wikilink>, offset: usize) -> Vec<Wikilink> {
1218 links
1219 .into_iter()
1220 .map(|link| Wikilink {
1221 span: link.span.start + offset..link.span.end + offset,
1222 ..link
1223 })
1224 .collect()
1225}
1226
1227fn code_spans_for(path: &Path, body: &str) -> Option<Vec<Range<usize>>> {
1228 let format = crate::content::ContentFormat::from_extension(path)?;
1229 // A twig failure degrades to "no spans" rather than aborting the scan —
1230 // code-awareness is a refinement, the purely lexical scan above is
1231 // always a safe fallback. An unrecognized extension is `None` (via
1232 // `from_extension`), scanning the whole body as before.
1233 crate::content::code_spans(body, format).ok()
1234}
1235
1236// Lexical path handling lives in `fs-transaction`, which needs the same
1237// normalization to clamp a staged op to its root. Re-exported here so prov's
1238// read guards and its write guards demonstrably share one implementation
1239// rather than two that agree by inspection.
1240pub use fs_transaction::path::{escapes_root, normalize};
1241
1242/// Resolve a link target written in `doc` to a normalized path in the same
1243/// coordinate system as `doc` (workspace-relative when `doc` is). A target with
1244/// a leading `/` is **workspace-absolute** — resolved from the root, not `doc`'s
1245/// directory, and never against the filesystem root; any other target is
1246/// relative to `doc`'s directory.
1247///
1248/// Any [sub-document locator](Link::locator) is dropped first: it names a place
1249/// inside the document, so it has no bearing on which file this is.
1250pub fn resolve(doc: &Path, target: &str) -> PathBuf {
1251 let (target, _) = split_locator(target);
1252 if let Some(from_root) = target.strip_prefix('/') {
1253 return normalize(from_root);
1254 }
1255 let dir = doc.parent().unwrap_or(Path::new(""));
1256 normalize(dir.join(target))
1257}
1258
1259/// The relative path string that reaches `to` from `from_dir` (both normalized,
1260/// same coordinate system). Rendered with forward slashes — link targets are
1261/// text, not platform paths.
1262pub fn relative(from_dir: &Path, to: &Path) -> String {
1263 let from: Vec<&std::ffi::OsStr> = from_dir.iter().collect();
1264 let to_parts: Vec<&std::ffi::OsStr> = to.iter().collect();
1265 let common = from
1266 .iter()
1267 .zip(to_parts.iter())
1268 .take_while(|(a, b)| a == b)
1269 .count();
1270 let mut parts: Vec<String> = Vec::new();
1271 for _ in common..from.len() {
1272 parts.push("..".to_string());
1273 }
1274 for part in &to_parts[common..] {
1275 parts.push(part.to_string_lossy().into_owned());
1276 }
1277 if parts.is_empty() {
1278 ".".to_string()
1279 } else {
1280 parts.join("/")
1281 }
1282}
1283
1284#[cfg(test)]
1285mod tests {
1286 use super::*;
1287 use std::path::Component;
1288
1289 #[test]
1290 fn locator_splits_at_the_first_separator_and_round_trips() {
1291 assert_eq!(split_locator("chapter.md"), ("chapter.md", None));
1292 assert_eq!(split_locator("chapter.md#3"), ("chapter.md", Some("3")));
1293 assert_eq!(split_locator("id:abc1234#2-3"), ("id:abc1234", Some("2-3")));
1294 // First separator wins, so a locator may itself contain one.
1295 assert_eq!(split_locator("a.md#b#c"), ("a.md", Some("b#c")));
1296 // An empty locator is still a locator — the author wrote the `#`.
1297 assert_eq!(split_locator("a.md#"), ("a.md", Some("")));
1298 // A leading `#` is a same-document reference, not a locator on "".
1299 assert_eq!(split_locator("#3"), ("#3", None));
1300
1301 for target in ["chapter.md", "chapter.md#3", "a.md#b#c", "a.md#", "#3"] {
1302 let (doc, locator) = split_locator(target);
1303 assert_eq!(join_locator(doc, locator), target, "round-trip `{target}`");
1304 }
1305 }
1306
1307 #[test]
1308 fn a_locator_does_not_change_which_document_is_named() {
1309 // Path targets: the locator is dropped before resolution.
1310 assert_eq!(
1311 resolve(Path::new("bofm/1-ne-1.md"), "1-ne-2.md#5"),
1312 PathBuf::from("bofm/1-ne-2.md")
1313 );
1314 assert_eq!(
1315 resolve(Path::new("a/b.md"), "/vol/c.md#2-3"),
1316 PathBuf::from("vol/c.md")
1317 );
1318
1319 // Id targets: same id with or without a locator.
1320 let plain = Link::parse("[1 Nephi 1](id:abc1234)");
1321 let located = Link::parse("[1 Nephi 1:1](id:abc1234#1)");
1322 assert_eq!(located.id_target(), plain.id_target());
1323 assert_eq!(located.id_ref(), plain.id_ref());
1324 assert_eq!(located.locator(), Some("1"));
1325 assert_eq!(located.addressed_target(), "id:abc1234");
1326 assert_eq!(plain.locator(), None);
1327
1328 // …and a located id target is still not a path, so no move rewrites it.
1329 assert!(!located.is_path_target());
1330 }
1331
1332 #[test]
1333 fn a_target_that_is_only_a_locator_names_no_path() {
1334 // `[Section One](#section-one)` is the commonest link in a long
1335 // markdown document, and it names no file at all. Reading it as a path
1336 // would look for a sibling *named* `#section-one`, which is how `check`
1337 // came to report every same-document anchor as a broken link.
1338 for target in [
1339 "#3",
1340 "#section-one",
1341 "[[#v2]]",
1342 "[Section One](#section-one)",
1343 ] {
1344 let link = Link::parse(target);
1345 assert!(link.is_same_document(), "{target}");
1346 assert!(!link.is_path_target(), "{target}");
1347 }
1348 // A locator *on* a document is the other case entirely: that one is a
1349 // path, and a move rewrites it.
1350 let located = Link::parse("chapter.md#3");
1351 assert!(!located.is_same_document());
1352 assert!(located.is_path_target());
1353 // A URL's fragment belongs to the URL, wherever it sits.
1354 assert!(!Link::parse("https://example.com/#top").is_same_document());
1355 }
1356
1357 #[test]
1358 fn an_external_url_keeps_its_own_fragment() {
1359 let url = Link::parse("[talk](https://example.com/a#p3)");
1360 assert!(url.is_external());
1361 assert_eq!(url.locator(), None);
1362 assert_eq!(url.addressed_target(), "https://example.com/a#p3");
1363 // Untouched by a rewrite, fragment and all.
1364 assert_eq!(url.with_path("x.md").render(), "[talk](x.md)");
1365 }
1366
1367 #[test]
1368 fn with_path_preserves_the_locator_but_with_target_does_not() {
1369 let link = Link::parse("[1 Nephi 1:1](../1-ne-1.md#1)");
1370 // The rewrite passes use `with_path`: a move changes where the document
1371 // lives, never which part of it was pointed at.
1372 assert_eq!(
1373 link.with_path("bofm/1-ne-1.md").render(),
1374 "[1 Nephi 1:1](bofm/1-ne-1.md#1)"
1375 );
1376 // `with_target` still sets the target verbatim.
1377 assert_eq!(
1378 link.with_target("bofm/1-ne-1.md").render(),
1379 "[1 Nephi 1:1](bofm/1-ne-1.md)"
1380 );
1381 // A wikilink keeps its wrapper and its locator alike.
1382 let wl = Link::parse("[[1-ne-1.md#1|1 Nephi 1:1]]");
1383 assert_eq!(wl.locator(), Some("1"));
1384 assert_eq!(wl.with_path("x.md").render(), "[[x.md#1|1 Nephi 1:1]]");
1385 }
1386
1387 #[test]
1388 fn slug_makes_readable_stems_and_round_trips_the_common_case() {
1389 assert_eq!(slug("My Great Note"), "my-great-note");
1390 // Collapses/strips separators and punctuation; keeps it legible.
1391 assert_eq!(slug(" Hello, World! "), "hello-world");
1392 assert_eq!(slug("already-a-slug"), "already-a-slug");
1393 assert_eq!(slug("under_scored/and slashed"), "under-scored-and-slashed");
1394 assert_eq!(slug("v1.0 Release"), "v10-release");
1395 // Unicode letters/digits survive.
1396 assert_eq!(slug("Café Notes"), "café-notes");
1397 // No leading/trailing/double dashes ever reach the output.
1398 assert_eq!(slug("--x--y--"), "x-y");
1399 // A title with nothing slug-able still yields a valid stem.
1400 assert_eq!(slug("!!!"), "untitled");
1401 assert_eq!(slug(""), "untitled");
1402 // The everyday case is the inverse of path_to_title.
1403 assert_eq!(
1404 path_to_title(std::path::Path::new("my-great-note.md")),
1405 "My Great Note"
1406 );
1407 }
1408
1409 #[test]
1410 fn parses_labeled_and_bare_links() {
1411 let l = Link::parse("[Design](docs/design.md)");
1412 assert_eq!(l.label.as_deref(), Some("Design"));
1413 assert_eq!(l.target, "docs/design.md");
1414 assert_eq!(l.render(), "[Design](docs/design.md)");
1415
1416 let bare = Link::parse("notes/a.md");
1417 assert_eq!(bare.label, None);
1418 assert_eq!(bare.render(), "notes/a.md");
1419 }
1420
1421 #[test]
1422 fn odd_shapes_fall_back_to_bare() {
1423 // A target with brackets but not the [label](target) shape.
1424 for raw in ["[unclosed](x", "no[mid](x)", "[]"] {
1425 assert_eq!(Link::parse(raw).render(), raw);
1426 }
1427 }
1428
1429 #[test]
1430 fn with_target_keeps_the_label() {
1431 let l = Link::parse("[Design](old.md)").with_target("new.md");
1432 assert_eq!(l.render(), "[Design](new.md)");
1433 }
1434
1435 #[test]
1436 fn external_links_are_flagged() {
1437 assert!(Link::parse("https://example.com/x").is_external());
1438 assert!(Link::parse("[me](mailto:a@b.c)").is_external());
1439 assert!(!Link::parse("docs/design.md").is_external());
1440 }
1441
1442 #[test]
1443 fn id_refs_split_into_local_foreign_and_malformed() {
1444 use crate::identity::Id;
1445 let r = |t: &str| Link::parse(t).id_ref();
1446 assert_eq!(r("id:ajp7eq"), Some(IdRef::Local(Id("ajp7eq".into()))));
1447 assert_eq!(
1448 r("id:notes/ajp7eq"),
1449 Some(IdRef::Foreign {
1450 workspace: "notes".into(),
1451 id: Id("ajp7eq".into()),
1452 })
1453 );
1454 // The legacy scheme carries a qualifier just as well — an old workspace
1455 // gains cross-workspace references without a rewrite.
1456 assert_eq!(
1457 r("colophon:notes/ajp7eq"),
1458 Some(IdRef::Foreign {
1459 workspace: "notes".into(),
1460 id: Id("ajp7eq".into()),
1461 })
1462 );
1463 // Every way the scheme can be present but the reference absent.
1464 for bad in ["id:", "id:/x", "id:ws/", "id:a/b/c"] {
1465 assert_eq!(r(bad), Some(IdRef::Malformed), "{bad}");
1466 }
1467 // No scheme at all is not an id ref — it is a path or an alias.
1468 assert_eq!(r("docs/design.md"), None);
1469 assert_eq!(r("https://example.com/x"), None);
1470 }
1471
1472 #[test]
1473 fn a_foreign_id_is_not_a_local_id() {
1474 // The distinction that keeps a foreign reference from being looked up in
1475 // the wrong registry: `id_target` is *local ids only*.
1476 let foreign = Link::parse("id:notes/ajp7eq");
1477 assert_eq!(foreign.id_target(), None);
1478 assert_eq!(
1479 foreign.foreign_target(),
1480 Some(("notes".into(), crate::identity::Id("ajp7eq".into())))
1481 );
1482 let local = Link::parse("id:ajp7eq");
1483 assert_eq!(
1484 local.id_target(),
1485 Some(crate::identity::Id("ajp7eq".into()))
1486 );
1487 assert_eq!(local.foreign_target(), None);
1488 }
1489
1490 #[test]
1491 fn only_paths_are_path_targets() {
1492 // The predicate every rewrite pass filters on. A move may rewrite the
1493 // first group and must leave the second alone — including the malformed
1494 // id, which is a broken reference, not a filename to re-relativize.
1495 for path in ["docs/design.md", "/a.md", "../b.md", "My Note"] {
1496 assert!(Link::parse(path).is_path_target(), "{path}");
1497 }
1498 for stable in [
1499 "id:ajp7eq",
1500 "id:notes/ajp7eq",
1501 "colophon:notes/ajp7eq",
1502 "id:a/b/c",
1503 "https://example.com/x",
1504 "mailto:a@b.c",
1505 // A same-document reference: byte-literal, so a move must leave it
1506 // alone as surely as it leaves an id alone.
1507 "#3",
1508 ] {
1509 assert!(!Link::parse(stable).is_path_target(), "{stable}");
1510 }
1511 }
1512
1513 #[test]
1514 fn foreign_targets_round_trip_through_rendering() {
1515 let target = foreign_id_target("notes", &crate::identity::Id("ajp7eq".into()));
1516 assert_eq!(target, "id:notes/ajp7eq");
1517 assert_eq!(
1518 Link::parse(&target).foreign_target(),
1519 Some(("notes".into(), crate::identity::Id("ajp7eq".into())))
1520 );
1521 // Through a labeled wikilink too, since that is how diaryx would author
1522 // one — the wrapper is orthogonal to the addressing.
1523 let wl = Link::parse("[[id:notes/ajp7eq|My Note]]");
1524 assert_eq!(wl.label.as_deref(), Some("My Note"));
1525 assert_eq!(
1526 wl.foreign_target(),
1527 Some(("notes".into(), crate::identity::Id("ajp7eq".into())))
1528 );
1529 assert_eq!(wl.render(), "[[id:notes/ajp7eq|My Note]]");
1530 }
1531
1532 #[test]
1533 fn parses_angle_bracketed_and_absolute_targets() {
1534 // Diaryx-style: a labeled link to an angle-bracketed, workspace-absolute
1535 // path containing a space.
1536 let l = Link::parse("[Archived Documents](</Archive/Archived documents.md>)");
1537 assert_eq!(l.label.as_deref(), Some("Archived Documents"));
1538 assert_eq!(l.target, "/Archive/Archived documents.md");
1539 // Round-trips: the space forces the angle brackets back on render.
1540 assert_eq!(
1541 l.render(),
1542 "[Archived Documents](</Archive/Archived documents.md>)"
1543 );
1544
1545 // A bare angle-bracketed target — no `[label](…)` around it — is
1546 // *not* unwrapped: angle brackets are only URL delimiters inside a
1547 // parsed markdown link, so a bare `<…>` value stays byte-literal (C2;
1548 // diaryx reads a bare `<…>` as a literal path, brackets and all). This
1549 // used to unwrap unconditionally; see `bare_angle_bracket_value_stays_literal`
1550 // for the dedicated regression coverage.
1551 let bare = Link::parse("</Creative Writing/Creative Writing.md>");
1552 assert_eq!(bare.target, "</Creative Writing/Creative Writing.md>");
1553 assert_eq!(bare.render(), "</Creative Writing/Creative Writing.md>");
1554
1555 // An absolute path without spaces needs no brackets, and stays bare.
1556 let plain = Link::parse("[Blog](/Blog/Blog.md)");
1557 assert_eq!(plain.target, "/Blog/Blog.md");
1558 assert_eq!(plain.render(), "[Blog](/Blog/Blog.md)");
1559 }
1560
1561 /// C2 regression: before the fix, the bare-value fallback ran `unbracket`
1562 /// on the *whole* raw value, so any `<...>`-shaped bare string (not just
1563 /// the diaryx example above) was silently unwrapped. Now the bare branch
1564 /// never touches angle brackets — only a successfully parsed
1565 /// `[label](<target>)` URL gets unwrapped.
1566 #[test]
1567 fn bare_angle_bracket_value_stays_literal() {
1568 for raw in ["<notes/a.md>", "<https://example.com>", "<a (b) c>", "<>"] {
1569 let l = Link::parse(raw);
1570 assert_eq!(l.label, None);
1571 assert_eq!(l.target, raw, "bare angle-bracket value must be literal");
1572 assert_eq!(l.render(), raw);
1573 }
1574 // Contrast: the *same* angle-bracketed text, once it's the URL of an
1575 // actual markdown link, is unwrapped — that part of the old behavior
1576 // was correct and stays.
1577 assert_eq!(Link::parse("[x](<notes/a.md>)").target, "notes/a.md");
1578 }
1579
1580 /// C3 regression: before the fix, the markdown-link branch demanded the
1581 /// *entire* trimmed input end in `)` (`raw.strip_suffix(')')`), so any
1582 /// trailing text after a well-formed link's closing paren made the whole
1583 /// value fall through to the bare branch — the complete string, including
1584 /// the `[label](target)` syntax, became one literal target. Balanced-paren
1585 /// scanning fixes both halves of that: trailing text is tolerated, and
1586 /// parens *inside* the target (nested, even) don't confuse the scan.
1587 #[test]
1588 fn markdown_link_split_tolerates_trailing_text_and_balanced_parens() {
1589 // Trailing prose after a legitimate link is ignored, not swallowed.
1590 let l = Link::parse("[Title](/path.md) trailing junk");
1591 assert_eq!(l.label.as_deref(), Some("Title"));
1592 assert_eq!(l.target, "/path.md");
1593
1594 // A target containing its own parens still closes at the matching `)`.
1595 let l = Link::parse("[Explanation (1.1)](/Archive/Explanation (1.1).md)");
1596 assert_eq!(l.label.as_deref(), Some("Explanation (1.1)"));
1597 assert_eq!(l.target, "/Archive/Explanation (1.1).md");
1598
1599 // Nested parens in the target keep working.
1600 let l = Link::parse("[File (a (b))](/path/file (a (b)).md)");
1601 assert_eq!(l.label.as_deref(), Some("File (a (b))"));
1602 assert_eq!(l.target, "/path/file (a (b)).md");
1603
1604 // Trailing text *and* parens in the target, together.
1605 let l = Link::parse("[T](/a (1).md) and then some more words");
1606 assert_eq!(l.target, "/a (1).md");
1607
1608 // An angle-bracketed URL still requires the `>` immediately followed by
1609 // `)` — trailing text after *that* `)` is likewise tolerated.
1610 let l = Link::parse("[Notes](</My Notes/x.md>) ignored tail");
1611 assert_eq!(l.target, "/My Notes/x.md");
1612
1613 // An unterminated target (no closing paren at all) still falls back to
1614 // bare, unchanged from before.
1615 let unterminated = "[Title](/path.md";
1616 assert_eq!(Link::parse(unterminated).render(), unterminated);
1617 }
1618
1619 /// C1: `parse_path_only` opts out of the `[[…]]` wikilink convention so a
1620 /// frontmatter path field can hold a literal bracket-shaped string without
1621 /// `Link::parse` reinterpreting it — the convention diaryx's own path-value
1622 /// parser never had. `parse` is unchanged (still treats it as a wikilink).
1623 #[test]
1624 fn wikilink_opt_out_keeps_bracket_literal_string() {
1625 let ordinary = Link::parse("[[notes/a.md]]");
1626 assert!(ordinary.wikilink);
1627 assert_eq!(ordinary.target, "notes/a.md");
1628
1629 let opted_out = Link::parse_path_only("[[notes/a.md]]");
1630 assert!(!opted_out.wikilink);
1631 assert_eq!(opted_out.label, None);
1632 assert_eq!(opted_out.target, "[[notes/a.md]]");
1633 assert_eq!(opted_out.render(), "[[notes/a.md]]");
1634
1635 // A pipe-labeled wikilink scalar is likewise kept as one literal bare
1636 // string, not split into label/target.
1637 let piped = Link::parse_path_only("[[notes/a.md|My Note]]");
1638 assert_eq!(piped.label, None);
1639 assert_eq!(piped.target, "[[notes/a.md|My Note]]");
1640
1641 // Every other `parse` rule is unaffected: markdown links, bare paths,
1642 // and angle-bracket handling (both C2's literal-bare and C3's
1643 // balanced-paren splitting) all behave identically under the opt-out.
1644 assert_eq!(
1645 Link::parse_path_only("[Design](docs/design.md)"),
1646 Link::parse("[Design](docs/design.md)")
1647 );
1648 assert_eq!(
1649 Link::parse_path_only("notes/a.md"),
1650 Link::parse("notes/a.md")
1651 );
1652 assert_eq!(
1653 Link::parse_path_only("<notes/a.md>"),
1654 Link::parse("<notes/a.md>")
1655 );
1656 }
1657
1658 #[test]
1659 fn formats_links_in_each_workspace_style() {
1660 let from = Path::new("School/MATH 213/hw.md");
1661 let target = Path::new("School/Archive/MATH 213 files.md");
1662 // MarkdownRoot: absolute, titled, angle-bracketed for the space.
1663 assert_eq!(
1664 format_link(LinkStyle::MarkdownRoot, from, target, "MATH 213 Files"),
1665 "[MATH 213 Files](</School/Archive/MATH 213 files.md>)"
1666 );
1667 // MarkdownRelative: relative, titled.
1668 assert_eq!(
1669 format_link(LinkStyle::MarkdownRelative, from, target, "MATH 213 Files"),
1670 "[MATH 213 Files](<../Archive/MATH 213 files.md>)"
1671 );
1672 // Plain styles: bare, no title.
1673 assert_eq!(
1674 format_link(LinkStyle::PlainRelative, from, target, "ignored"),
1675 "../Archive/MATH 213 files.md"
1676 );
1677 assert_eq!(
1678 format_link(LinkStyle::PlainRoot, from, target, "ignored"),
1679 "/School/Archive/MATH 213 files.md"
1680 );
1681 }
1682
1683 #[test]
1684 fn link_style_axes_round_trip_and_cover_every_combination() {
1685 use Notation::*;
1686 use PathStyle::*;
1687 // Every notation×path_style combination has a fused LinkStyle, and axes()
1688 // is its inverse — so the orthogonal config surface is lossless.
1689 for notation in [Markdown, Bare] {
1690 for path_style in [Root, Relative] {
1691 let style = LinkStyle::from_axes(notation, path_style);
1692 assert_eq!(style.axes(), (notation, path_style));
1693 }
1694 }
1695 // Wikilink has no bare/bracketed split, so it maps through the Markdown
1696 // family and its path text follows the path style.
1697 assert_eq!(
1698 LinkStyle::from_axes(Wikilink, Relative),
1699 LinkStyle::MarkdownRelative
1700 );
1701 assert_eq!(
1702 Notation::from_wrapper(Wrapper::Wikilink, LinkStyle::MarkdownRoot),
1703 Wikilink
1704 );
1705 assert_eq!(Notation::from_config_str("bare"), Some(Bare));
1706 assert_eq!(PathStyle::from_config_str("relative"), Some(Relative));
1707 // Retired: a bare workspace-relative path is unspellable, because a bare
1708 // path is directory-relative and the two cannot both be true.
1709 assert_eq!(PathStyle::from_config_str("canonical"), None);
1710 assert_eq!(LinkStyle::default(), LinkStyle::MarkdownRoot);
1711 assert_eq!(
1712 path_to_title(Path::new("Folder/utility_index.md")),
1713 "Utility Index"
1714 );
1715 }
1716
1717 #[test]
1718 fn the_bare_workspace_absolute_style_renders_a_leading_slash() {
1719 let from = Path::new("a/b.md");
1720 let to = Path::new("c/d.md");
1721 assert_eq!(format_link(LinkStyle::PlainRoot, from, to, "D"), "/c/d.md");
1722 }
1723
1724 #[test]
1725 fn resolves_workspace_absolute_paths_from_the_root() {
1726 // A leading slash means "from the workspace root", regardless of where
1727 // the linking document sits — and never the filesystem root.
1728 assert_eq!(
1729 resolve(Path::new("Meta/Meta files.md"), "/Blog/Blog.md"),
1730 PathBuf::from("Blog/Blog.md")
1731 );
1732 assert_eq!(
1733 resolve(Path::new("deep/nested/doc.md"), "/Resume.md"),
1734 PathBuf::from("Resume.md")
1735 );
1736 // Relative targets still resolve against the document's own directory.
1737 assert_eq!(
1738 resolve(Path::new("Meta/Meta files.md"), "../Blog/Blog.md"),
1739 PathBuf::from("Blog/Blog.md")
1740 );
1741 }
1742
1743 #[test]
1744 fn normalizes_dot_and_dotdot() {
1745 assert_eq!(normalize("a/./b/../c.md"), PathBuf::from("a/c.md"));
1746 assert_eq!(normalize("../up.md"), PathBuf::from("../up.md"));
1747 assert_eq!(normalize("a/b/../../x.md"), PathBuf::from("x.md"));
1748 }
1749
1750 #[test]
1751 fn resolves_against_the_documents_directory() {
1752 assert_eq!(
1753 resolve(Path::new("docs/index.md"), "../README.md"),
1754 PathBuf::from("README.md")
1755 );
1756 assert_eq!(
1757 resolve(Path::new("README.md"), "docs/design.md"),
1758 PathBuf::from("docs/design.md")
1759 );
1760 }
1761
1762 #[test]
1763 fn scans_bare_and_labeled_wikilinks_with_spans() {
1764 let body = "see [[notes/a.md]] and [[colophon:ajp7eq|My file]] here";
1765 let links = parse_wikilinks(body);
1766 assert_eq!(links.len(), 2);
1767
1768 assert_eq!(links[0].target, "notes/a.md");
1769 assert_eq!(links[0].label, None);
1770 assert_eq!(&body[links[0].span.clone()], "[[notes/a.md]]");
1771 assert_eq!(links[0].id_target(), None);
1772
1773 assert_eq!(links[1].target, "colophon:ajp7eq");
1774 assert_eq!(links[1].label.as_deref(), Some("My file"));
1775 assert_eq!(&body[links[1].span.clone()], "[[colophon:ajp7eq|My file]]");
1776 assert_eq!(
1777 links[1].id_target(),
1778 Some(crate::identity::Id("ajp7eq".into()))
1779 );
1780 }
1781
1782 #[test]
1783 fn wikilink_scan_trims_and_skips_degenerate_shapes() {
1784 // Whitespace inside the brackets is trimmed on both sides of the pipe.
1785 let trimmed = parse_wikilinks("x [[ notes/a.md | Label ]] y");
1786 assert_eq!(trimmed[0].target, "notes/a.md");
1787 assert_eq!(trimmed[0].label.as_deref(), Some("Label"));
1788
1789 // Empty target and unclosed openers are not links.
1790 assert!(parse_wikilinks("nothing [[]] here").is_empty());
1791 assert!(parse_wikilinks("[[ | orphan label ]]").is_empty());
1792 assert!(parse_wikilinks("dangling [[notes/a.md without close").is_empty());
1793 }
1794
1795 #[test]
1796 fn wikilink_render_round_trips_and_retargets() {
1797 let link = &parse_wikilinks("[[old.md|Design]]")[0];
1798 assert_eq!(link.render(), "[[old.md|Design]]");
1799 // Retarget keeps the label — the rename path relies on this.
1800 assert_eq!(link.with_target("new.md").render(), "[[new.md|Design]]");
1801
1802 let bare = &parse_wikilinks("[[old.md]]")[0];
1803 assert_eq!(bare.render(), "[[old.md]]");
1804 }
1805
1806 #[test]
1807 fn exclude_code_spans_drops_only_overlapping_wikilinks() {
1808 let body = "see [[notes/a.md]] and `[[not/a/link]]` too";
1809 let links = parse_wikilinks(body);
1810 assert_eq!(links.len(), 2, "the lexical scanner has no code awareness");
1811
1812 let code_start = body.find('`').unwrap();
1813 let code_end = body.rfind('`').unwrap() + 1;
1814 let code_span = code_start..code_end;
1815 let kept = exclude_code_spans(links, std::slice::from_ref(&code_span));
1816
1817 assert_eq!(kept.len(), 1);
1818 assert_eq!(kept[0].target, "notes/a.md");
1819 }
1820
1821 #[test]
1822 fn relative_walks_up_and_down() {
1823 assert_eq!(
1824 relative(Path::new("docs"), Path::new("README.md")),
1825 "../README.md"
1826 );
1827 assert_eq!(
1828 relative(Path::new(""), Path::new("docs/design.md")),
1829 "docs/design.md"
1830 );
1831 assert_eq!(relative(Path::new("a/b"), Path::new("a/b/c.md")), "c.md");
1832 assert_eq!(relative(Path::new("a/b"), Path::new("a/b")), ".");
1833 }
1834
1835 #[test]
1836 fn parses_and_round_trips_wikilink_scalars_in_metadata() {
1837 // A metadata scalar written as a wikilink resolves through the same
1838 // Link path as a markdown one, and round-trips its wrapper.
1839 let l = Link::parse("[[id:ajp7eqb|My File]]");
1840 assert!(l.wikilink);
1841 assert_eq!(l.label.as_deref(), Some("My File"));
1842 assert_eq!(l.target, "id:ajp7eqb");
1843 assert_eq!(l.id_target(), Some(crate::identity::Id("ajp7eqb".into())));
1844 assert_eq!(l.render(), "[[id:ajp7eqb|My File]]");
1845
1846 let bare = Link::parse("[[notes/a.md]]");
1847 assert!(bare.wikilink);
1848 assert_eq!(bare.label, None);
1849 assert_eq!(bare.render(), "[[notes/a.md]]");
1850 // Retarget keeps the wikilink wrapper and label.
1851 assert_eq!(
1852 l.with_target("id:zzzzzz9").render(),
1853 "[[id:zzzzzz9|My File]]"
1854 );
1855 }
1856
1857 #[test]
1858 fn id_scheme_reads_current_and_legacy_spellings() {
1859 assert_eq!(strip_id_scheme("id:ajp7eqb"), Some("ajp7eqb"));
1860 assert_eq!(strip_id_scheme("colophon:ajp7eqb"), Some("ajp7eqb"));
1861 assert_eq!(strip_id_scheme("notes/a.md"), None);
1862 // New links are authored in the `id:` spelling.
1863 assert_eq!(
1864 id_target(&crate::identity::Id("ajp7eqb".into())),
1865 "id:ajp7eqb"
1866 );
1867 assert_eq!(
1868 Link::parse("colophon:ajp7eqb").id_target().unwrap().0,
1869 "ajp7eqb"
1870 );
1871 }
1872
1873 #[test]
1874 fn format_reference_renders_each_style() {
1875 let from = Path::new("notes/hw.md");
1876 let to = Path::new("Archive/a.md");
1877 let id = crate::identity::Id("ajp7eqb".into());
1878 let s = |wrapper, addressing, label| ReferenceStyle {
1879 wrapper,
1880 addressing,
1881 label,
1882 path_style: LinkStyle::MarkdownRoot,
1883 };
1884
1885 // Markdown + path → the classic LinkStyle rendering.
1886 assert_eq!(
1887 format_reference(
1888 s(Wrapper::Markdown, Addressing::Path, false),
1889 from,
1890 to,
1891 None,
1892 "A"
1893 ),
1894 "[A](/Archive/a.md)"
1895 );
1896 // Wikilink + path, label off vs on.
1897 assert_eq!(
1898 format_reference(
1899 s(Wrapper::Wikilink, Addressing::Path, false),
1900 from,
1901 to,
1902 None,
1903 "A"
1904 ),
1905 "[[/Archive/a.md]]"
1906 );
1907 assert_eq!(
1908 format_reference(
1909 s(Wrapper::Wikilink, Addressing::Path, true),
1910 from,
1911 to,
1912 None,
1913 "A"
1914 ),
1915 "[[/Archive/a.md|A]]"
1916 );
1917 // Markdown + id: bare when unlabeled (the diaryx-shaped id link), a
1918 // titled markdown link when labeled.
1919 assert_eq!(
1920 format_reference(
1921 s(Wrapper::Markdown, Addressing::Id, false),
1922 from,
1923 to,
1924 Some(&id),
1925 "A"
1926 ),
1927 "id:ajp7eqb"
1928 );
1929 assert_eq!(
1930 format_reference(
1931 s(Wrapper::Markdown, Addressing::Id, true),
1932 from,
1933 to,
1934 Some(&id),
1935 "A"
1936 ),
1937 "[A](id:ajp7eqb)"
1938 );
1939 // Wikilink + id, no label / with label.
1940 assert_eq!(
1941 format_reference(
1942 s(Wrapper::Wikilink, Addressing::Id, false),
1943 from,
1944 to,
1945 Some(&id),
1946 "A"
1947 ),
1948 "[[id:ajp7eqb]]"
1949 );
1950 assert_eq!(
1951 format_reference(
1952 s(Wrapper::Wikilink, Addressing::Id, true),
1953 from,
1954 to,
1955 Some(&id),
1956 "A"
1957 ),
1958 "[[id:ajp7eqb|A]]"
1959 );
1960 // Alias is a bare-name wikilink, even if markdown was requested.
1961 assert_eq!(
1962 format_reference(
1963 s(Wrapper::Markdown, Addressing::Alias, false),
1964 from,
1965 to,
1966 None,
1967 "My File"
1968 ),
1969 "[[My File]]"
1970 );
1971 // Id addressing with no id available degrades to a path link.
1972 assert_eq!(
1973 format_reference(
1974 s(Wrapper::Wikilink, Addressing::Id, true),
1975 from,
1976 to,
1977 None,
1978 "A"
1979 ),
1980 "[A](/Archive/a.md)"
1981 );
1982 }
1983
1984 #[test]
1985 fn reference_style_config_round_trips_and_normalizes() {
1986 assert_eq!(
1987 Wrapper::from_config_str("wikilink"),
1988 Some(Wrapper::Wikilink)
1989 );
1990 assert_eq!(
1991 Addressing::from_config_str("alias"),
1992 Some(Addressing::Alias)
1993 );
1994 assert_eq!(Wrapper::Wikilink.as_config_str(), "wikilink");
1995 assert_eq!(Addressing::Id.as_config_str(), "id");
1996 // markdown + alias is impossible; normalization forces wikilink.
1997 let n = ReferenceStyle {
1998 addressing: Addressing::Alias,
1999 ..ReferenceStyle::default()
2000 }
2001 .normalized();
2002 assert_eq!(n.wrapper, Wrapper::Wikilink);
2003 assert!(
2004 ReferenceStyle {
2005 addressing: Addressing::Id,
2006 ..ReferenceStyle::default()
2007 }
2008 .registers()
2009 );
2010 assert!(!ReferenceStyle::default().registers());
2011 }
2012
2013 #[test]
2014 fn path_text_takes_the_path_style_shape() {
2015 let from = Path::new("a/b/hw.md");
2016 let to = Path::new("a/c/x.md");
2017 assert_eq!(path_text(LinkStyle::MarkdownRoot, from, to), "/a/c/x.md");
2018 assert_eq!(
2019 path_text(LinkStyle::MarkdownRelative, from, to),
2020 "../c/x.md"
2021 );
2022 assert_eq!(path_text(LinkStyle::PlainRoot, from, to), "/a/c/x.md");
2023 }
2024
2025 /// Laws, rather than examples.
2026 ///
2027 /// Every test above names one input and asserts the output prov produced
2028 /// for it. That is the right shape for a decision (`slug("v1.0 Release")`
2029 /// is `"v10-release"` because someone chose it), and the wrong shape for a
2030 /// *law* — a claim quantified over every input, of which an example
2031 /// witnesses exactly one. The round-trip below is a law: a link prov
2032 /// authors must name the document prov meant, from wherever it was
2033 /// written, in whichever style the workspace declared.
2034 mod properties {
2035 use super::*;
2036 use proptest::prelude::*;
2037
2038 /// A workspace-relative document path — up to two directories deep,
2039 /// short lowercase names. The alphabet is small on purpose: a
2040 /// counterexample is only useful if you can read it, and `a/b.md`
2041 /// makes the same point as `Xk9/qZ2.md` with none of the noise.
2042 fn doc_path() -> impl Strategy<Value = PathBuf> {
2043 (prop::collection::vec("[a-z]{1,3}", 0..3usize), "[a-z]{1,3}").prop_map(
2044 |(dirs, stem)| {
2045 let mut path = PathBuf::new();
2046 for dir in dirs {
2047 path.push(dir);
2048 }
2049 path.push(format!("{stem}.md"));
2050 path
2051 },
2052 )
2053 }
2054
2055 /// A path as a *human* might write one into frontmatter: real names
2056 /// mixed with the `.` and `..` a relative reference is made of. Unlike
2057 /// [`doc_path`] this may climb above the root (`../../x`), which is
2058 /// legal to *write* and refused later by [`escapes_root`] — the
2059 /// normalizer has to survive it either way.
2060 fn messy_path() -> impl Strategy<Value = PathBuf> {
2061 prop::collection::vec(
2062 prop_oneof![Just(".".to_string()), Just("..".to_string()), "[a-z]{1,3}"],
2063 1..5usize,
2064 )
2065 .prop_map(|parts| parts.iter().collect())
2066 }
2067
2068 /// Every style there is.
2069 ///
2070 /// This list was once four of six. The two `Canonical` styles emitted a
2071 /// bare *workspace*-relative path that [`resolve`] reads as
2072 /// *directory*-relative, so they failed the law below — and they are
2073 /// gone now rather than excused, which is why the strategy can name the
2074 /// whole enum again. A style that cannot be read back is not a style.
2075 fn round_tripping_style() -> impl Strategy<Value = LinkStyle> {
2076 prop::sample::select(vec![
2077 LinkStyle::MarkdownRoot,
2078 LinkStyle::MarkdownRelative,
2079 LinkStyle::PlainRoot,
2080 LinkStyle::PlainRelative,
2081 ])
2082 }
2083
2084 proptest! {
2085 /// `resolve ∘ format = id`: authoring a link to `to` from the
2086 /// document at `from`, then reading it back the way every consumer
2087 /// does (`Link::parse` for the scalar, `resolve` for the path),
2088 /// must land on `to` again. The whole point of a style axis is
2089 /// that it changes how a reference is *spelled* and not what it
2090 /// *means* — so this holds for every style, which is a claim the
2091 /// enum only earned once the canonical pair was retired.
2092 #[test]
2093 fn a_formatted_link_resolves_back_to_the_document_it_names(
2094 from in doc_path(),
2095 to in doc_path(),
2096 style in round_tripping_style(),
2097 ) {
2098 let written = format_link(style, &from, &to, "Label");
2099 let got = resolve(&from, &Link::parse(&written).target);
2100 prop_assert_eq!(
2101 &got,
2102 &to,
2103 "{:?} wrote `{}` in `{}`",
2104 style,
2105 written,
2106 from.display()
2107 );
2108 }
2109
2110 /// The law a move rests on: **re-relativizing a link preserves its
2111 /// referent.** `mutate::rename` rewrites every outbound path link
2112 /// of a document it moves by resolving the old text against the old
2113 /// location and re-rendering it against the new one
2114 /// (`rename.rs:236`). That is only safe if the two resolve to the
2115 /// same document — which is this, quantified over every pair of
2116 /// locations a document could move between.
2117 #[test]
2118 fn re_relativizing_a_link_preserves_the_document_it_names(
2119 from in doc_path(),
2120 to in doc_path(),
2121 referent in doc_path(),
2122 ) {
2123 let dir = |p: &Path| p.parent().unwrap_or(Path::new("")).to_path_buf();
2124 // As authored in the document at its old location.
2125 let written = relative(&dir(&from), &referent);
2126 // What `rename` writes when the document lands at `to`.
2127 let rewritten = relative(&dir(&to), &resolve(&from, &written));
2128 prop_assert_eq!(
2129 resolve(&to, &rewritten),
2130 referent,
2131 "`{}` moving {} → {} became `{}`",
2132 written,
2133 from.display(),
2134 to.display(),
2135 rewritten
2136 );
2137 }
2138
2139 /// [`normalize`] is idempotent — folding `.`/`..` a second time
2140 /// changes nothing. Load-bearing because resolved paths are
2141 /// compared for equality all over the crate (`move_conflict`, the
2142 /// registry's id↔path bijection, every `check` finding that says
2143 /// two links name the same document); a normal form that still
2144 /// moves under re-application would make those comparisons depend
2145 /// on how many times a path had been through the resolver.
2146 #[test]
2147 fn normalizing_a_path_twice_is_normalizing_it_once(path in messy_path()) {
2148 let once = normalize(&path);
2149 prop_assert_eq!(normalize(&once), once.clone(), "on `{}`", path.display());
2150 }
2151
2152 /// A normalized path has no `.` left, and any `..` that survives is
2153 /// a *leading* one — the climb above the root that could not be
2154 /// cancelled, which is precisely what [`escapes_root`] then looks
2155 /// for. A `..` appearing after a normal component would mean the
2156 /// fold missed a cancellation, and every path comparison downstream
2157 /// would be reading a path that still had reducing left to do.
2158 #[test]
2159 fn a_normalized_path_keeps_only_the_climb_it_could_not_cancel(
2160 path in messy_path(),
2161 ) {
2162 let normalized = normalize(&path);
2163 let parts: Vec<_> = normalized.components().collect();
2164 let climb = parts
2165 .iter()
2166 .take_while(|c| matches!(c, Component::ParentDir))
2167 .count();
2168 prop_assert!(
2169 parts[climb..]
2170 .iter()
2171 .all(|c| matches!(c, Component::Normal(_) | Component::RootDir)),
2172 "`{}` normalized to `{}`",
2173 path.display(),
2174 normalized.display()
2175 );
2176 }
2177 }
2178 }
2179}