panache 2.44.0

An LSP, formatter, and linter for Markdown, Quarto, and R Markdown
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
//! Handler for textDocument/hover LSP requests.
//!
//! Provides hover information for:
//! - Footnote references: `[^id]` → shows footnote content from `[^id]: content`

use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;

use tokio::sync::Mutex;
use tower_lsp_server::jsonrpc::Result;
use tower_lsp_server::ls_types::*;

use crate::lsp::DocumentState;
use crate::lsp::symbols::{SymbolTarget, resolve_symbol_target_at_offset};
use crate::metadata::inline_reference_contains;
use crate::syntax::{
    AstNode, DisplayMath, Document, FootnoteDefinition, Heading, Link, ReferenceDefinition,
};
use crate::utils::{crossref_resolution_labels, normalize_label};

use super::super::{conversions, helpers};

/// Handle textDocument/hover request
pub(crate) async fn hover(
    _client: &tower_lsp_server::Client,
    document_map: Arc<Mutex<HashMap<String, DocumentState>>>,
    salsa_db: Arc<Mutex<crate::salsa::SalsaDb>>,
    _workspace_root: Arc<Mutex<Option<PathBuf>>>,
    params: HoverParams,
) -> Result<Option<Hover>> {
    let uri = &params.text_document_position_params.text_document.uri;
    let position = params.text_document_position_params.position;

    let Some(ctx) =
        crate::lsp::context::get_open_document_context(&document_map, &salsa_db, uri).await
    else {
        return Ok(None);
    };
    let salsa_file = ctx.salsa_file;
    let salsa_config = ctx.salsa_config;
    let doc_path = ctx.path.clone();
    let parsed_yaml_regions = ctx.parsed_yaml_regions.clone();

    let Some(doc_path) = doc_path else {
        return Ok(None);
    };
    let content_for_offset = ctx.content.clone();
    let Some(offset) = conversions::position_to_offset(&content_for_offset, position) else {
        return Ok(None);
    };
    let in_frontmatter_region =
        helpers::is_offset_in_yaml_frontmatter(&parsed_yaml_regions, offset);
    if in_frontmatter_region {
        return Ok(None);
    }
    let yaml_ok = helpers::is_yaml_frontmatter_valid(&parsed_yaml_regions);
    if !yaml_ok {
        return Ok(None);
    }

    let metadata = {
        let db = salsa_db.lock().await;
        crate::salsa::metadata(&*db, salsa_file, salsa_config, doc_path.clone()).clone()
    };

    let target = {
        let root = ctx.syntax_root();
        resolve_symbol_target_at_offset(&root, offset)
    };

    if let Some(SymbolTarget::HeadingLink(label)) = target.as_ref() {
        let doc_indices = crate::lsp::navigation::project_symbol_documents(
            &salsa_db,
            salsa_file,
            salsa_config,
            &doc_path,
            uri,
            &content_for_offset,
        )
        .await;

        for doc in &doc_indices {
            if let Some(markdown) = section_hover_markdown(doc, label) {
                return Ok(Some(Hover {
                    contents: HoverContents::Markup(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value: markdown,
                    }),
                    range: None,
                }));
            }
        }
    }
    if let Some(SymbolTarget::Reference {
        label,
        is_footnote: false,
    }) = target.as_ref()
    {
        let doc_indices = crate::lsp::navigation::project_symbol_documents(
            &salsa_db,
            salsa_file,
            salsa_config,
            &doc_path,
            uri,
            &content_for_offset,
        )
        .await;

        for doc in &doc_indices {
            let Some(heading_label) = reference_definition_heading_target(doc, label) else {
                continue;
            };
            for candidate_doc in &doc_indices {
                if let Some(markdown) = section_hover_markdown(candidate_doc, &heading_label) {
                    return Ok(Some(Hover {
                        contents: HoverContents::Markup(MarkupContent {
                            kind: MarkupKind::Markdown,
                            value: markdown,
                        }),
                        range: None,
                    }));
                }
            }
        }
    }
    if let Some(SymbolTarget::Crossref(label)) = target.as_ref() {
        let doc_indices = crate::lsp::navigation::project_symbol_documents(
            &salsa_db,
            salsa_file,
            salsa_config,
            &doc_path,
            uri,
            &content_for_offset,
        )
        .await;

        for doc in &doc_indices {
            if let Some(markdown) = equation_hover_markdown(doc, label) {
                return Ok(Some(Hover {
                    contents: HoverContents::Markup(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value: markdown,
                    }),
                    range: None,
                }));
            }
            if let Some(markdown) = section_hover_markdown(doc, label) {
                return Ok(Some(Hover {
                    contents: HoverContents::Markup(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value: markdown,
                    }),
                    range: None,
                }));
            }
        }
    }
    let link_target = {
        let root = ctx.syntax_root();
        hovered_link_target(&root, offset)
    };
    if let Some(markdown) = linked_document_hover_markdown(
        link_target.as_deref(),
        &salsa_db,
        salsa_file,
        salsa_config,
        &doc_path,
        &content_for_offset,
        uri,
    )
    .await
    {
        return Ok(Some(Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value: markdown,
            }),
            range: None,
        }));
    }

    let pending_footnote = {
        let root = ctx.syntax_root();
        let Some(mut node) = helpers::find_node_at_offset(&root, offset) else {
            return Ok(None);
        };

        // Walk up the tree to find a footnote reference or citation
        loop {
            if let Some((label, is_footnote)) = helpers::extract_reference_label(&node) {
                // Only handle footnotes (not regular references)
                if is_footnote {
                    break Some(label);
                }
            }

            if let Some(key) = helpers::extract_citation_key(&node) {
                if let Some(ref parse) = metadata.bibliography_parse
                    && let Some(entry) = parse.index.get(&key)
                {
                    let summary = format_bibliography_entry(entry);
                    if !summary.is_empty() {
                        return Ok(Some(Hover {
                            contents: HoverContents::Markup(MarkupContent {
                                kind: MarkupKind::Markdown,
                                value: summary,
                            }),
                            range: None,
                        }));
                    }
                }

                if inline_reference_contains(&metadata.inline_references, &key) {
                    return Ok(Some(Hover {
                        contents: HoverContents::Markup(MarkupContent {
                            kind: MarkupKind::Markdown,
                            value: "Inline YAML reference".to_string(),
                        }),
                        range: None,
                    }));
                }
            }

            // Move up to parent, or return None if at root
            match node.parent() {
                Some(parent) => node = parent,
                None => break None,
            }
        }
    };

    let Some(label) = pending_footnote else {
        return Ok(None);
    };

    // Cross-document footnote lookup via symbol usage index.
    let doc_indices = crate::lsp::navigation::project_symbol_documents(
        &salsa_db,
        salsa_file,
        salsa_config,
        &doc_path,
        uri,
        &content_for_offset,
    )
    .await;

    for doc in doc_indices {
        let Some(ranges) = doc.symbol_index.footnote_definitions(&label) else {
            continue;
        };
        let Some(range) = ranges.first() else {
            continue;
        };

        let tree = crate::parse(&doc.text, None);
        let Some(footnote_def) = tree
            .descendants()
            .filter_map(FootnoteDefinition::cast)
            .find(|def| def.syntax().text_range() == *range)
        else {
            continue;
        };

        let trimmed = footnote_def.content().trim().to_string();
        return Ok(Some(Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value: trimmed,
            }),
            range: None,
        }));
    }

    Ok(None)
}

