lex-core 0.15.0

Parser library for the lex format
Documentation
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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
//! Document link extraction for LSP support
//!
//! This module provides APIs for extracting clickable links from Lex documents,
//! enabling the LSP "document links" feature that makes URLs and file references
//! clickable in editors.
//!
//! ## Problem
//!
//! The LSP document links feature needs to find all clickable links:
//! - URLs in text (`[https://example.com]`)
//! - File references (`[./file.txt]`)
//! - Verbatim block `src` parameters (images, includes)
//!
//! While `ReferenceType::Url` and `ReferenceType::File` exist, there's no API to
//! extract all links from a document.
//!
//! ## Solution
//!
//! This module provides:
//! - `DocumentLink` struct representing a link with its location and type
//! - `find_all_links()` methods on Document and Session
//! - `src_parameter()` method on Verbatim to access src parameters
//!
//! ## Link Types
//!
//! 1. **URL links**: `[https://example.com]` - HTTP/HTTPS URLs
//! 2. **File links**: `[./file.txt]`, `[../path/to/file.md]` - File references
//! 3. **Verbatim src**: `:: image src=./image.png ::` - External resource references

use super::anchoring::{ReferenceAnchor, ReferenceLine};
use super::elements::Verbatim;
use super::inline_positions::{walk_text_content_positions, InlinePositionVisitor};
use super::range::{Position, Range};
use super::text_content::TextContent;
use super::{Document, Session};
use crate::lex::inlines::{AnchorDirection, ReferenceInline, ReferenceType, WordAnchor};
use std::fmt;

/// Represents a document link with its location and type
#[derive(Debug, Clone, PartialEq)]
pub struct DocumentLink {
    pub range: Range,
    pub target: String,
    pub link_type: LinkType,
}

impl DocumentLink {
    pub fn new(range: Range, target: String, link_type: LinkType) -> Self {
        Self {
            range,
            target,
            link_type,
        }
    }
}

impl fmt::Display for DocumentLink {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{:?} link: {} at {}",
            self.link_type, self.target, self.range.start
        )
    }
}

/// Type of document link
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinkType {
    /// HTTP/HTTPS URL
    Url,
    /// File reference (relative or absolute path)
    File,
    /// Verbatim block src parameter
    VerbatimSrc,
}

impl Verbatim {
    /// Get the src parameter value if present
    ///
    /// The src parameter is commonly used for:
    /// - Image sources: `:: image src=./diagram.png ::`
    /// - File includes: `:: include src=./code.rs ::`
    /// - External resources: `:: data src=./data.csv ::`
    ///
    /// # Returns
    /// The value of the `src` parameter, or None if not present
    ///
    /// # Example
    /// ```rust,ignore
    /// if let Some(src) = verbatim.src_parameter() {
    ///     // Make src clickable in editor
    ///     println!("Link to: {}", src);
    /// }
    /// ```
    pub fn src_parameter(&self) -> Option<&str> {
        self.closing_data
            .parameters
            .iter()
            .find(|p| p.key == "src")
            .map(|p| p.value.as_str())
    }
}

impl Session {
    /// Find all links at any depth in this session
    ///
    /// This searches recursively through all content to find:
    /// - URL references: `[https://example.com]`
    /// - File references: `[./path/to/file.txt]`
    /// - Verbatim src parameters: `src=./image.png`
    ///
    /// # Returns
    /// Vector of all links found in this session and its descendants
    ///
    /// # Example
    /// ```rust,ignore
    /// let links = session.find_all_links();
    /// for link in links {
    ///     println!("Found {} link: {}", link.link_type, link.target);
    /// }
    /// ```
    pub fn find_all_links(&self) -> Vec<DocumentLink> {
        use super::elements::content_item::ContentItem;
        use super::traits::AstNode;

        let mut links = Vec::new();

        // Links in this session's title and every nested session's title.
        //
        // `Document::find_all_links` invokes us on the implicit root session
        // (whose title is empty), so without the recursive sweep below we
        // would silently drop every URL/File reference that appears in a
        // section heading — `1. See [./handlers.lex] for details` and
        // similar — even though paragraph-body refs were correctly found.
        collect_text_content_links(&self.title, &mut links);
        for nested in self.iter_sessions_recursive() {
            collect_text_content_links(&nested.title, &mut links);
        }

        // Paragraphs (recursively into nested sessions).
        for paragraph in self.iter_paragraphs_recursive() {
            for line_item in &paragraph.lines {
                if let ContentItem::TextLine(line) = line_item {
                    collect_text_content_links(&line.content, &mut links);
                }
            }
        }

        // Verbatim `src` parameters — these aren't bracketed inline references,
        // so the verbatim's range stays as-is.
        for (item, _depth) in self.iter_all_nodes_with_depth() {
            if let ContentItem::VerbatimBlock(verbatim) = item {
                if let Some(src) = verbatim.src_parameter() {
                    let link = DocumentLink::new(
                        verbatim.range().clone(),
                        src.to_string(),
                        LinkType::VerbatimSrc,
                    );
                    links.push(link);
                }
            }
        }

        links
    }
}

