mull 0.26.1

Organize your knowledge.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
use crate::{
    error::{Error, SourceRange},
    format::{CodePath, CodeStr},
    scoring::populate_depths,
    wiki::{
        DIRECTORY_LINK_SUFFIX, FILESYSTEM_LINK_PREFIX, Link, TITLE_MARKER, TITLE_PREFIX, TextNode,
        Wiki, escape_link_delimiters, unescape_link_delimiters,
    },
};
use std::path::{Component, Path, PathBuf};

// This struct retains the source information needed to finish a node at its next boundary.
struct PendingNode {
    title: String,
    source_start: usize,
    content_start: usize,
    title_source_range: SourceRange,
}

// Parse source contents into a scored wiki with source ranges for every node and link.
pub fn parse(source_path: Option<&Path>, source_contents: &str) -> Result<Wiki, Vec<Error>> {
    // Accumulate parsed nodes, errors, and the node currently being read.
    let mut wiki = Wiki::default();
    let mut errors = Vec::<Error>::new();
    let mut pending_node = None::<PendingNode>;
    let mut has_seen_title_marker = false;
    let mut reported_content_before_title = false;
    let mut line_start = 0;

    // Process ranged source lines as boundaries while retaining their original byte offsets.
    for raw_line in source_contents.split_inclusive('\n') {
        let next_line_start = line_start + raw_line.len();
        let line_with_possible_carriage_return = raw_line.strip_suffix('\n').unwrap_or(raw_line);
        let line = line_with_possible_carriage_return
            .strip_suffix('\r')
            .unwrap_or(line_with_possible_carriage_return);
        let line_source_range = SourceRange {
            start: line_start,
            end: line_start + line.len(),
        };

        // Recognize a title marker followed by either a space or the end of the line.
        let raw_title = if line == TITLE_MARKER {
            Some("")
        } else {
            line.strip_prefix(TITLE_PREFIX)
        };
        if let Some(raw_title) = raw_title {
            // Treat invalid titles as structural boundaries for subsequent content.
            has_seen_title_marker = true;

            // Finish the preceding node before starting the next one.
            if let Some(previous_node) = pending_node.take()
                && let Err(node_errors) = insert_node(
                    &mut wiki,
                    previous_node,
                    line_start,
                    source_path,
                    source_contents,
                )
            {
                errors.extend(node_errors);
            }

            // Start a node for the title if it is valid.
            match parse_title(raw_title, source_path, source_contents, line_source_range) {
                Ok(title_source_range) => {
                    pending_node = Some(PendingNode {
                        title: source_contents[title_source_range.start..title_source_range.end]
                            .to_owned(),
                        source_start: line_start,
                        content_start: next_line_start,
                        title_source_range,
                    });
                }
                Err(error) => errors.push(error),
            }
        } else if !has_seen_title_marker
            && !reported_content_before_title
            && !line.trim().is_empty()
        {
            // Report only the first non-whitespace content outside a valid node.
            errors.push(Error::new(
                "This content is not in any node.",
                source_path,
                Some((
                    source_contents,
                    trim_source_range(source_contents, line_source_range),
                )),
                None,
            ));
            reported_content_before_title = true;
        }

        line_start = next_line_start;
    }

    // Finish the final node at the end of the wiki.
    if let Some(final_node) = pending_node
        && let Err(node_errors) = insert_node(
            &mut wiki,
            final_node,
            source_contents.len(),
            source_path,
            source_contents,
        )
    {
        errors.extend(node_errors);
    }

    // Return all node errors together, or score and return the parsed wiki.
    if errors.is_empty() {
        populate_depths(&mut wiki);
        Ok(wiki)
    } else {
        Err(errors)
    }
}

// Locate the title that follows a title marker, rejecting titles that are empty after surrounding
// whitespace is stripped, as well as titles that text links could not target because they would
// become filesystem links.
fn parse_title(
    raw_title: &str,
    source_path: Option<&Path>,
    source_contents: &str,
    line_source_range: SourceRange,
) -> Result<SourceRange, Error> {
    // Strip surrounding whitespace from the text after the marker, which ends the line.
    let title_source_range = trim_source_range(
        source_contents,
        SourceRange {
            start: line_source_range.end - raw_title.len(),
            end: line_source_range.end,
        },
    );
    let title = &source_contents[title_source_range.start..title_source_range.end];

    // Report an empty title at the whole line, since the title has no text of its own.
    if title.is_empty() {
        Err(Error::new(
            "This title is empty.",
            source_path,
            Some((source_contents, line_source_range)),
            None,
        ))
    } else if !title.starts_with(FILESYSTEM_LINK_PREFIX) {
        Ok(title_source_range)
    } else {
        Err(Error::new(
            &format!(
                "This title cannot start with {}.",
                FILESYSTEM_LINK_PREFIX.code_str(),
            ),
            source_path,
            Some((source_contents, title_source_range)),
            None,
        ))
    }
}