const HOVER_PREVIEW_MAX_CHARS: usize = 180;
const HOVER_EQUATION_PREVIEW_MAX_LINES: usize = 6;

fn equation_hover_markdown(
    doc: &crate::lsp::navigation::IndexedDocument,
    label: &str,
) -> Option<String> {
    let candidates = crossref_resolution_labels(label, true);
    let mut declaration_ranges = Vec::new();
    for candidate in candidates {
        if let Some(ranges) = doc.symbol_index.crossref_declarations(&candidate) {
            declaration_ranges.extend(ranges.iter().copied());
        }
    }
    declaration_ranges.sort_by_key(|range| range.start());
    declaration_ranges.dedup();
    if declaration_ranges.is_empty() {
        return None;
    }

    let tree = crate::parse(&doc.text, None);
    for declaration in declaration_ranges {
        let Some(math) = display_math_for_declaration(&tree, declaration) else {
            continue;
        };
        let content = math.content();
        let trimmed = content.trim_matches('\n').trim_end();
        if trimmed.is_empty() {
            continue;
        }
        let snippet = crop_preview_lines(trimmed, HOVER_EQUATION_PREVIEW_MAX_LINES);
        return Some(format!("**Equation:** `{label}`\n\n```tex\n{snippet}\n```"));
    }
    None
}