impl Document {
    /// Find all links in the entire document
    ///
    /// This searches the entire document tree to find all clickable links:
    /// - URL references in text
    /// - File references in text
    /// - Verbatim block src parameters
    ///
    /// # Returns
    /// Vector of all links found in the document
    ///
    /// # Example
    /// ```rust,ignore
    /// let doc = parse_document(source)?;
    /// let links = doc.find_all_links();
    /// for link in links {
    ///     // Make link clickable in LSP
    ///     send_document_link(link.range, link.target);
    /// }
    /// ```
    pub fn find_all_links(&self) -> Vec<DocumentLink> {
        let mut links = Vec::new();
        if let Some(title) = &self.title {
            collect_text_content_links(&title.content, &mut links);
        }
        links.extend(self.root.find_all_links());

        // Reference lines (whole-element anchors and self-links) live outside
        // the structural tree — they are removed from the line stream before
        // parsing (see `crate::lex::anchoring`) and collected on the document.
        // Each becomes a `DocumentLink` whose range is the *anchored span*
        // (the head line for a whole-element anchor, the reference's own text
        // for a self-link), so editors underline/navigate the anchored text
        // rather than the bracketed reference.
        for ref_line in self.reference_lines() {
            collect_reference_line_link(ref_line, &mut links);
        }

        links
    }
}

/// Emit a [`DocumentLink`] for a reference line (§2.3.2). Only link-like Url/File
/// reference types become document links — Session/General reference types have
/// no navigable Url/File target today, mirroring the inline collector which only
/// surfaces Url/File. Marker-style types never reach here (they are not reference
/// lines).
///
/// - [`ReferenceAnchor::WholeElement`]: range = the anchored head line
///   (`anchor_range`); target = the reference's Url/File.
/// - [`ReferenceAnchor::SelfLink`]: range = the reference's own bracketed text
///   (`reference_range`); target = the reference's Url/File.
fn collect_reference_line_link(ref_line: &ReferenceLine, out: &mut Vec<DocumentLink>) {
    let (target, link_type) = match &ref_line.reference.reference_type {
        ReferenceType::Url { target } => (target.clone(), LinkType::Url),
        ReferenceType::File { target } => (target.clone(), LinkType::File),
        _ => return,
    };

    // `anchor_range` / `reference_range` were produced via
    // `SourceLocation::byte_range_to_ast_range`, whose columns are *byte*
    // offsets within the line. The inline word-anchor path (and LSP's default
    // `positionEncoding`) uses *UTF-16* columns. Normalize the reference-line
    // ranges to UTF-16: keep the byte span and start column (the start sits at
    // a known boundary — the anchor head or the `[`) and recompute the end
    // column from the anchored text's UTF-16 width. For non-ASCII anchor or
    // reference text this is the only correct mapping; for ASCII it is a no-op.
    let (base, anchored_utf16) = match &ref_line.anchor {
        ReferenceAnchor::WholeElement {
            anchor_range,
            anchor_text,
            ..
        } => (anchor_range, utf16_width(anchor_text)),
        // Self-link covers the reference's own `[bracketed]` text:
        // `[` + raw + `]`.
        ReferenceAnchor::SelfLink => (
            &ref_line.reference_range,
            utf16_width("[") + utf16_width(&ref_line.reference.raw) + utf16_width("]"),
        ),
    };

    let range = Range::new(
        base.span.clone(),
        base.start,
        Position::new(base.start.line, base.start.column + anchored_utf16),
    );

    out.push(DocumentLink::new(range, target, link_type));
}

/// Walks `text`'s inline tree and pushes a [`DocumentLink`] for each URL and
/// File reference, with a range covering exactly the `[bracketed]` reference.
///
/// LSP `textDocument/documentLink` ranges drive the clickable + visually
/// underlined area in editors. Using the containing paragraph or title range
/// would underline the whole element — which is exactly the bug this function
/// is replacing.
///
/// The cursor work is delegated to the shared
/// [`crate::lex::ast::inline_positions::walk_text_content_positions`] visitor;
/// this function only contributes the link-shaping logic in `LinkCollector`.
fn collect_text_content_links(text: &TextContent, out: &mut Vec<DocumentLink>) {
    let mut collector = LinkCollector::new(out);
    walk_text_content_positions(text, &mut collector);
    // A `Following`-anchored reference defers its link until the next `Plain`
    // node arrives. If the walk ends with one still pending (the reference was
    // the last node, or only non-`Plain` nodes followed it), flush it now so
    // the link is not lost — it falls back to the bracket range.
    collector.flush();
}