// Add a completed node after collecting all of its parsing errors.
fn insert_node(
    wiki: &mut Wiki,
    pending_node: PendingNode,
    source_end: usize,
    source_path: Option<&Path>,
    source_contents: &str,
) -> Result<(), Vec<Error>> {
    // Locate the trimmed node and its trimmed content in the original source.
    let PendingNode {
        title,
        source_start,
        content_start,
        title_source_range,
    } = pending_node;
    let source_range = trim_source_range(
        source_contents,
        SourceRange {
            start: source_start,
            end: source_end,
        },
    );
    let content_source_range = trim_source_range(
        source_contents,
        SourceRange {
            start: content_start,
            end: source_end,
        },
    );
    let (content, links, mut errors) =
        parse_content(source_path, source_contents, content_source_range);

    // Reject a title that has already been used.
    if wiki.text_nodes.contains_key(&title) {
        errors.push(Error::new(
            &format!("Duplicate title {}.", title.code_str()),
            source_path,
            Some((source_contents, title_source_range)),
            None,
        ));
    }

    // Insert only nodes that parsed without errors.
    if errors.is_empty() {
        wiki.text_nodes.insert(
            title.clone(),
            TextNode {
                title,
                content,
                links,
                depth: None,
                source_range,
                title_source_range,
            },
        );
        Ok(())
    } else {
        Err(errors)
    }
}

// Parse link occurrences and produce the normalized content stored on a text node.
fn parse_content(
    source_path: Option<&Path>,
    source_contents: &str,
    source_range: SourceRange,
) -> (String, Vec<Link>, Vec<Error>) {
    // Traverse the original content while retaining indices for copying and diagnostics.
    let original_content = &source_contents[source_range.start..source_range.end];
    let mut content = String::new();
    let mut copied_through = 0;
    let mut links = Vec::<Link>::new();
    let mut errors = Vec::<Error>::new();
    let mut link_start = None::<usize>;
    let mut link_has_line_break = false;
    let mut previous_was_backslash = false;

    for (index, character) in original_content.char_indices() {
        let is_escaped_delimiter = previous_was_backslash && matches!(character, '[' | ']');
        previous_was_backslash = character == '\\';
        if is_escaped_delimiter {
            continue;
        }

        // Locate the current character for any delimiter error.
        let character_source_range = SourceRange {
            start: source_range.start + index,
            end: source_range.start + index + character.len_utf8(),
        };

        // Report the first line break within each link.
        if character == '\n'
            && let Some(start) = link_start
            && !link_has_line_break
        {
            let link_source_range = SourceRange {
                start: source_range.start + start,
                end: source_range.start + index + character.len_utf8(),
            };
            errors.push(Error::new(
                "This link contains a line break.",
                source_path,
                Some((source_contents, link_source_range)),
                None,
            ));
            link_has_line_break = true;
        }

        // Interpret unescaped square brackets as link delimiters.
        match character {
            '[' if link_start.is_some() => errors.push(Error::new(
                "Unexpected opening link delimiter.",
                source_path,
                Some((source_contents, character_source_range)),
                None,
            )),
            '[' => {
                link_start = Some(index);
                link_has_line_break = false;
            }
            ']' if link_start.is_none() => {
                // Reject a closing delimiter without an opening delimiter [tag:missing_link_start].
                errors.push(Error::new(
                    "Unexpected closing link delimiter.",
                    source_path,
                    Some((source_contents, character_source_range)),
                    None,
                ));
            }
            ']' => {
                // The preceding arm rejected a missing link start [ref:missing_link_start].
                let start = link_start.take().expect("the link start was checked above");
                let inner_start = start + '['.len_utf8();
                let trimmed_target = original_content[inner_start..index].trim();
                let link_source_range = SourceRange {
                    start: source_range.start + start,
                    end: source_range.start + index + character.len_utf8(),
                };
                let formatted_target = match parse_link(
                    trimmed_target,
                    source_path,
                    source_contents,
                    link_source_range,
                ) {
                    Ok(link) => {
                        let formatted_target = format_link_target(trimmed_target, &link);
                        links.push(link);
                        formatted_target
                    }
                    Err(error) => {
                        errors.push(error);
                        trimmed_target.to_owned()
                    }
                };

                // Copy the prose before the link, then the link in its formatted form.
                content.push_str(&original_content[copied_through..inner_start]);
                content.push_str(&formatted_target);
                content.push(']');
                copied_through = index + character.len_utf8();
            }
            _ => {}
        }
    }

    // Reject an opening delimiter that has no closing delimiter.
    if let Some(start) = link_start {
        let link_source_range = SourceRange {
            start: source_range.start + start,
            end: source_range.start + start + '['.len_utf8(),
        };
        errors.push(Error::new(
            "Unclosed link.",
            source_path,
            Some((source_contents, link_source_range)),
            None,
        ));
    }

    // Retain the content following the final link, then normalize the finished content. Links
    // cannot contain line breaks, and each ends with a delimiter, so normalizing never changes one.
    content.push_str(&original_content[copied_through..]);
    (normalize_lines(&content), links, errors)
}