fn section_hover_markdown(
    doc: &crate::lsp::navigation::IndexedDocument,
    label: &str,
) -> Option<String> {
    let heading_range = first_heading_definition_range(&doc.symbol_index, label)?;
    let tree = crate::parse(&doc.text, None);
    let document = Document::cast(tree)?;

    let blocks: Vec<_> = document.blocks().collect();
    let heading_idx = blocks.iter().position(|node| {
        node.kind() == crate::syntax::SyntaxKind::HEADING && node.text_range() == heading_range
    })?;
    let heading_node = &blocks[heading_idx];
    let heading = Heading::cast(heading_node.clone())?;
    let title = heading.title_or("(empty)");
    let section_end = section_end_offset(&doc.symbol_index, heading_range, doc.text.len());

    let mut preview = None;
    for block in blocks.iter().skip(heading_idx + 1) {
        let start: usize = block.text_range().start().into();
        if start >= section_end {
            break;
        }
        let normalized = normalize_preview_text(block.text().to_string().trim());
        if !normalized.is_empty() {
            preview = Some(crop_preview(&normalized, HOVER_PREVIEW_MAX_CHARS));
            break;
        }
    }

    let markdown = match preview {
        Some(snippet) => format!("**Section:** {}\n\n{}", title, snippet),
        None => format!("**Section:** {}", title),
    };
    Some(markdown)
}

fn reference_definition_heading_target(
    doc: &crate::lsp::navigation::IndexedDocument,
    label: &str,
) -> Option<String> {
    let tree = crate::parse(&doc.text, None);
    let normalized = normalize_label(label);
    let def = tree
        .descendants()
        .filter_map(ReferenceDefinition::cast)
        .find(|def| normalize_label(&def.label()) == normalized)?;
    let destination = def.destination()?;
    heading_label_from_destination(&destination)
}

fn heading_label_from_destination(destination: &str) -> Option<String> {
    let mut target = destination.trim();
    if let Some(rest) = target.strip_prefix('<')
        && let Some(end) = rest.find('>')
    {
        target = &rest[..end];
    } else if let Some((head, _)) = target.split_once(char::is_whitespace) {
        target = head;
    }
    let anchor = target.strip_prefix('#')?;
    let normalized = normalize_label(anchor);
    (!normalized.is_empty()).then_some(normalized)
}

fn first_heading_definition_range(
    index: &crate::salsa::SymbolUsageIndex,
    label: &str,
) -> Option<rowan::TextRange> {
    let mut all = Vec::new();
    if let Some(ranges) = index.heading_explicit_definition_ranges(label) {
        all.extend(ranges.iter().copied());
    }
    if let Some(ranges) = index.heading_implicit_definition_ranges(label) {
        all.extend(ranges.iter().copied());
    }
    all.into_iter().min_by_key(|range| range.start())
}

fn section_end_offset(
    index: &crate::salsa::SymbolUsageIndex,
    heading_range: rowan::TextRange,
    text_len: usize,
) -> usize {
    let Some((at, level)) = index
        .heading_sequence()
        .iter()
        .enumerate()
        .find_map(|(idx, (range, lvl))| (*range == heading_range).then_some((idx, *lvl)))
    else {
        return text_len;
    };

    index
        .heading_sequence()
        .iter()
        .skip(at + 1)
        .find_map(|(next_range, next_level)| (*next_level <= level).then_some(next_range.start()))
        .map(Into::<usize>::into)
        .unwrap_or(text_len)
}

fn normalize_preview_text(text: &str) -> String {
    text.split_whitespace().collect::<Vec<_>>().join(" ")
}