/// Visitor that emits a [`DocumentLink`] per URL/File reference. All other
/// inline node variants are intentionally ignored (footnote/citation/session/
/// annotation/TK refs do not become document links).
///
/// ## Range widening for inline word anchors (§2.3.1)
///
/// An *inline* URL/File reference (one that shares its line with other text)
/// anchors a single word — the word immediately *preceding* it (default) or,
/// when it is the first token on the line, the word immediately *following* it.
/// The anchor-resolution pass records that word (and direction) on
/// `ReferenceInline::word_anchor`. To make the link underline/navigate the
/// *word* rather than the `[bracketed]` text, the collector computes the word's
/// source range from the adjacent `Plain` node:
///
/// - `Preceding`: the word lies at the end of the most-recently-visited `Plain`
///   node (`last_plain`), which is emitted before the reference. Computed
///   immediately.
/// - `Following`: the word lies at the start of the *next* `Plain` node, which
///   is visited after the reference. The reference is recorded as `pending` and
///   resolved when that `Plain` arrives.
///
/// The word stored on `WordAnchor` is *cleaned* (surrounding punctuation
/// trimmed) by the resolver; we locate that cleaned substring inside the plain
/// text so the range covers exactly the word, not its surrounding punctuation.
/// If the word cannot be located in the adjacent plain text (e.g. it was
/// flattened across a formatting span, or the plain node was escaped in a way
/// that shifts byte math), the link falls back to the `[bracketed]` range.
struct LinkCollector<'a> {
    out: &'a mut Vec<DocumentLink>,
    /// The most recently visited `Plain` node's range + text, used to resolve a
    /// `Preceding` word anchor (the word at the end of the text before a
    /// reference).
    last_plain: Option<PlainSpan>,
    /// A reference whose `Following` word anchor is waiting for the next `Plain`
    /// node to be visited so its start word can be located.
    pending_following: Option<PendingFollowing>,
}

/// A `Plain` inline node captured for word-anchor range computation: the node's
/// source range and the (unescaped) text the range covers.
struct PlainSpan {
    range: Range,
    text: String,
}

/// A reference awaiting the next `Plain` node to resolve a `Following` anchor.
struct PendingFollowing {
    word: String,
    target: String,
    link_type: LinkType,
    /// The bracket-bounded fallback range, used if the word can't be located.
    bracket_range: Range,
}

impl<'a> LinkCollector<'a> {
    fn new(out: &'a mut Vec<DocumentLink>) -> Self {
        Self {
            out,
            last_plain: None,
            pending_following: None,
        }
    }

    /// Bracket-bounded range of a reference: open marker start → close marker end.
    fn bracket_range(open_marker: &Range, close_marker: &Range) -> Range {
        Range::new(
            open_marker.span.start..close_marker.span.end,
            open_marker.start,
            close_marker.end,
        )
    }

    fn push(&mut self, range: Range, target: String, link_type: LinkType) {
        self.out.push(DocumentLink::new(range, target, link_type));
    }

    /// Emit any reference still waiting on a following `Plain` node, falling back
    /// to its bracket range (no following plain text was found to anchor in).
    ///
    /// Called at the end of the walk and whenever a *new* `Following` anchor
    /// arrives while one is already pending — without this the earlier pending
    /// link would be silently overwritten and lost.
    fn flush(&mut self) {
        if let Some(pending) = self.pending_following.take() {
            self.push(pending.bracket_range, pending.target, pending.link_type);
        }
    }
}

impl<'a> InlinePositionVisitor for LinkCollector<'a> {
    fn visit_plain(&mut self, range: &Range, text: &str) {
        // Resolve any reference waiting on a following word first — this plain
        // node is the text that follows it.
        if let Some(pending) = self.pending_following.take() {
            let plain = PlainSpan {
                range: range.clone(),
                text: text.to_string(),
            };
            let resolved = locate_word_range(&plain, &pending.word, WordEnd::Start)
                .unwrap_or(pending.bracket_range);
            self.push(resolved, pending.target, pending.link_type);
        }
        self.last_plain = Some(PlainSpan {
            range: range.clone(),
            text: text.to_string(),
        });
    }

