1use std::collections::{BTreeMap, BTreeSet};
10
11use super::{Block, Book, Inline, NodeId, Section, block_attributes, block_id, inline_attributes};
12use super::{inline_id, rows, text};
13
14const IGNORED: &str = "!\"#$%&()*+,.:;<=>?@^`{|}~/[]\\_";
18
19#[derive(Debug, Clone, Default)]
22pub struct Anchors {
23 sources: Vec<Source>,
24 written: BTreeMap<String, NodeId>,
27 names: BTreeMap<NodeId, String>,
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum LinkTarget {
34 Node(NodeId),
37 Outside,
39 Missing,
41}
42
43#[derive(Debug, Clone)]
45struct Source {
46 name: Option<String>,
47 path: Option<String>,
50 first: NodeId,
52 written: BTreeMap<String, NodeId>,
53 slugs: BTreeMap<String, NodeId>,
54 headings: Vec<Heading>,
55}
56
57#[derive(Debug, Clone)]
58struct Heading {
59 node: NodeId,
60 level: u8,
61 text: String,
63 slug: Option<String>,
65}
66
67impl Book {
68 pub fn anchors(&self) -> Anchors {
73 Anchors::of(self)
74 }
75}
76
77impl Anchors {
78 pub fn of(book: &Book) -> Anchors {
80 let mut anchors = Anchors::default();
81 let mut index: BTreeMap<Option<&str>, usize> = BTreeMap::new();
82 for section in &book.sections {
83 let at = *index.entry(section.source.as_deref()).or_insert_with(|| {
84 anchors.sources.push(Source::new(section));
85 anchors.sources.len() - 1
86 });
87 let source = &mut anchors.sources[at];
88 source.collect(§ion.blocks);
89 }
90 for source in &mut anchors.sources {
91 source.count_slugs();
92 for (id, node) in &source.written {
93 anchors.written.entry(id.clone()).or_insert(*node);
94 }
95 }
96 let sources = std::mem::take(&mut anchors.sources);
97 for source in &sources {
98 anchors.name_source(source);
99 }
100 anchors.sources = sources;
101 anchors
102 }
103
104 pub fn resolve(&self, url: &str, from: Option<&str>) -> LinkTarget {
123 if url.is_empty() {
124 return LinkTarget::Missing;
125 }
126 if outside(url) {
127 return LinkTarget::Outside;
128 }
129 let (path, fragment) = match url.split_once('#') {
130 Some((path, fragment)) => (path, Some(fragment)),
131 None => (url, None),
132 };
133 let from = self.sources.iter().position(|s| s.name.as_deref() == from);
134 let source = if path.is_empty() {
135 from
136 } else {
137 match self.find(&decode(path), from) {
138 Some(source) => Some(source),
139 None => return LinkTarget::Missing,
140 }
141 };
142 let fragment = fragment.map(decode).filter(|fragment| !fragment.is_empty());
143 let found = match &fragment {
144 None if path.is_empty() => None,
145 None => source.map(|source| self.sources[source].first),
146 Some(fragment) => source
147 .and_then(|source| self.sources[source].find(fragment))
148 .or_else(|| {
149 path.is_empty()
150 .then(|| self.written.get(fragment).copied())
151 .flatten()
152 }),
153 };
154 found.map_or(LinkTarget::Missing, LinkTarget::Node)
155 }
156
157 pub(crate) fn name(&self, node: NodeId) -> Option<&str> {
159 self.names.get(&node).map(String::as_str)
160 }
161
162 pub(crate) fn reaches(&self, node: NodeId) -> bool {
164 self.names.contains_key(&node)
165 }
166
167 fn find(&self, path: &str, from: Option<usize>) -> Option<usize> {
168 let folder = from
169 .and_then(|from| self.sources[from].path.as_deref())
170 .and_then(|path| path.rsplit_once('/'))
171 .map_or("", |(folder, _)| folder);
172 let relative = path.starts_with("./") || path.starts_with("../");
173 let rooted = path.starts_with('/');
174 let wanted = match (relative, folder.is_empty()) {
175 (true, false) => path_key(&format!("{folder}/{path}")),
176 (true, true) => path_key(path),
177 (false, _) => path_key(path.trim_start_matches('/')),
178 };
179 let named = || {
180 self.sources
181 .iter()
182 .enumerate()
183 .filter_map(|(at, source)| Some((at, source.path.as_deref()?)))
184 };
185 if let Some((at, _)) = named().find(|(_, path)| *path == wanted) {
186 return Some(at);
187 }
188 if relative || rooted || wanted.is_empty() {
189 return None;
190 }
191 let ending = format!("/{wanted}");
192 let within = format!("{folder}/");
193 let ends = || named().filter(|(_, path)| path.ends_with(&ending));
194 ends()
195 .find(|(_, path)| !folder.is_empty() && path.starts_with(&within))
196 .or_else(|| ends().next())
197 .map(|(at, _)| at)
198 }
199
200 fn name_source(&mut self, source: &Source) {
201 let prefix = source.name.as_deref().unwrap_or_default();
202 if let Some(name) = &source.name {
203 self.names.insert(source.first, name.clone());
204 }
205 for (id, node) in &source.written {
206 self.names.entry(*node).or_insert_with(|| id.clone());
207 }
208 for (slug, node) in &source.slugs {
209 self.names
210 .entry(*node)
211 .or_insert_with(|| format!("{prefix}#{slug}"));
212 }
213 for heading in source.headings.iter().filter(|h| !h.text.is_empty()) {
214 self.names
215 .entry(heading.node)
216 .or_insert_with(|| format!("{prefix}#{}", heading.text));
217 }
218 }
219}
220
221impl Source {
222 fn new(section: &Section) -> Source {
223 Source {
224 name: section.source.clone(),
225 path: section.source.as_deref().map(path_key),
226 first: section.id,
227 written: BTreeMap::new(),
228 slugs: BTreeMap::new(),
229 headings: Vec::new(),
230 }
231 }
232
233 fn collect(&mut self, blocks: &[Block]) {
234 for block in blocks {
235 self.write(block_id(block), &block_attributes(block).id);
236 match block {
237 Block::Heading {
238 id,
239 level,
240 inlines,
241 attributes,
242 ..
243 } => {
244 let words = text(inlines);
245 self.headings.push(Heading {
246 node: *id,
247 level: u8::from(*level),
248 text: matched(&words),
249 slug: attributes.id.is_none().then(|| slug(&words)).flatten(),
250 });
251 self.collect_inlines(inlines);
252 }
253 Block::Paragraph { inlines, .. } => self.collect_inlines(inlines),
254 Block::Blockquote { blocks, .. } => self.collect(blocks),
255 Block::List { items, .. } => {
256 for item in items {
257 self.write(item.id, &item.attributes.id);
258 self.collect(&item.blocks);
259 }
260 }
261 Block::Table { head, body, .. } => {
262 for row in rows(head, body) {
263 self.write(row.id, &row.attributes.id);
264 for cell in &row.cells {
265 self.write(cell.id, &cell.attributes.id);
266 self.collect(&cell.blocks);
267 }
268 }
269 }
270 Block::CodeBlock { .. }
271 | Block::ThematicBreak { .. }
272 | Block::PageBreak { .. }
273 | Block::ColumnBreak { .. }
274 | Block::Image { .. } => {}
275 }
276 }
277 }
278
279 fn collect_inlines(&mut self, inlines: &[Inline]) {
280 for inline in inlines {
281 self.write(inline_id(inline), &inline_attributes(inline).id);
282 if let Inline::Emphasis { children, .. }
283 | Inline::Strong { children, .. }
284 | Inline::Link { children, .. }
285 | Inline::Strikethrough { children, .. }
286 | Inline::Highlight { children, .. }
287 | Inline::Span { children, .. } = inline
288 {
289 self.collect_inlines(children);
290 }
291 }
292 }
293
294 fn write(&mut self, node: NodeId, id: &Option<String>) {
295 if let Some(id) = id {
296 self.written.entry(id.clone()).or_insert(node);
297 }
298 }
299
300 fn count_slugs(&mut self) {
304 let mut taken: BTreeSet<String> = self.written.keys().cloned().collect();
305 for heading in &self.headings {
306 let Some(base) = &heading.slug else {
307 continue;
308 };
309 let mut slug = base.clone();
310 let mut count = 2;
311 while taken.contains(&slug) {
312 slug = format!("{base}-{count}");
313 count += 1;
314 }
315 taken.insert(slug.clone());
316 self.slugs.insert(slug, heading.node);
317 }
318 }
319
320 fn find(&self, fragment: &str) -> Option<NodeId> {
321 if let Some(node) = self
322 .written
323 .get(fragment)
324 .or_else(|| self.slugs.get(fragment))
325 {
326 return Some(*node);
327 }
328 let wanted: Vec<String> = fragment
329 .split('#')
330 .map(matched)
331 .filter(|text| !text.is_empty())
332 .collect();
333 let mut wanted = wanted.iter();
334 let mut next = wanted.next()?;
335 let mut level = 0;
336 for heading in &self.headings {
337 if heading.level > level && heading.text == *next {
338 level = heading.level;
339 match wanted.next() {
340 Some(text) => next = text,
341 None => return Some(heading.node),
342 }
343 }
344 }
345 None
346 }
347}
348
349fn slug(text: &str) -> Option<String> {
353 let lower = text.to_lowercase();
354 let words: Vec<&str> = lower
355 .split(|c: char| !c.is_alphanumeric())
356 .filter(|word| !word.is_empty())
357 .collect();
358 (!words.is_empty()).then(|| words.join("-"))
359}
360
361fn matched(text: &str) -> String {
364 let spaced: String = text
365 .chars()
366 .map(|c| if IGNORED.contains(c) { ' ' } else { c })
367 .collect();
368 spaced
369 .split_whitespace()
370 .collect::<Vec<_>>()
371 .join(" ")
372 .to_lowercase()
373}
374
375fn path_key(path: &str) -> String {
378 let lower = path.replace('\\', "/").to_lowercase();
379 let lower = lower.strip_suffix(".md").unwrap_or(&lower);
380 let rooted = lower.starts_with('/');
381 let mut parts: Vec<&str> = Vec::new();
382 for part in lower.split('/') {
383 match part {
384 "" | "." => {}
385 ".." if parts.last().is_some_and(|last| *last != "..") => {
386 parts.pop();
387 }
388 part => parts.push(part),
389 }
390 }
391 let joined = parts.join("/");
392 if rooted { format!("/{joined}") } else { joined }
393}
394
395fn outside(url: &str) -> bool {
398 if url.starts_with("//") {
399 return true;
400 }
401 let Some((scheme, _)) = url.split_once(':') else {
402 return false;
403 };
404 scheme.starts_with(|c: char| c.is_ascii_alphabetic())
405 && scheme
406 .chars()
407 .all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c))
408}
409
410fn decode(text: &str) -> String {
413 let bytes = text.as_bytes();
414 let mut out = Vec::with_capacity(bytes.len());
415 let mut at = 0;
416 while at < bytes.len() {
417 let escape = bytes
418 .get(at + 1..at + 3)
419 .filter(|hex| bytes[at] == b'%' && hex.iter().all(u8::is_ascii_hexdigit));
420 match escape {
421 Some(hex) => {
422 let hex = std::str::from_utf8(hex).expect("hex digits are ASCII");
423 out.push(u8::from_str_radix(hex, 16).expect("two hex digits are a byte"));
424 at += 3;
425 }
426 None => {
427 out.push(bytes[at]);
428 at += 1;
429 }
430 }
431 }
432 String::from_utf8(out).unwrap_or_else(|_| text.to_string())
433}
434
435#[cfg(test)]
436mod tests {
437 use super::*;
438 use crate::content::{Attributes, HeadingLevel};
439
440 fn words(value: &str) -> Inline {
441 Inline::Text {
442 id: NodeId::UNASSIGNED,
443 value: value.into(),
444 attributes: Attributes::default(),
445 position: None,
446 span: None,
447 }
448 }
449
450 fn heading_at(level: HeadingLevel, inlines: Vec<Inline>, written: Option<&str>) -> Block {
451 Block::Heading {
452 id: NodeId::UNASSIGNED,
453 level,
454 inlines,
455 attributes: Attributes {
456 id: written.map(Into::into),
457 classes: Vec::new(),
458 },
459 position: None,
460 span: None,
461 }
462 }
463
464 fn h1(title: &str) -> Block {
465 heading_at(HeadingLevel::H1, vec![words(title)], None)
466 }
467
468 fn h2(title: &str) -> Block {
469 heading_at(HeadingLevel::H2, vec![words(title)], None)
470 }
471
472 fn source(name: Option<&str>, blocks: Vec<Block>) -> Section {
473 Section {
474 attributes: Default::default(),
475 source: name.map(Into::into),
476 blocks,
477 ..Section::default()
478 }
479 }
480
481 fn book(sections: Vec<Section>) -> Book {
482 let mut book = Book {
483 sections,
484 ..Book::default()
485 };
486 book.assign_node_ids();
487 book
488 }
489
490 fn heading(book: &Book, nth: usize) -> LinkTarget {
492 let mut headings = Vec::new();
493 fn each(blocks: &[Block], out: &mut Vec<NodeId>) {
494 for block in blocks {
495 match block {
496 Block::Heading { id, .. } => out.push(*id),
497 Block::Blockquote { blocks, .. } => each(blocks, out),
498 _ => {}
499 }
500 }
501 }
502 for section in &book.sections {
503 each(§ion.blocks, &mut headings);
504 }
505 LinkTarget::Node(headings[nth])
506 }
507
508 #[test]
509 fn a_slug_is_the_text_lowercased_with_hyphens() {
510 for (title, want) in [
511 ("The Hunter", Some("the-hunter")),
512 (" Chapter 1: “Arrival”! ", Some("chapter-1-arrival")),
513 ("Café Noir", Some("café-noir")),
514 ("— ? —", None),
515 ("", None),
516 ] {
517 assert_eq!(slug(title).as_deref(), want, "{title:?}");
518 }
519 }
520
521 #[test]
524 fn slugs_count_per_source() {
525 let book = book(vec![
526 source(Some("one.md"), vec![h1("Notes"), h1("Notes")]),
527 source(
528 Some("two.md"),
529 vec![
530 h1("Notes"),
531 heading_at(HeadingLevel::H1, vec![words("Hunt")], Some("hunt")),
532 h1("Hunt"),
533 ],
534 ),
535 source(Some("three.md"), vec![h1("Hunt")]),
536 ]);
537 let anchors = book.anchors();
538 let at = |url, from| anchors.resolve(url, Some(from));
539 assert_eq!(at("#notes", "one.md"), heading(&book, 0));
540 assert_eq!(at("#notes-2", "one.md"), heading(&book, 1));
541 assert_eq!(at("#notes", "two.md"), heading(&book, 2));
542 assert_eq!(at("#notes-2", "two.md"), LinkTarget::Missing);
543 assert_eq!(at("#hunt", "two.md"), heading(&book, 3));
544 assert_eq!(at("#hunt-2", "two.md"), heading(&book, 4));
545 assert_eq!(at("#hunt", "three.md"), heading(&book, 5));
546 }
547
548 #[test]
551 fn text_form_matches_as_obsidian_does() {
552 let book = book(vec![source(
553 Some("note.md"),
554 vec![
555 heading_at(
556 HeadingLevel::H2,
557 vec![
558 words("What's "),
559 Inline::Emphasis {
560 id: NodeId::UNASSIGNED,
561 children: vec![words("new")],
562 attributes: Attributes::default(),
563 position: None,
564 span: None,
565 },
566 words("?"),
567 ],
568 None,
569 ),
570 h2("A: B / C"),
571 h2("A B C"),
572 ],
573 )]);
574 let anchors = book.anchors();
575 for (url, nth) in [
576 ("#What's *new*?", 0),
577 ("#what's new", 0),
578 ("#What's%20_new_", 0),
579 ("#A B / C", 1),
580 ("#a b c", 1),
581 ("#a-b-c-2", 2),
582 ] {
583 assert_eq!(
584 anchors.resolve(url, Some("note.md")),
585 heading(&book, nth),
586 "{url}"
587 );
588 }
589 assert_eq!(
590 anchors.resolve("#whats new", Some("note.md")),
591 LinkTarget::Missing
592 );
593 }
594
595 #[test]
598 fn a_nested_heading_follows_its_parents() {
599 let book = book(vec![source(
600 Some("note.md"),
601 vec![
602 h2("Notes"),
603 h1("Part"),
604 h2("Notes"),
605 h1("Other"),
606 h2("Notes"),
607 ],
608 )]);
609 let anchors = book.anchors();
610 let at = |url| anchors.resolve(url, Some("note.md"));
611 assert_eq!(at("#Notes"), heading(&book, 0));
612 assert_eq!(at("#Part#Notes"), heading(&book, 2));
613 assert_eq!(at("#Other#Notes"), heading(&book, 4));
614 assert_eq!(at("#Notes#Part"), LinkTarget::Missing);
615 }
616
617 #[test]
618 fn a_file_matches_as_obsidian_finds_it() {
619 let book = book(vec![
620 source(Some("vault/part-1/Chapter 3.md"), vec![h1("One")]),
621 source(Some("vault/part-2/Chapter 3.md"), vec![h1("Two")]),
622 source(Some("vault/part-2/notes.md"), vec![h1("Notes")]),
623 source(Some("vault/index.md"), vec![h1("Index")]),
624 ]);
625 let anchors = book.anchors();
626 let at = |url, from| anchors.resolve(url, Some(from));
627 let notes = "vault/part-2/notes.md";
628 let index = "vault/index.md";
629 for (url, from, nth) in [
630 ("Chapter 3#One", index, 0),
631 ("chapter 3.MD#one", index, 0),
632 ("Chapter%203.md#One", index, 0),
633 ("Chapter 3#Two", notes, 1),
634 ("./Chapter 3.md#Two", notes, 1),
635 ("../part-1/Chapter 3#One", notes, 0),
636 ("part-2/chapter 3#two", index, 1),
637 ("vault/part-2/Chapter 3#Two", index, 1),
638 ("notes", index, 2),
639 ] {
640 let found = anchors.resolve(url, Some(from));
641 match heading(&book, nth) {
642 _ if !url.contains('#') => {
644 assert_eq!(found, LinkTarget::Node(book.sections[nth].id), "{url}")
645 }
646 want => assert_eq!(found, want, "{url} from {from}"),
647 }
648 }
649 assert_eq!(at("./Chapter 3#One", notes), LinkTarget::Missing);
650 assert_eq!(at("/part-2/notes", index), LinkTarget::Missing);
651 assert_eq!(at("elsewhere.md#One", index), LinkTarget::Missing);
652 }
653
654 #[test]
657 fn a_file_alone_reaches_its_first_section() {
658 let book = book(vec![
659 source(Some("one.md"), vec![h1("A")]),
660 source(Some("two.md"), vec![h1("B")]),
661 source(Some("two.md"), vec![h1("C")]),
662 ]);
663 let anchors = book.anchors();
664 assert_eq!(
665 anchors.resolve("two", Some("one.md")),
666 LinkTarget::Node(book.sections[1].id)
667 );
668 assert_eq!(anchors.name(book.sections[1].id), Some("two.md"));
669 assert!(!anchors.reaches(book.sections[2].id));
670 }
671
672 #[test]
675 fn a_written_id_reaches_across_sources() {
676 let chase = heading_at(HeadingLevel::H1, vec![words("Chase")], Some("hunt"));
677 let book = book(vec![
678 source(Some("one.md"), vec![chase]),
679 source(Some("two.md"), vec![h1("Other")]),
680 source(Some("three.md"), vec![h1("Hunt")]),
681 ]);
682 let anchors = book.anchors();
683 assert_eq!(anchors.resolve("#hunt", Some("two.md")), heading(&book, 0));
684 assert_eq!(
685 anchors.resolve("#hunt", Some("three.md")),
686 heading(&book, 2)
687 );
688 assert_eq!(
689 anchors.resolve("two.md#hunt", Some("one.md")),
690 LinkTarget::Missing
691 );
692 assert_eq!(
693 anchors.name(block_id(&book.sections[0].blocks[0])),
694 Some("hunt")
695 );
696 assert_eq!(
697 anchors.name(block_id(&book.sections[2].blocks[0])),
698 Some("three.md#hunt")
699 );
700 }
701
702 #[test]
703 fn a_url_with_a_scheme_is_outside() {
704 let book = book(vec![source(None, vec![h1("A")])]);
705 let anchors = book.anchors();
706 for url in ["https://example.com", "mailto:a@b.c", "//example.com/x"] {
707 assert_eq!(anchors.resolve(url, None), LinkTarget::Outside, "{url}");
708 }
709 for url in ["", "#", "#b", "a.md", "A B#c"] {
710 assert_eq!(anchors.resolve(url, None), LinkTarget::Missing, "{url}");
711 }
712 assert_eq!(anchors.resolve("#a", None), heading(&book, 0));
713 }
714
715 #[test]
716 fn a_percent_escape_decodes() {
717 assert_eq!(decode("Chapter%203"), "Chapter 3");
718 assert_eq!(decode("caf%C3%A9"), "café");
719 assert_eq!(decode("100% sure%2"), "100% sure%2");
720 assert_eq!(decode("%FF"), "%FF");
721 }
722}