// Format the trimmed target of a parsed link. A text link's target is kept as written, while a
// filesystem link's path is written in its normalized form.
fn format_link_target(trimmed_target: &str, link: &Link) -> String {
    match link {
        Link::Text { .. } => trimmed_target.to_owned(),
        Link::File { path, .. } => render_link_path(path, false),
        Link::Directory { path, .. } => render_link_path(path, true),
    }
}

// Convert the contents of a closed delimiter pair into a typed link occurrence.
fn parse_link(
    target: &str,
    source_path: Option<&Path>,
    source_contents: &str,
    source_range: SourceRange,
) -> Result<Link, Error> {
    // Unescape delimiters before converting the target into its semantic link type. A filesystem
    // link starts with `/` and names a directory if it also ends with one.
    let target = unescape_link_delimiters(target);
    if target.starts_with(FILESYSTEM_LINK_PREFIX) {
        let is_directory = target.ends_with(DIRECTORY_LINK_SUFFIX);
        parse_filesystem_path(&target, source_path, source_contents, source_range).map(|path| {
            if is_directory {
                Link::Directory { path, source_range }
            } else {
                Link::File { path, source_range }
            }
        })
    } else {
        Ok(Link::Text {
            title: target,
            source_range,
        })
    }
}

// Parse a filesystem link path, attributing any problem to the link's source range.
fn parse_filesystem_path(
    path: &str,
    source_path: Option<&Path>,
    source_contents: &str,
    source_range: SourceRange,
) -> Result<PathBuf, Error> {
    normalize_filesystem_path(path).map_err(|message| {
        Error::new(
            &message,
            source_path,
            Some((source_contents, source_range)),
            None,
        )
    })
}

// Normalize a filesystem link path, which is relative to the wiki directory even if it starts with
// `/`, while keeping it inside the wiki's logical tree. Describe any problem with a message.
pub fn normalize_filesystem_path(path: &str) -> Result<PathBuf, String> {
    // Interpret the path relative to the wiki directory, even with the leading `/` of a filesystem
    // link. What remains may be empty, which denotes the wiki directory itself.
    let parsed_path = Path::new(path.trim_start_matches('/'));

    // Reject components that escape the logical wiki tree [tag:filesystem_path_components]. A root
    // or prefix makes the path absolute.
    if parsed_path
        .components()
        .any(|component| matches!(component, Component::RootDir | Component::Prefix(_)))
    {
        return Err(format!(
            "Path {} must be relative to the wiki directory.",
            parsed_path.code_path(),
        ));
    }

    // A parent component could lead outside the wiki directory.
    if parsed_path
        .components()
        .any(|component| component == Component::ParentDir)
    {
        return Err(format!(
            "Path {} must not contain {}.",
            parsed_path.code_path(),
            "..".code_str(),
        ));
    }

    // Normalize harmless current-directory components without resolving symlinks.
    Ok(parsed_path
        .components()
        .filter_map(|component| match component {
            Component::Normal(component) => Some(component),
            Component::CurDir => None,
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
                // Escaping components were rejected above [ref:filesystem_path_components].
                unreachable!("filesystem link path components were already validated")
            }
        })
        .collect())
}