fn crop_preview(text: &str, max_chars: usize) -> String {
    let mut iter = text.chars();
    let mut out = String::new();
    for _ in 0..max_chars {
        if let Some(ch) = iter.next() {
            out.push(ch);
        } else {
            return out;
        }
    }
    if iter.next().is_some() {
        out.push_str("...");
    }
    out
}

fn display_math_for_declaration(
    tree: &crate::syntax::SyntaxNode,
    declaration: rowan::TextRange,
) -> Option<DisplayMath> {
    let math_nodes: Vec<_> = tree.descendants().filter_map(DisplayMath::cast).collect();

    if let Some(math) = math_nodes.iter().find(|math| {
        let range = math.syntax().text_range();
        range.start() <= declaration.start() && declaration.end() <= range.end()
    }) {
        return DisplayMath::cast(math.syntax().clone());
    }

    let declaration_start: usize = declaration.start().into();
    math_nodes
        .into_iter()
        .filter_map(|math| {
            let range = math.syntax().text_range();
            let math_end: usize = range.end().into();
            (math_end <= declaration_start).then_some((declaration_start - math_end, math))
        })
        .min_by_key(|(distance, _)| *distance)
        .and_then(|(distance, math)| (distance <= 16).then_some(math))
}

fn crop_preview_lines(text: &str, max_lines: usize) -> String {
    let lines: Vec<&str> = text.lines().collect();
    if lines.len() <= max_lines {
        return text.to_string();
    }
    let mut out = lines[..max_lines].join("\n");
    out.push_str("\n...");
    out
}

async fn linked_document_hover_markdown(
    raw_link_target: Option<&str>,
    salsa_db: &Arc<Mutex<crate::salsa::SalsaDb>>,
    salsa_file: crate::salsa::FileText,
    salsa_config: crate::salsa::FileConfig,
    doc_path: &Path,
    content: &str,
    uri: &Uri,
) -> Option<String> {
    let link_target = raw_link_target?;
    let target_uri = resolve_local_markdown_target(
        salsa_db,
        salsa_file,
        salsa_config,
        doc_path,
        content,
        uri,
        link_target,
    )
    .await?;
    let target_path = target_uri.to_file_path()?;
    if target_path == doc_path {
        return None;
    }
    let target_text = std::fs::read_to_string(&target_path).ok()?;
    linked_doc_preview_markdown(&target_text, &target_path)
}

fn hovered_link_target(root: &crate::syntax::SyntaxNode, offset: usize) -> Option<String> {
    let mut node = helpers::find_node_at_offset(root, offset)?;
    loop {
        if let Some(link) = Link::cast(node.clone()) {
            if let Some(dest) = link.dest() {
                let dest_url = dest.url();
                let raw = crate::lsp::handlers::document_links::extract_first_destination_token(
                    &dest_url,
                );
                return (!raw.is_empty()).then_some(raw.to_string());
            }
            if let Some(link_ref) = link.reference() {
                let label = normalize_label(&link_ref.label());
                return (!label.is_empty()).then_some(format!("[ref]:{label}"));
            }
            if let Some(text) = link.text() {
                let label = normalize_label(&text.text_content());
                return (!label.is_empty()).then_some(format!("[ref]:{label}"));
            }
        }
        node = node.parent()?;
    }
}

async fn resolve_local_markdown_target(
    salsa_db: &Arc<Mutex<crate::salsa::SalsaDb>>,
    salsa_file: crate::salsa::FileText,
    salsa_config: crate::salsa::FileConfig,
    doc_path: &Path,
    content: &str,
    uri: &Uri,
    raw_target: &str,
) -> Option<Uri> {
    let resolved = if let Some(label) = raw_target.strip_prefix("[ref]:") {
        let ref_targets = crate::lsp::handlers::document_links::build_reference_targets(
            salsa_db,
            salsa_file,
            salsa_config,
            doc_path,
            content,
            uri,
        )
        .await;
        let target = ref_targets.get(label)?;
        crate::lsp::handlers::document_links::resolve_link_target(
            &target.raw_target,
            Some(&target.base_path),
            target.base_uri.as_ref(),
        )?
    } else {
        crate::lsp::handlers::document_links::resolve_link_target(
            raw_target,
            Some(doc_path),
            Some(uri),
        )?
    };

    let path = resolved.to_file_path()?;
    if !is_markdown_family_path(&path) {
        return None;
    }
    Some(resolved)
}