    fn visit_reference(
        &mut self,
        open_marker: &Range,
        _content: &Range,
        close_marker: &Range,
        data: &ReferenceInline,
    ) {
        let (target, link_type) = match &data.reference_type {
            ReferenceType::Url { target } => (target.clone(), LinkType::Url),
            ReferenceType::File { target } => (target.clone(), LinkType::File),
            _ => return,
        };
        let bracket_range = Self::bracket_range(open_marker, close_marker);

        match &data.word_anchor {
            // Inline reference anchoring the preceding word: resolve against the
            // last plain node we visited.
            Some(WordAnchor {
                word,
                direction: AnchorDirection::Preceding,
            }) => {
                let range = self
                    .last_plain
                    .as_ref()
                    .and_then(|plain| locate_word_range(plain, word, WordEnd::End))
                    .unwrap_or(bracket_range);
                self.push(range, target, link_type);
            }
            // Inline reference anchoring the following word: defer until the
            // next plain node is visited.
            Some(WordAnchor {
                word,
                direction: AnchorDirection::Following,
            }) => {
                // Flush any earlier pending `Following` link first — two
                // `Following` references back-to-back (before the next `Plain`
                // node) would otherwise clobber the first.
                self.flush();
                self.pending_following = Some(PendingFollowing {
                    word: word.clone(),
                    target,
                    link_type,
                    bracket_range,
                });
            }
            // No word anchor (reference lines are handled separately; a lone
            // marker reference has no word). Fall back to the bracket range.
            None => {
                self.push(bracket_range, target, link_type);
            }
        }
    }
}

/// Which end of the plain text the anchored word sits at.
#[derive(Clone, Copy)]
enum WordEnd {
    /// The word is the *last* whitespace-delimited token (preceding anchor).
    End,
    /// The word is the *first* whitespace-delimited token (following anchor).
    Start,
}

/// Compute the source [`Range`] of `word` within `plain`, looking at the
/// appropriate end of the plain text.
///
/// `word` is the *cleaned* anchor word (surrounding punctuation already trimmed
/// by the resolver). We find the matching whitespace-delimited token at the
/// requested end, then locate the cleaned word inside it so trailing/leading
/// punctuation (`website,` → `website`) is excluded from the range.
///
/// Returns `None` (caller falls back to the bracket range) when the word can't
/// be located — e.g. the anchor was flattened across a formatting span, so the
/// adjacent plain node doesn't literally contain it.
fn locate_word_range(plain: &PlainSpan, word: &str, end: WordEnd) -> Option<Range> {
    let text = &plain.text;
    // `text` is the *unescaped* plain text, but `plain.range.span` covers the
    // *raw* source. When the run contains escapes (`\X`), the raw span is longer
    // than the unescaped text, so byte offsets computed against `text` no longer
    // map onto the raw span. Bail out (caller falls back to the bracket range)
    // rather than emit a misplaced underline.
    if plain.range.span.len() != text.len() {
        return None;
    }
    // The token at the requested end, with its byte offset within `text`.
    let token = match end {
        WordEnd::End => last_token(text),
        WordEnd::Start => first_token(text),
    }?;
    // Locate the cleaned word inside the token (punctuation trimmed). The token
    // contains the word as a contiguous substring (cleaning only strips leading
    // and trailing chars), so a single `find` recovers its offset.
    let word_in_token = token.text.find(word)?;
    let word_start = token.offset + word_in_token;
    let word_end = word_start + word.len();

    // Map byte offsets within the plain text to source coordinates. The plain
    // node is single-line (inline parsing is per-line), so the source byte span
    // is the plain node's span offset by these byte positions, and columns
    // advance from the plain node's start column. This holds when the plain
    // text's bytes line up 1:1 with the source (the common, escape-free case);
    // if an escape shifted the bytes, `find` would still give a plausible
    // offset but the column math could drift — acceptable since the worst case
    // is a slightly-off underline, and callers can fall back to brackets.
    let base = &plain.range;
    let span = (base.span.start + word_start)..(base.span.start + word_end);
    let start_col = base.start.column + utf16_width(&text[..word_start]);
    let end_col = base.start.column + utf16_width(&text[..word_end]);
    Some(Range::new(
        span,
        Position::new(base.start.line, start_col),
        Position::new(base.start.line, end_col),
    ))
}

/// A whitespace-delimited token with its byte offset within the parent text.
struct Token<'a> {
    text: &'a str,
    offset: usize,
}

/// The last whitespace-delimited token of `text`, with its byte offset.
fn last_token(text: &str) -> Option<Token<'_>> {
    let tok = text.split_whitespace().next_back()?;
    // `split_whitespace` doesn't give offsets; the last token ends at the last
    // non-whitespace byte, so find it from the trimmed end.
    let trimmed_end = text.trim_end().len();
    let offset = trimmed_end - tok.len();
    Some(Token { text: tok, offset })
}

/// The first whitespace-delimited token of `text`, with its byte offset.
fn first_token(text: &str) -> Option<Token<'_>> {
    let tok = text.split_whitespace().next()?;
    let offset = text.len() - text.trim_start().len();
    Some(Token { text: tok, offset })
}