// Write a normalized filesystem link path: `/` and the path's components, followed by `/` for a
// directory, with any link delimiters escaped. The wiki directory is written as `/`.
pub fn render_link_path(path: &Path, is_directory: bool) -> String {
    // Join the components with the separator that links use on every platform. Link paths come
    // from UTF-8 text.
    let components = path
        .components()
        .map(|component| {
            component
                .as_os_str()
                .to_str()
                .expect("link paths should come from UTF-8 text")
        })
        .collect::<Vec<_>>();
    let mut rendered = format!("{FILESYSTEM_LINK_PREFIX}{}", components.join("/"));

    // Mark a directory with a trailing separator, which the prefix already provides for the wiki
    // directory.
    if is_directory && !components.is_empty() {
        rendered.push_str(DIRECTORY_LINK_SUFFIX);
    }

    // Escape the finished text once, just before it returns to the source.
    escape_link_delimiters(&rendered)
}

// Write text in the wiki's canonical form, with Unix line endings and no whitespace at the end of a
// line.
fn normalize_lines(text: &str) -> String {
    text.lines()
        .map(str::trim_end)
        .collect::<Vec<_>>()
        .join("\n")
}

// Remove surrounding whitespace from a source range without losing its original coordinates.
fn trim_source_range(source_contents: &str, source_range: SourceRange) -> SourceRange {
    // Find the trimmed start relative to the original source.
    let source = &source_contents[source_range.start..source_range.end];
    let start_trimmed = source.trim_start();
    let start = source_range.start + source.len() - start_trimmed.len();

    // Find the trimmed end relative to the adjusted start.
    let trimmed = start_trimmed.trim_end();
    SourceRange {
        start,
        end: start + trimmed.len(),
    }
}

#[cfg(test)]
mod tests {
    use super::parse;
    use crate::{
        assert_fails,
        error::Error,
        wiki::{Link, Wiki},
    };
    use std::{
        fmt::Write,
        path::{Path, PathBuf},
    };

    // Parse test sources using a stable path for diagnostic assertions.
    fn parse_test(source_contents: &str) -> Result<Wiki, Vec<Error>> {
        parse(Some(Path::new("test.mull")), source_contents)
    }

    // Describe link targets without coupling semantic assertions to their source ranges.
    fn link_targets(links: &[Link]) -> Vec<String> {
        links
            .iter()
            .map(|link| match link {
                Link::Text { title, .. } => format!("text:{title}"),
                Link::File { path, .. } => format!("file:{}", path.display()),
                Link::Directory { path, .. } => format!("dir:{}", path.display()),
            })
            .collect()
    }

    // Parse titles and multiline content while retaining exact source ranges.
    #[test]
    fn nodes() {
        let source =
            "  \n#   Home  \n\n Check out the [Greeting]. \n\n# Greeting\n Hello,\nworld! \n";
        let wiki = parse_test(source).unwrap();

        assert_eq!(wiki.text_nodes.len(), 2);
        assert_eq!(wiki.text_nodes["Home"].title, "Home");
        assert_eq!(wiki.text_nodes["Home"].content, "Check out the [Greeting].");
        assert_eq!(
            link_targets(&wiki.text_nodes["Home"].links),
            vec!["text:Greeting"],
        );
        assert_eq!(wiki.text_nodes["Greeting"].content, "Hello,\nworld!");
        assert_eq!(wiki.text_nodes["Home"].title_source_range.start, 7);
        assert_eq!(wiki.text_nodes["Home"].title_source_range.end, 11);
        assert_eq!(wiki.text_nodes["Home"].source_range.start, 3);
        assert_eq!(wiki.text_nodes["Home"].source_range.end, 41);
        let Link::Text { source_range, .. } = &wiki.text_nodes["Home"].links[0] else {
            panic!("the parsed link should be a text link");
        };
        assert_eq!(&source[source_range.start..source_range.end], "[Greeting]");
    }

    // Preserve duplicate links as distinct source occurrences while normalizing their text.
    #[test]
    fn links() {
        let wiki = parse_test(concat!(
            "# Home\nSee [Greeting], [ About ], and [Greeting].",
            "\n# About\n# Greeting",
        ))
        .unwrap();

        assert_eq!(
            link_targets(&wiki.text_nodes["Home"].links),
            vec!["text:Greeting", "text:About", "text:Greeting"],
        );
        assert_eq!(
            wiki.text_nodes["Home"].content,
            "See [Greeting], [About], and [Greeting].",
        );
    }

    // Keep source ranges on UTF-8 boundaries when titles and links contain multibyte characters.
    #[test]
    fn unicode_source_ranges() {
        let source = "# Home\nSee [Grüße].\n# Grüße";
        let wiki = parse_test(source).unwrap();
        let Link::Text { source_range, .. } = &wiki.text_nodes["Home"].links[0] else {
            panic!("the parsed link should be a text link");
        };

        assert_eq!(&source[source_range.start..source_range.end], "[Grüße]");
        assert_eq!(
            &source[wiki.text_nodes["Grüße"].title_source_range.start
                ..wiki.text_nodes["Grüße"].title_source_range.end],
            "Grüße",
        );
    }