fn is_markdown_family_path(path: &Path) -> bool {
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or_default();
    matches!(ext, "md" | "qmd" | "Rmd" | "markdown")
}

fn linked_doc_preview_markdown(target_text: &str, target_path: &Path) -> Option<String> {
    let tree = crate::parse(target_text, None);
    let document = Document::cast(tree)?;
    let blocks: Vec<_> = document.blocks().collect();
    let title = blocks
        .iter()
        .find_map(|node| Heading::cast(node.clone()))
        .map(|h| h.title_or("(empty)"));

    let heading_ranges: HashSet<rowan::TextRange> = blocks
        .iter()
        .filter(|node| node.kind() == crate::syntax::SyntaxKind::HEADING)
        .map(|node| node.text_range())
        .collect();
    let snippet = blocks.iter().find_map(|node| {
        if heading_ranges.contains(&node.text_range()) {
            return None;
        }
        let normalized = normalize_preview_text(node.text().to_string().trim());
        (!normalized.is_empty()).then_some(crop_preview(&normalized, HOVER_PREVIEW_MAX_CHARS))
    });

    if title.is_none() && snippet.is_none() {
        return None;
    }
    let file_name = target_path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("document");
    let mut out = format!("**Linked document:** `{file_name}`");
    if let Some(title) = title {
        out.push_str(&format!("\n\n**Title:** {}", title));
    }
    if let Some(snippet) = snippet {
        out.push_str(&format!("\n\n{}", snippet));
    }
    Some(out)
}

/// Format a bibliography entry for hover display.
///
/// Works with any bibliography format (BibTeX, CSL-JSON, CSL-YAML, RIS).
fn format_bibliography_entry(entry: &crate::bib::BibEntry) -> String {
    let author = entry
        .fields
        .get("author")
        .or_else(|| entry.fields.get("editor"))
        .map(|s| s.as_str())
        .unwrap_or_default();

    let year = entry
        .fields
        .get("year")
        .or_else(|| entry.fields.get("date"))
        .or_else(|| entry.fields.get("issued"))
        .map(|s| s.as_str())
        .unwrap_or_default();

    let title = entry
        .fields
        .get("title")
        .or_else(|| entry.fields.get("booktitle"))
        .map(|s| s.as_str())
        .unwrap_or_default();

    let container = entry
        .fields
        .get("journal")
        .or_else(|| entry.fields.get("journaltitle"))
        .or_else(|| entry.fields.get("container-title"))
        .or_else(|| entry.fields.get("publisher"))
        .map(|s| s.as_str())
        .unwrap_or_default();

    let locator = build_locator_unified(entry);

    let mut summary = String::new();
    if !author.is_empty() {
        summary.push_str(author);
    }
    if !year.is_empty() {
        if !summary.is_empty() {
            summary.push_str(" (");
            summary.push_str(year);
            summary.push(')');
        } else {
            summary.push_str(year);
        }
    }
    if !title.is_empty() {
        if !summary.is_empty() {
            summary.push_str(". ");
        }
        summary.push_str(&format!("*{}*", title));
    }
    if !container.is_empty() {
        summary.push_str(". ");
        summary.push_str(container);
    }
    if !locator.is_empty() {
        summary.push_str(", ");
        summary.push_str(&locator);
    }

    summary.trim().to_string()
}