/// UTF-16 code-unit width of `s` — matches the column units used by the inline
/// position walker (LSP default `positionEncoding`).
fn utf16_width(s: &str) -> usize {
    s.chars().map(char::len_utf16).sum()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lex::parsing::parse_document;

    #[test]
    fn test_url_link_extraction() {
        let source = "Check out [https://example.com] for more info.\n\n";
        let doc = parse_document(source).unwrap();

        let links = doc.find_all_links();

        assert_eq!(links.len(), 1);
        assert_eq!(links[0].link_type, LinkType::Url);
        assert_eq!(links[0].target, "https://example.com");
    }

    #[test]
    fn test_file_link_extraction() {
        let source = "See [./README.md] for details.\n\n";
        let doc = parse_document(source).unwrap();

        let links = doc.find_all_links();

        assert_eq!(links.len(), 1);
        assert_eq!(links[0].link_type, LinkType::File);
        assert_eq!(links[0].target, "./README.md");
    }

    #[test]
    fn test_multiple_links() {
        let source = "Visit [https://example.com] and check [./docs.md].\n\n";
        let doc = parse_document(source).unwrap();

        let links = doc.find_all_links();

        assert_eq!(links.len(), 2);
        assert!(links.iter().any(|l| l.link_type == LinkType::Url));
        assert!(links.iter().any(|l| l.link_type == LinkType::File));
    }

    #[test]
    fn test_verbatim_src_parameter() {
        let source =
            "Sunset Photo:\n    As the sun sets over the ocean.\n:: image src=./diagram.png ::\n\n";
        let doc = parse_document(source).unwrap();

        let links = doc.find_all_links();

        // Find verbatim src link
        let src_links: Vec<_> = links
            .iter()
            .filter(|l| l.link_type == LinkType::VerbatimSrc)
            .collect();
        assert_eq!(
            src_links.len(),
            1,
            "Expected 1 verbatim src link, found {}. All links: {:?}",
            src_links.len(),
            links
        );
        assert_eq!(src_links[0].target, "./diagram.png");
    }

    #[test]
    fn test_verbatim_src_parameter_method() {
        use super::super::elements::{Data, Label, Parameter};

        let verbatim = Verbatim::with_subject(
            "Test".to_string(),
            Data::new(
                Label::new("image".to_string()),
                vec![Parameter::new("src".to_string(), "./test.png".to_string())],
            ),
        );

        assert_eq!(verbatim.src_parameter(), Some("./test.png"));

        // Test verbatim without src parameter
        let verbatim_no_src = Verbatim::with_subject(
            "Test".to_string(),
            Data::new(Label::new("code".to_string()), vec![]),
        );

        assert_eq!(verbatim_no_src.src_parameter(), None);
    }

    #[test]
    fn test_no_links() {
        let source = "Just plain text with no links.\n\n";
        let doc = parse_document(source).unwrap();

        let links = doc.find_all_links();

        assert_eq!(links.len(), 0);
    }

    #[test]
    fn test_footnote_not_a_link() {
        let source = "Text with footnote [42].\n\n";
        let doc = parse_document(source).unwrap();

        let links = doc.find_all_links();

        // Footnote references are not clickable links
        assert_eq!(links.len(), 0);
    }

    #[test]
    fn test_nested_session_links() {
        let source = "Outer Session\n\n    Inner session with [https://example.com].\n\n";
        let doc = parse_document(source).unwrap();

        let links = doc.find_all_links();

        // Should find link in nested session
        assert_eq!(links.len(), 1);
        assert_eq!(links[0].target, "https://example.com");
    }

    // -----------------------------------------------------------------------
    // Range-precision tests (inline word anchors, §2.3.1)
    //
    // The LSP `textDocument/documentLink` response uses each link's `range`
    // to decide what is clickable and what gets the link decoration in the
    // editor. Editors (notably VSCode) render the entire range as an
    // underlined link.
    //
    // An *inline* reference (one that shares its line with other text) anchors
    // a single word — the word immediately *preceding* it by default. So the
    // link range covers that anchored word, not the `[bracketed]` reference and
    // not the surrounding paragraph. This is the PR-C widening: editors now
    // underline/navigate the word, matching how the reference renders.
    // -----------------------------------------------------------------------

    use super::super::range::Position;

    #[test]
    fn test_url_link_range_covers_preceding_word_in_paragraph() {
        // "Check out [https://example.com] for more info."
        //  0123456789^
        // The reference shares its line with text, so it anchors the preceding
        // word "out" (bytes 6..9), not the brackets.
        let source = "Check out [https://example.com] for more info.\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(links.len(), 1);
        let link = &links[0];
        assert_eq!(link.target, "https://example.com");

        let captured = &source[link.range.span.clone()];
        assert_eq!(
            link.range.span,
            6..9,
            "inline link range must cover the anchored word 'out'. Captured: {captured:?}"
        );
        assert_eq!(captured, "out");
        assert_eq!(link.range.start, Position::new(0, 6));
        assert_eq!(link.range.end, Position::new(0, 9));
    }

    #[test]
    fn test_file_link_range_covers_preceding_word_in_paragraph() {
        // "See [./README.md] for details." → anchors the preceding word "See".
        let source = "See [./README.md] for details.\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(links.len(), 1);
        let link = &links[0];
        assert_eq!(link.target, "./README.md");

        let captured = &source[link.range.span.clone()];
        assert_eq!(
            link.range.span,
            0..3,
            "inline link range must cover the anchored word 'See'. Captured: {captured:?}"
        );
        assert_eq!(captured, "See");
        assert_eq!(link.range.start, Position::new(0, 0));
        assert_eq!(link.range.end, Position::new(0, 3));
    }

    #[test]
    fn test_following_word_anchor_range() {
        // First-on-line reference anchors the *following* word "is".
        // "[https://lex.ing] is the home page."
        let source = "[https://lex.ing] is the home page.\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(links.len(), 1);
        let link = &links[0];
        assert_eq!(link.target, "https://lex.ing");

        let captured = &source[link.range.span.clone()];
        assert_eq!(captured, "is", "following-anchor link must cover 'is'");
        let is_start = source.find("is").unwrap();
        assert_eq!(link.range.span, is_start..is_start + 2);
    }

    #[test]
    fn test_word_anchor_excludes_trailing_punctuation() {
        // The preceding token is "website," but the anchor word is "website"
        // (punctuation trimmed), so the range must exclude the comma.
        let source = "the project website, [https://x.example] is fast.\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(links.len(), 1);
        let captured = &source[links[0].range.span.clone()];
        assert_eq!(captured, "website", "range must exclude the trailing comma");
    }

    #[test]
    fn test_abutting_word_anchor_range() {
        // "Hello[./file.txt] World" → abutting preceding word "Hello".
        let source = "Hello[./file.txt] World\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(links.len(), 1);
        let captured = &source[links[0].range.span.clone()];
        assert_eq!(captured, "Hello");
    }

    #[test]
    fn test_multiple_links_anchor_distinct_words() {
        // "Visit [https://example.com] and check [./docs.md]."
        // URL anchors "Visit", file anchors "check".
        let source = "Visit [https://example.com] and check [./docs.md].\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(links.len(), 2);

        let url = links
            .iter()
            .find(|l| l.link_type == LinkType::Url)
            .expect("url link");
        let file = links
            .iter()
            .find(|l| l.link_type == LinkType::File)
            .expect("file link");

        assert_eq!(&source[url.range.span.clone()], "Visit");
        assert_eq!(&source[file.range.span.clone()], "check");
    }

    #[test]
    fn test_long_paragraph_with_single_file_ref_anchors_only_the_word() {
        // Reproduces the dodot architecture.lex case: a long paragraph that
        // contains a single file reference. The link's range covers only the
        // anchored word "see", never the whole paragraph.
        let source = "\
This document describes how dodot is organized. It is the conceptual view. \
For concrete types, crate layout, and trait signatures, see [./types.lex].\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(links.len(), 1);
        let link = &links[0];
        assert_eq!(link.target, "./types.lex");

        let captured = &source[link.range.span.clone()];
        assert_eq!(
            captured, "see",
            "inline link range must cover only the anchored word, not the paragraph"
        );
    }

    // -----------------------------------------------------------------------
    // Nested-session title coverage
    //
    // `Session::find_all_links` originally only inspected `self.title`, while
    // `Document::find_all_links` calls it on the implicit root session whose
    // title is empty. Paragraph traversal recurses into nested sessions, but
    // nested-session *titles* never get scanned. So URL/File refs that appear
    // in a section heading like
    //
    //     1. See [./handlers.lex] for the phase list
    //
    //         (body)
    //
    // were silently dropped from the LSP `documentLink` response, and editors
    // had no clickable surface on the heading.
    // -----------------------------------------------------------------------

    #[test]
    fn test_file_ref_in_nested_session_title_produces_link() {
        // "Doc title" + blank + indent → outer session whose title is
        // "Doc title". Then the indented "See [./other.lex] for details"
        // line, followed by a blank and a deeper indent, becomes a *nested*
        // session whose title contains a file reference.
        let source =
            "Doc title\n\n    See [./other.lex] for details\n\n        nested content here.\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(
            links.len(),
            1,
            "expected one link for the file ref in the nested-session title; got {links:?}"
        );
        let link = &links[0];
        assert_eq!(link.target, "./other.lex");
        assert_eq!(link.link_type, LinkType::File);

        // Inline reference in the title → anchors the preceding word "See".
        assert_eq!(
            &source[link.range.span.clone()],
            "See",
            "nested-session title link anchors the preceding word"
        );
    }

    #[test]
    fn test_url_ref_in_nested_session_title_produces_link() {
        let source = "Doc title\n\n    Visit [https://example.com] today\n\n        body line.\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(links.len(), 1);
        let link = &links[0];
        assert_eq!(link.target, "https://example.com");
        assert_eq!(link.link_type, LinkType::Url);

        // Inline reference in the title → anchors the preceding word "Visit".
        assert_eq!(&source[link.range.span.clone()], "Visit");
    }

    #[test]
    fn test_refs_in_both_outer_and_nested_session_titles_produce_links() {
        // The outer title also contains a file reference, so both the outer
        // and nested titles should each contribute one link, distinct from
        // any links found in paragraphs.
        let source = "\
Top [./top.lex] section

    Inner [./inner.lex] subsection

        See also [./body.lex] in the body.
";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(
            links.len(),
            3,
            "expected three links (outer-title, inner-title, body); got {links:?}"
        );
        let targets: Vec<&str> = links.iter().map(|l| l.target.as_str()).collect();
        assert!(targets.contains(&"./top.lex"));
        assert!(targets.contains(&"./inner.lex"));
        assert!(targets.contains(&"./body.lex"));
    }

    // -----------------------------------------------------------------------
    // Reference lines: whole-element anchors and self-links (§2.3.2)
    //
    // A reference line (`[ref]` alone on its line) is removed from the
    // structural stream and collected on the document. PR C surfaces it as a
    // `DocumentLink` whose range is the *anchored span*: the head line of the
    // element above (whole-element anchor), or the reference's own text when
    // there is no content line above (self-link). These prove the LSP emits a
    // standard range + target — the editor needs no special handling.
    // -----------------------------------------------------------------------

    #[test]
    fn test_reference_line_whole_element_anchors_session_title() {
        // The reference line anchors the entire session title "Getting Started".
        let source = "Getting Started\n[./readme.txt]\n\n    Welcome to the docs.\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(links.len(), 1, "one whole-element link; got {links:?}");
        let link = &links[0];
        assert_eq!(link.target, "./readme.txt");
        assert_eq!(link.link_type, LinkType::File);

        // Range covers the head line, not the `[./readme.txt]` reference line.
        assert_eq!(
            &source[link.range.span.clone()],
            "Getting Started",
            "whole-element link must cover the anchored head line"
        );
        // Positions point at the title line (line 0), full width.
        assert_eq!(link.range.start, Position::new(0, 0));
        assert_eq!(link.range.end, Position::new(0, "Getting Started".len()));
    }

    #[test]
    fn test_reference_line_whole_element_anchors_list_item() {
        // Anchors the whole "Water" list item; the `- ` marker is excluded.
        let source = "- Food\n- Water\n[https://water.example]\n- Bread\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(links.len(), 1);
        let link = &links[0];
        assert_eq!(link.target, "https://water.example");
        assert_eq!(link.link_type, LinkType::Url);
        assert_eq!(
            &source[link.range.span.clone()],
            "Water",
            "list-item anchor excludes the `- ` marker"
        );
    }

    #[test]
    fn test_reference_line_whole_element_anchors_definition_subject() {
        // Anchors the definition term "API Endpoint"; the trailing `:` excluded.
        let source =
            "API Endpoint:\n[./endpoint.txt]\n    A URL that provides access to a resource.\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(links.len(), 1);
        let link = &links[0];
        assert_eq!(link.target, "./endpoint.txt");
        assert_eq!(
            &source[link.range.span.clone()],
            "API Endpoint",
            "subject anchor excludes the trailing colon"
        );
    }

    #[test]
    fn test_reference_line_self_link_range_is_the_reference_text() {
        // No content line directly above (blank line above) → self-link. The
        // link covers the reference's own `[bracketed]` text.
        let source = "See the upstream project:\n\n[https://github.com/lex-fmt/lex]\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(links.len(), 1, "one self-link; got {links:?}");
        let link = &links[0];
        assert_eq!(link.target, "https://github.com/lex-fmt/lex");
        assert_eq!(
            &source[link.range.span.clone()],
            "[https://github.com/lex-fmt/lex]",
            "self-link covers the reference's own bracketed text"
        );
    }

    #[test]
    fn test_reference_line_self_link_at_start_of_document() {
        // First line of the document → no content above → self-link.
        let source = "[https://lex.ing]\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(links.len(), 1);
        assert_eq!(
            &source[links[0].range.span.clone()],
            "[https://lex.ing]",
            "self-link covers the reference's own bracketed text"
        );
    }

    // -----------------------------------------------------------------------
    // Finding #1: pending `Following` link must never be silently dropped.
    //
    // A `Following`-anchored reference defers its link until the next `Plain`
    // node. If that never arrives (the walk ends, or only non-`Plain` nodes
    // follow) the collector must still flush the pending link, falling back to
    // the bracket range. Likewise, two `Following` refs back-to-back must each
    // emit (the first is flushed before the second becomes pending).
    // -----------------------------------------------------------------------

    #[test]
    fn test_following_anchor_followed_by_only_non_plain_nodes_still_emits() {
        // The reference is first on its line (→ `Following` anchor) and the only
        // node after it is inline code, which the walker reports via
        // `visit_code` — never `visit_plain`. So the pending link is never
        // resolved during the walk. Without the end-of-walk `flush()` this link
        // is silently dropped (0 links); with it, the link still emits, falling
        // back to the bracket range.
        let source = "[https://a.example]`code`\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(
            links.len(),
            1,
            "following-anchor link followed only by non-plain nodes must still \
             emit (bracket-range fallback); got {links:?}"
        );
        let link = &links[0];
        assert_eq!(link.target, "https://a.example");
        // Bracket-range fallback: covers the `[https://a.example]` text.
        assert_eq!(&source[link.range.span.clone()], "[https://a.example]");
    }

    #[test]
    fn test_two_following_anchors_in_a_row_both_emit() {
        // Two first-on-line references with no plain text between them. The
        // first becomes pending, then the second arrives: the first must be
        // flushed (bracket fallback) before the second is stored, so both emit.
        let source = "[https://a.example][https://b.example] tail\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(
            links.len(),
            2,
            "both back-to-back following-anchor refs must emit; got {links:?}"
        );
        let targets: Vec<&str> = links.iter().map(|l| l.target.as_str()).collect();
        assert!(targets.contains(&"https://a.example"));
        assert!(targets.contains(&"https://b.example"));
    }

    // -----------------------------------------------------------------------
    // Finding #2: reference-line ranges must use UTF-16 columns, matching the
    // inline word-anchor path and LSP's default `positionEncoding`.
    //
    // The reference-line ranges arrive as byte columns (built via
    // `SourceLocation::byte_range_to_ast_range`). For non-ASCII anchor /
    // reference text, a byte column overshoots the UTF-16 column an editor
    // expects, misplacing the link decoration. The collector normalizes them.
    // -----------------------------------------------------------------------

    #[test]
    fn test_reference_line_whole_element_end_column_is_utf16() {
        // Title contains a multi-byte char "é" (2 UTF-8 bytes, 1 UTF-16 unit).
        // "Café Menu" is 9 chars / 9 UTF-16 units, but 10 UTF-8 bytes.
        let source = "Café Menu\n[./menu.txt]\n\n    Today's specials.\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(links.len(), 1, "got {links:?}");
        let link = &links[0];
        assert_eq!(link.target, "./menu.txt");
        assert_eq!(
            &source[link.range.span.clone()],
            "Café Menu",
            "byte span still covers the whole anchored title"
        );
        // End column counts UTF-16 units (9), not UTF-8 bytes (10).
        assert_eq!(link.range.start, Position::new(0, 0));
        assert_eq!(
            link.range.end,
            Position::new(0, 9),
            "end column must be the UTF-16 width of the anchor, not its byte length"
        );
    }

    #[test]
    fn test_reference_line_self_link_end_column_is_utf16() {
        // Self-link whose URL contains a multi-byte char. "[https://café.example]"
        // is 22 chars / 22 UTF-16 units but 23 UTF-8 bytes (é = 2 bytes).
        let source = "[https://café.example]\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(links.len(), 1, "got {links:?}");
        let link = &links[0];
        assert_eq!(link.target, "https://café.example");
        assert_eq!(
            &source[link.range.span.clone()],
            "[https://café.example]",
            "byte span still covers the bracketed reference"
        );
        assert_eq!(link.range.start, Position::new(0, 0));
        assert_eq!(
            link.range.end,
            Position::new(0, 22),
            "self-link end column must be the UTF-16 width of `[` + raw + `]`"
        );
    }

    // -----------------------------------------------------------------------
    // Finding #3: `locate_word_range` must not mis-map when the anchored plain
    // text run contains an escape. The unescaped `PlainSpan.text` is shorter
    // than its raw `range.span`, so byte offsets into the text don't line up
    // with the raw source. The guard returns `None` → bracket-range fallback.
    // -----------------------------------------------------------------------

    #[test]
    fn test_escaped_char_in_anchored_word_falls_back_to_bracket_range() {
        // The preceding plain run "a\\*b " contains an escape (`\*` → `*`), so
        // the unescaped text ("a*b ") is one byte shorter than the raw span.
        // The collector must fall back to the bracket range rather than emit a
        // misplaced underline.
        let source = "a\\*b [https://x.example] tail\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();

        assert_eq!(links.len(), 1, "got {links:?}");
        let link = &links[0];
        assert_eq!(link.target, "https://x.example");
        assert_eq!(
            &source[link.range.span.clone()],
            "[https://x.example]",
            "escaped anchored run must fall back to the bracket range"
        );
    }

    #[test]
    fn test_marker_reference_line_is_not_a_document_link() {
        // A footnote on its own line is a marker-style reference: not a
        // reference line and not a document link.
        let source = "Some claim.\n[42]\n\n:: 42 :: A footnote.\n\n";
        let doc = parse_document(source).unwrap();
        let links = doc.find_all_links();
        assert!(
            links.is_empty(),
            "marker-style references are not document links: {links:?}"
        );
    }
}