    // Treat escaped square brackets as literal link-title characters.
    #[test]
    fn escaped_link_delimiters() {
        let wiki = parse_test(
            r"# Home
See \[Ignored\], [One\]Two], [\[Three], [Four], and \[also ignored\].
# Four
# One]Two
# [Three",
        )
        .unwrap();

        assert_eq!(
            link_targets(&wiki.text_nodes["Home"].links),
            vec!["text:One]Two", "text:[Three", "text:Four"],
        );
    }

    // Parse file and directory links separately from text links.
    #[test]
    fn filesystem_links() {
        let wiki = parse_test(
            "# Home\nSee [/notes.txt], [/images/], [/images/./raw/], [/], [//docs/], and \
                [/ spaced.txt].",
        )
        .unwrap();

        assert_eq!(
            link_targets(&wiki.text_nodes["Home"].links),
            vec![
                format!("file:{}", PathBuf::from("notes.txt").display()),
                format!("dir:{}", PathBuf::from("images").display()),
                format!("dir:{}", PathBuf::from("images").join("raw").display()),
                "dir:".to_owned(),
                format!("dir:{}", PathBuf::from("docs").display()),
                format!("file:{}", PathBuf::from(" spaced.txt").display()),
            ],
        );
    }

    // Format links by trimming their targets and normalizing filesystem paths, writing a directory
    // with a trailing `/` and the wiki directory as `/`.
    #[test]
    fn formatted_links() {
        let wiki = parse_test(
            "# Home\n[ Home ] [ /a//b/./c\\[1\\].txt ] [/images/] [/images/./raw//] [/] [/./] \
                [///]",
        )
        .unwrap();

        assert_eq!(
            wiki.text_nodes["Home"].content,
            "[Home] [/a/b/c\\[1\\].txt] [/images/] [/images/raw/] [/] [/] [/]",
        );
    }

    // Remove whitespace at the end of each line, including after a link and on blank lines.
    #[test]
    fn trailing_whitespace() {
        let wiki =
            parse_test("# Home\r\nFirst  \t\r\n   \nSee [Home]  \nand [Home] later.\t\nLast")
                .unwrap();

        assert_eq!(
            wiki.text_nodes["Home"].content,
            "First\n\nSee [Home]\nand [Home] later.\nLast",
        );
    }

    // Reject filesystem links whose paths contain parent components.
    #[test]
    fn invalid_filesystem_link_paths() {
        let result = parse_test("# Home\n[/../notes.txt] [/notes/../notes.txt]");

        assert_fails!(result.clone(), "Path `../notes.txt` must not contain `..`.");
        assert_fails!(result, "Path `notes/../notes.txt` must not contain `..`.");
    }

    // Reject opening link delimiters that are not closed.
    #[test]
    fn unclosed_link() {
        assert_fails!(parse_test("# Home\nSee [Greeting."), "Unclosed link.");
    }

    // Reject links that span multiple lines.
    #[test]
    fn link_with_line_break() {
        assert_fails!(
            parse_test("# Home\nSee [Greeting\ncontinued]."),
            "This link contains a line break.",
        );
    }

    // Reject unescaped opening delimiters inside links.
    #[test]
    fn unexpected_opening_delimiter() {
        assert_fails!(
            parse_test("# Home\nSee [nested[Greeting]."),
            "Unexpected opening link delimiter.",
        );
    }

    // Reject unescaped closing delimiters outside links.
    #[test]
    fn unexpected_closing_delimiter() {
        let errors = parse_test("# Home\nSee Greeting].").unwrap_err();

        assert!(
            errors[0]
                .to_string()
                .contains("Unexpected closing link delimiter"),
        );
        assert!(errors[0].to_string().contains("2 \u{2502} See Greeting]."));
    }

    // Treat non-title hash prefixes as ordinary content.
    #[test]
    fn non_title_hashes() {
        let wiki = parse_test("# Home\n\n## Subtitle\n#not a title").unwrap();

        assert_eq!(wiki.text_nodes["Home"].content, "## Subtitle\n#not a title");
    }

    // Accept empty and whitespace-only wikis.
    #[test]
    fn empty_wiki() {
        assert!(parse_test(" \n\t\n").unwrap().text_nodes.is_empty());
    }