fn build_locator_unified(entry: &crate::bib::BibEntry) -> String {
    let volume = entry
        .fields
        .get("volume")
        .map(|s| s.as_str())
        .unwrap_or_default();
    let number = entry
        .fields
        .get("number")
        .or_else(|| entry.fields.get("issue"))
        .map(|s| s.as_str())
        .unwrap_or_default();
    let pages = entry
        .fields
        .get("pages")
        .or_else(|| entry.fields.get("page"))
        .map(|s| s.as_str())
        .unwrap_or_default();

    let mut parts = Vec::new();
    if !volume.is_empty() {
        if !number.is_empty() {
            parts.push(format!("{}({})", volume, number));
        } else {
            parts.push(volume.to_string());
        }
    } else if !number.is_empty() {
        parts.push(number.to_string());
    }
    if !pages.is_empty() {
        parts.push(pages.to_string());
    }
    parts.join(", ")
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse;
    use crate::syntax::AstNode;

    #[test]
    fn test_hover_on_footnote_reference() {
        let input = "Text with footnote[^1]\n\n[^1]: This is the footnote content.";
        let root = parse(input, None);

        // Find the footnote reference node
        let footnote_ref = root
            .descendants()
            .find_map(crate::syntax::FootnoteReference::cast)
            .expect("Should find footnote reference")
            .syntax()
            .clone();

        // Extract the label
        let (label, is_footnote) =
            helpers::extract_reference_label(&footnote_ref).expect("Should extract label");
        assert_eq!(label, "1");
        assert!(is_footnote);

        let db = crate::salsa::SalsaDb::default();
        let extensions = crate::config::Extensions::default();
        let index = crate::salsa::symbol_usage_index_from_tree(&db, &root, &extensions);
        let range = index
            .footnote_definitions(&label)
            .and_then(|ranges| ranges.first())
            .copied()
            .expect("Should find definition range");
        let footnote_def = root
            .descendants()
            .filter_map(FootnoteDefinition::cast)
            .find(|def| def.syntax().text_range() == range)
            .expect("Should find footnote definition by range");

        // Extract content
        let content = footnote_def.content();
        assert!(content.contains("This is the footnote content"));
    }

    #[test]
    fn test_hover_multiline_footnote() {
        let input = "Text[^1]\n\n[^1]: First line\n    Second line";
        let root = parse(input, None);

        let db = crate::salsa::SalsaDb::default();
        let extensions = crate::config::Extensions::default();
        let index = crate::salsa::symbol_usage_index_from_tree(&db, &root, &extensions);
        let range = index
            .footnote_definitions("1")
            .and_then(|ranges| ranges.first())
            .copied()
            .expect("Should find definition range");
        let footnote_def = root
            .descendants()
            .filter_map(FootnoteDefinition::cast)
            .find(|def| def.syntax().text_range() == range)
            .expect("Should find footnote definition by range");

        let content = footnote_def.content();
        assert!(content.contains("First line"));
        assert!(content.contains("Second line"));
    }

    #[test]
    fn test_no_definition_found() {
        let input = "Text with footnote[^missing]";
        let root = parse(input, None);

        let db = crate::salsa::SalsaDb::default();
        let extensions = crate::config::Extensions::default();
        let index = crate::salsa::symbol_usage_index_from_tree(&db, &root, &extensions);
        assert!(index.footnote_definitions("missing").is_none());
    }

    #[test]
    fn test_footnote_with_formatting() {
        let input = "[^1]: Text with *emphasis* and `code`.";
        let root = parse(input, None);

        let db = crate::salsa::SalsaDb::default();
        let extensions = crate::config::Extensions::default();
        let index = crate::salsa::symbol_usage_index_from_tree(&db, &root, &extensions);
        let range = index
            .footnote_definitions("1")
            .and_then(|ranges| ranges.first())
            .copied()
            .expect("Should find definition range");
        let footnote_def = root
            .descendants()
            .filter_map(FootnoteDefinition::cast)
            .find(|def| def.syntax().text_range() == range)
            .expect("Should find footnote definition by range");

        let content = footnote_def.content();
        assert!(content.contains("*emphasis*"));
        assert!(content.contains("`code`"));
    }

    #[test]
    fn footnote_definition_index_contains_definition_range() {
        let db = crate::salsa::SalsaDb::default();
        let text = "Text[^a]\n\n[^a]: Hello world\n";
        let tree = parse(text, None);
        let extensions = crate::config::Extensions::default();
        let index = crate::salsa::symbol_usage_index_from_tree(&db, &tree, &extensions);
        assert_eq!(
            index.footnote_definitions("a").map(|ranges| ranges.len()),
            Some(1)
        );
    }
}