    // Accept empty node content.
    #[test]
    fn empty_content() {
        assert!(
            parse_test("# Empty").unwrap().text_nodes["Empty"]
                .content
                .is_empty(),
        );
    }

    // Parse Windows line endings without retaining carriage returns.
    #[test]
    fn windows_line_endings() {
        let wiki = parse_test("# Greeting\r\n\r\nHello, world!\r\n").unwrap();

        assert_eq!(wiki.text_nodes["Greeting"].content, "Hello, world!");
    }

    // Reject non-whitespace content before the first title.
    #[test]
    fn content_before_title() {
        assert_fails!(
            parse_test("Introduction\n# Home"),
            "This content is not in any node.",
        );
    }

    // Reject titles that are empty after whitespace is stripped.
    #[test]
    fn empty_title() {
        let errors = parse_test("#   \nContent").unwrap_err();

        assert_eq!(errors.len(), 1);
        assert!(errors[0].to_string().contains("This title is empty."));
    }

    // Reject titles that text links would interpret as filesystem links.
    #[test]
    fn filesystem_link_titles() {
        let errors = parse_test("# Home\n\n# /notes.txt\n\n# /\n\n# notes: /draft").unwrap_err();

        assert_eq!(errors.len(), 2);
        for error in &errors {
            assert!(
                error
                    .to_string()
                    .contains("This title cannot start with `/`."),
            );
        }
    }

    // Do not reinterpret content after an invalid title as content before the first title.
    #[test]
    fn content_after_empty_title() {
        let errors = parse_test("# Home\n\nfoo\n\n#\n\nbar").unwrap_err();

        assert_eq!(errors.len(), 1);
        assert!(errors[0].to_string().contains("This title is empty."));
    }

    // Recognize a bare title marker so it can be reported as an empty title.
    #[test]
    fn bare_empty_title() {
        let errors = parse_test("#").unwrap_err();

        assert_eq!(errors.len(), 1);
        assert!(errors[0].to_string().contains("This title is empty."));
        assert!(errors[0].to_string().contains("1 │ #"));
    }

    // Report only the first occurrence of content before a valid title.
    #[test]
    fn repeated_content_before_title() {
        let errors = parse_test("First\nSecond\n# Home").unwrap_err();

        assert_eq!(errors.len(), 1);
        assert!(
            errors[0]
                .to_string()
                .contains("This content is not in any node."),
        );
    }

    // Reject duplicate titles and identify the later declaration.
    #[test]
    fn duplicate_title() {
        let errors = parse_test("# Home\nFirst\n# Home\nSecond").unwrap_err();

        assert_eq!(errors.len(), 1);
        assert!(errors[0].to_string().contains("Duplicate title `Home`."));
        assert!(errors[0].to_string().contains("3 \u{2502} # Home"));
    }

    // Report errors from every invalid node in source order.
    #[test]
    fn multiple_node_errors() {
        let errors = parse_test("# First\nUnexpected].\n# Second\nUnclosed [link.").unwrap_err();

        assert_eq!(errors.len(), 2);
        assert!(
            errors[0]
                .to_string()
                .contains("Unexpected closing link delimiter"),
        );
        assert!(errors[1].to_string().contains("Unclosed link"));
    }

    // Report every delimiter error within one node.
    #[test]
    fn multiple_errors_in_node() {
        let errors = parse_test("# Home\nUnexpected] and [nested[link.").unwrap_err();

        assert_eq!(errors.len(), 3);
        assert!(
            errors[0]
                .to_string()
                .contains("Unexpected closing link delimiter"),
        );
        assert!(
            errors[1]
                .to_string()
                .contains("Unexpected opening link delimiter"),
        );
        assert!(errors[2].to_string().contains("Unclosed link"));
    }

    // Report structural and node errors together in source order.
    #[test]
    fn multiple_error_types() {
        let errors = parse_test(concat!(
            "Introduction\n",
            "#   \n",
            "Content\n",
            "# First\n",
            "Unexpected].\n",
            "# Second\n",
            "Unclosed [link.",
        ))
        .unwrap_err();

        assert_eq!(errors.len(), 4);
        assert!(
            errors[0]
                .to_string()
                .contains("This content is not in any node"),
        );
        assert!(errors[1].to_string().contains("This title is empty"));
        assert!(
            errors[2]
                .to_string()
                .contains("Unexpected closing link delimiter"),
        );
        assert!(errors[3].to_string().contains("Unclosed link"));
    }
}