panache 3.14.0

Language server, 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
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
//! Handler for textDocument/completion LSP requests.

use lsp_types::*;
use std::path::{Path, PathBuf};

use crate::lsp::global_state::StateSnapshot;
use crate::syntax::{
    AstNode, AttributeNode, AutoLink, Citation, CodeBlock, CodeSpan, DisplayMath,
    FootnoteReference, HeadingContent, ImageAlt, ImageLink, InlineExecutable, InlineHtml,
    InlineMath, LineBlockLine, Link, LinkDest, LinkRef, LinkText, Paragraph, Plain,
    ReferenceDefinition, Shortcode, SyntaxKind, SyntaxNode, TableCell, TexBlock,
    UnresolvedReference, WikiLink, YamlMetadata,
};
use crate::utils::{normalize_anchor_label, normalize_label};

use super::super::conversions::offset_to_position;
use super::super::helpers;
use super::shortcode_args::{
    ShortcodeKind, shortcode_token_value_span, shortcode_tokens, token_is_named,
};
use crate::metadata::inline_reference_map;

/// Common still-image extensions accepted by Pandoc/Quarto image syntax
/// `![](…)` across LaTeX, Typst, and HTML output paths.
const STILL_IMAGE_EXTENSIONS: &[&str] = &[
    // Raster
    "png", "jpg", "jpeg", "gif", "apng", "webp", "avif", "bmp", "tif", "tiff", "heic", "heif",
    "jxl", "ico", // Vector / print
    "svg", "pdf", "eps", "ps",
];

/// Video container extensions that Quarto can embed directly via `![](…)`
/// or `{{< video >}}`.
const VIDEO_EXTENSIONS: &[&str] = &[
    "mp4", "webm", "ogv", "mov", "m4v", "mkv", "avi", "flv", "mpeg", "mpg", "3gp",
];

/// Extensions accepted by `{{< include >}}` — markdown documents plus
/// script files that the user typically pulls into code chunks.
const INCLUDE_EXTENSIONS: &[&str] = &[
    "qmd",
    "md",
    "markdown",
    "rmd",
    "rmarkdown",
    "ipynb",
    "r",
    "py",
    "jl",
];

/// Extensions accepted by `{{< embed >}}` — Jupyter notebooks and Quarto
/// source documents.
const EMBED_EXTENSIONS: &[&str] = &["ipynb", "qmd"];

const MAX_PATH_COMPLETIONS: usize = 250;

pub(crate) fn completion(
    snap: &StateSnapshot,
    params: CompletionParams,
) -> Option<CompletionResponse> {
    let uri = &params.text_document_position.text_document.uri;
    let position = params.text_document_position.position;
    let config = snap.config(uri);

    let text = snap.document_content(uri)?;
    let root = snap.parsed_tree(uri)?;
    let line_index = snap.line_index(uri)?;
    let offset = super::super::conversions::position_to_offset(&line_index, position)?;
    if config.extensions.reference_links
        && let Some(ctx) = reference_label_context(&root, &text, offset, &config.parser_options())
    {
        let state = snap.document_state(uri)?;
        let index =
            crate::salsa::symbol_usage_index(snap.db(), state.salsa_file, state.salsa_config);
        let items = reference_label_items(&root, index, &line_index, ctx);
        return (!items.is_empty()).then_some(CompletionResponse::Array(items));
    }
    let link_ctx_opt = link_dest_context(&root, &text, offset);
    let shortcode_ctx_opt = if link_ctx_opt.is_none() && config.extensions.quarto_shortcodes {
        shortcode_arg_context(&root, &text, offset)
    } else {
        None
    };
    drop(root);

    // Path-completion branches: cursor inside `[text](…)` / `![alt](…)` destination,
    // or inside a path-bearing Quarto shortcode argument.
    if link_ctx_opt.is_some() || shortcode_ctx_opt.is_some() {
        let doc_path = snap
            .document_state(uri)
            .and_then(|s| crate::salsa::Db::path_of_id(snap.db(), s.file_id));
        let ws_root = snap.workspace_root_for(uri);

        let request = if let Some(ctx) = link_ctx_opt {
            link_dest_path_request(&ctx, doc_path.as_deref())
        } else if let Some(ctx) = shortcode_ctx_opt {
            shortcode_path_request(&ctx, doc_path.as_deref(), ws_root.as_deref())
        } else {
            None
        };

        return match request {
            Some(req) => match path_completion_items(req, &text, offset) {
                Some(items) if !items.is_empty() => Some(CompletionResponse::Array(items)),
                _ => None,
            },
            None => None,
        };
    }

    let query = citation_query_prefix(&text, offset)?;

    let state = snap.document_state(uri)?;
    let (salsa_file, salsa_config, doc_path) = (
        state.salsa_file,
        state.salsa_config,
        crate::salsa::Db::path_of_id(snap.db(), state.file_id),
    );
    let parsed_yaml_regions = snap.parsed_yaml_regions(uri);

    let offset_in_frontmatter = helpers::is_offset_in_yaml_frontmatter(parsed_yaml_regions, offset);
    if offset_in_frontmatter {
        return None;
    }

    // Bibliography/citation completions only apply to saved documents.
    doc_path?;
    let yaml_ok = helpers::is_yaml_frontmatter_valid(parsed_yaml_regions);
    if !yaml_ok {
        return None;
    }

    let metadata = crate::salsa::metadata(snap.db(), salsa_file, salsa_config).clone();
    let parse = metadata.bibliography_parse.as_ref();
    let symbol_index =
        crate::salsa::symbol_usage_index(snap.db(), salsa_file, salsa_config).clone();

    let has_crossref_candidates = symbol_index
        .crossref_declaration_entries()
        .any(|(key, _)| is_supported_crossref_completion_key(key));
    if parse.is_none() && metadata.inline_references.is_empty() && !has_crossref_candidates {
        return None;
    }

    let mut seen = std::collections::HashSet::new();
    let mut items = Vec::new();
    if let Some(parse) = parse {
        for entry in parse.index.entries() {
            if !seen.insert(entry.key.to_lowercase()) {
                continue;
            }
            if !matches_query(&entry.key, &query) {
                continue;
            }
            items.push(CompletionItem {
                label: entry.key.clone(),
                kind: Some(CompletionItemKind::REFERENCE),
                insert_text: Some(entry.key.clone()),
                insert_text_format: Some(InsertTextFormat::PLAIN_TEXT),
                // Defer the (potentially large) bibliography preview to
                // `completionItem/resolve`; carry only what's needed to
                // re-find the entry when the item is focused.
                data: Some(serde_json::json!({
                    "kind": "citation",
                    "uri": uri.as_str(),
                    "key": entry.key,
                })),
                ..Default::default()
            });
        }
    }
    for (key, entries) in inline_reference_map(&metadata.inline_references) {
        if entries.is_empty() || !seen.insert(key.clone()) {
            continue;
        }
        let label = entries[0].id.clone();
        if !matches_query(&label, &query) {
            continue;
        }
        items.push(CompletionItem {
            label: label.clone(),
            kind: Some(CompletionItemKind::REFERENCE),
            insert_text: Some(label),
            insert_text_format: Some(InsertTextFormat::PLAIN_TEXT),
            ..Default::default()
        });
    }

    if config.extensions.quarto_crossrefs || config.extensions.bookdown_references {
        for (label, _) in symbol_index.crossref_declaration_entries() {
            if !is_supported_crossref_completion_key(label) {
                continue;
            }
            let display = normalize_anchor_label(label);
            if display.is_empty() || !seen.insert(display.to_lowercase()) {
                continue;
            }
            if !matches_query(&display, &query) {
                continue;
            }
            items.push(CompletionItem {
                label: display.clone(),
                kind: Some(CompletionItemKind::REFERENCE),
                insert_text: Some(display),
                insert_text_format: Some(InsertTextFormat::PLAIN_TEXT),
                ..Default::default()
            });
        }
    }

    if items.is_empty() {
        return None;
    }

    Some(CompletionResponse::Array(items))
}

/// Resolve a deferred citation completion item by attaching its bibliography
/// preview as markdown documentation.
///
/// Citation items emitted by [`completion`] carry a `data` payload
/// (`{kind, uri, key}`) instead of an eagerly-computed preview. When the client
/// focuses such an item it sends `completionItem/resolve`; we look the entry up
/// in the (salsa-cached) bibliography for its document and fill in
/// `documentation`/`detail`. Non-citation items, or items we can no longer
/// resolve (document closed, key removed), are returned unchanged.
pub(crate) fn completion_item_resolve(
    snap: &StateSnapshot,
    mut item: CompletionItem,
) -> CompletionItem {
    if item.documentation.is_some() {
        return item;
    }

    let Some(data) = &item.data else {
        return item;
    };
    if data.get("kind").and_then(|v| v.as_str()) != Some("citation") {
        return item;
    }
    let (Some(uri_str), Some(key)) = (
        data.get("uri").and_then(|v| v.as_str()),
        data.get("key").and_then(|v| v.as_str()),
    ) else {
        return item;
    };
    let Ok(uri) = uri_str.parse::<Uri>() else {
        return item;
    };

    let Some(state) = snap.document_state(&uri) else {
        return item;
    };
    let metadata = crate::salsa::metadata(snap.db(), state.salsa_file, state.salsa_config);
    let Some(parse) = metadata.bibliography_parse.as_ref() else {
        return item;
    };
    let Some(entry) = parse.index.get(key) else {
        return item;
    };

    if item.detail.is_none() {
        item.detail = entry.entry_type.clone();
    }
    let summary = crate::bib::format_entry_preview(entry);
    if !summary.is_empty() {
        item.documentation = Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value: summary,
        }));
    }

    item
}

fn citation_query_prefix(text: &str, offset: usize) -> Option<String> {
    // Look back a small fixed window for an `@`. Floor the window start down to
    // a char boundary so multi-byte text (e.g. CJK) right before the cursor
    // doesn't make us slice inside a character and panic (#298).
    let mut start = offset.saturating_sub(8);
    while start > 0 && !text.is_char_boundary(start) {
        start -= 1;
    }
    let snippet = text.get(start..offset)?;
    let at = snippet.rfind('@')?;
    let query = &snippet[at + 1..];
    if query
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | ':' | '.'))
    {
        Some(query.to_string())
    } else {
        None
    }
}

fn matches_query(candidate: &str, query: &str) -> bool {
    if query.is_empty() {
        return true;
    }
    candidate
        .to_ascii_lowercase()
        .starts_with(&query.to_ascii_lowercase())
}

fn is_supported_crossref_completion_key(key: &str) -> bool {
    panache_parser::parser::inlines::citations::is_quarto_crossref_key(key)
        || panache_parser::parser::inlines::citations::has_bookdown_prefix(key)
}

struct ReferenceLabelContext {
    query: String,
    range: std::ops::Range<usize>,
    needs_close: bool,
}

fn reference_label_context(
    root: &SyntaxNode,
    text: &str,
    offset: usize,
    options: &crate::config::ParserOptions,
) -> Option<ReferenceLabelContext> {
    use panache_parser::parser::inlines::links::{LinkScanContext, try_parse_reference_link};

    // The token to the left keeps an EOF cursor and an empty second bracket
    // attached to the prose the user is editing.
    let node = root
        .token_at_offset(rowan::TextSize::try_from(offset).ok()?)
        .left_biased()?
        .parent()?;
    let container = reference_prose_container(&node)?;
    for ancestor in node.ancestors() {
        let reference = if let Some(link) = Link::cast(ancestor.clone()) {
            link.reference()
        } else if let Some(image) = ImageLink::cast(ancestor.clone()) {
            image.reference()
        } else if UnresolvedReference::can_cast(ancestor.kind()) {
            ancestor.children().find_map(LinkRef::cast)
        } else {
            continue;
        };
        if let Some(reference) = reference {
            let range = reference.syntax().text_range();
            let start = usize::from(range.start());
            let end = usize::from(range.end());
            if start <= offset && offset <= end && !text[start..end].contains(['\r', '\n', '[']) {
                return Some(ReferenceLabelContext {
                    query: normalize_label(&text[start..offset]),
                    range: start..end,
                    needs_close: false,
                });
            }
        }
    }

    // Unfinished references, and unresolved CommonMark references, need not
    // have a LinkRef node. Reuse the link scanner with a temporary closing
    // bracket, restricting the search to this inline container.
    let base = usize::from(container.text_range().start());
    let prefix = text.get(base..offset)?;
    let probe = format!("{prefix}]");
    for (relative, _) in prefix.match_indices('[').rev() {
        let start = base + relative;
        if escaped_bracket(text, start)
            || text[start + 1..].starts_with(['^', '@'])
            || text[start + 1..].starts_with("-@")
        {
            continue;
        }
        let Some((len, _, label, _, _)) = try_parse_reference_link(
            &probe[relative..],
            false,
            false,
            options.extensions.spaced_reference_links,
            LinkScanContext::from_options(options),
        ) else {
            continue;
        };
        if relative + len != probe.len() {
            continue;
        }
        let label_start = offset - label.len();
        if escaped_bracket(text, label_start - 1) || label.contains(['\r', '\n', '[']) {
            continue;
        }

        // A bracket inside code or an already complete link cannot start a
        // new reference merely because nearby source has the right shape.
        let opener = root
            .token_at_offset(rowan::TextSize::try_from(start).ok()?)
            .right_biased()?
            .parent()?;
        if reference_prose_container(&opener).is_none()
            || opener.ancestors().any(|ancestor| {
                Link::cast(ancestor.clone())
                    .is_some_and(|link| link.dest().is_some() || link.reference().is_some())
                    || ImageLink::cast(ancestor.clone())
                        .is_some_and(|image| image.dest().is_some() || image.reference().is_some())
            })
        {
            continue;
        }
        let line_end = text[offset..]
            .find(['\r', '\n'])
            .map_or(text.len(), |end| offset + end);
        let closing = text[offset..line_end]
            .find(['[', ']'])
            .map(|end| offset + end)
            .filter(|end| text.as_bytes()[*end] == b']');
        return Some(ReferenceLabelContext {
            query: normalize_label(&label),
            range: label_start..closing.unwrap_or(offset),
            needs_close: closing.is_none(),
        });
    }
    None
}

fn escaped_bracket(text: &str, offset: usize) -> bool {
    text.as_bytes()[..offset]
        .iter()
        .rev()
        .take_while(|byte| **byte == b'\\')
        .count()
        % 2
        != 0
}

fn reference_prose_container(node: &SyntaxNode) -> Option<SyntaxNode> {
    let mut container = None;
    for ancestor in node.ancestors() {
        let kind = ancestor.kind();
        if ReferenceDefinition::can_cast(kind)
            || CodeBlock::can_cast(kind)
            || CodeSpan::can_cast(kind)
            || InlineExecutable::can_cast(kind)
            || InlineMath::can_cast(kind)
            || DisplayMath::can_cast(kind)
            || TexBlock::can_cast(kind)
            || InlineHtml::can_cast(kind)
            || YamlMetadata::can_cast(kind)
            || Citation::can_cast(kind)
            || FootnoteReference::can_cast(kind)
            || LinkText::can_cast(kind)
            || ImageAlt::can_cast(kind)
            || LinkDest::can_cast(kind)
            || AutoLink::can_cast(kind)
            || WikiLink::can_cast(kind)
            || Shortcode::can_cast(kind)
            || AttributeNode::can_cast(kind)
            || matches!(kind, SyntaxKind::RAW_INLINE | SyntaxKind::HTML_BLOCK_RAW)
        {
            return None;
        }
        if container.is_none()
            && (Paragraph::can_cast(kind)
                || Plain::can_cast(kind)
                || HeadingContent::can_cast(kind)
                || LineBlockLine::can_cast(kind)
                || TableCell::can_cast(kind))
        {
            container = Some(ancestor);
        }
    }
    container
}

fn reference_label_items(
    root: &SyntaxNode,
    index: &crate::salsa::SymbolUsageIndex,
    line_index: &crate::lsp::line_index::LineIndex,
    ctx: ReferenceLabelContext,
) -> Vec<CompletionItem> {
    let range = Range::new(
        offset_to_position(line_index, ctx.range.start),
        offset_to_position(line_index, ctx.range.end),
    );
    let mut definitions: Vec<_> = index
        .reference_definition_entries()
        .flat_map(|(_, ranges)| ranges.iter().copied())
        .collect();
    definitions.sort_by_key(|range| range.start());
    let mut items = std::collections::BTreeMap::new();
    for definition_range in definitions {
        let Some(definition) = root
            .covering_element(definition_range)
            .into_node()
            .and_then(ReferenceDefinition::cast)
        else {
            continue;
        };
        let Some(label) = definition.link().and_then(|link| link.text()).map(|text| {
            text.raw_label()
                .replace("\r\n", " ")
                .replace(['\r', '\n'], " ")
        }) else {
            continue;
        };
        let key = normalize_label(&label);
        if key.is_empty() || !key.starts_with(&ctx.query) {
            continue;
        }
        items.entry(key).or_insert_with(|| CompletionItem {
            detail: definition.url(),
            kind: Some(CompletionItemKind::REFERENCE),
            filter_text: Some(label.clone()),
            text_edit: Some(CompletionTextEdit::Edit(TextEdit {
                range,
                new_text: if ctx.needs_close {
                    format!("{label}]")
                } else {
                    label.clone()
                },
            })),
            label,
            insert_text_format: Some(InsertTextFormat::PLAIN_TEXT),
            ..Default::default()
        });
    }
    items.into_values().collect()
}

/// Context for a cursor that sits inside an inline link or image destination.
struct LinkDestContext {
    is_image: bool,
    /// Text typed inside the destination, from the start of the URL up to the cursor.
    prefix: String,
}

fn link_dest_context(root: &SyntaxNode, text: &str, offset: usize) -> Option<LinkDestContext> {
    let starting = helpers::find_node_at_offset(root, offset)?;
    for ancestor in starting.ancestors() {
        let (is_image, dest): (bool, LinkDest) = if let Some(link) = Link::cast(ancestor.clone()) {
            (false, link.dest()?)
        } else if let Some(image) = ImageLink::cast(ancestor.clone()) {
            (true, image.dest()?)
        } else {
            continue;
        };
        let range = dest.syntax().text_range();
        let start: usize = range.start().into();
        let end: usize = range.end().into();
        if offset < start || offset > end {
            return None;
        }
        let prefix = text.get(start..offset)?.to_string();
        // Bail if the prefix isn't plausibly part of an inline URL (e.g. cursor
        // has crossed into the title portion `[text](url "title")`).
        if prefix.chars().any(|c| c.is_whitespace() || c == '"') {
            return None;
        }
        return Some(LinkDestContext { is_image, prefix });
    }
    None
}

/// Context for a cursor that sits inside the path argument of a
/// `{{< include | embed | video | placeholder >}}` shortcode.
struct ShortcodeArgContext {
    kind: ShortcodeKind,
    /// Value typed in the path argument so far (after `key=` and quote stripping).
    prefix: String,
}

impl ShortcodeKind {
    fn accepts(self, file_name: &str) -> bool {
        let exts: &[&str] = match self {
            Self::Include => INCLUDE_EXTENSIONS,
            Self::Embed => EMBED_EXTENSIONS,
            Self::Video => VIDEO_EXTENSIONS,
            Self::Placeholder => STILL_IMAGE_EXTENSIONS,
        };
        has_extension(file_name, exts)
    }
}

fn shortcode_arg_context(
    root: &SyntaxNode,
    text: &str,
    offset: usize,
) -> Option<ShortcodeArgContext> {
    let starting = helpers::find_node_at_offset(root, offset)?;
    let shortcode = starting
        .ancestors()
        .find_map(|ancestor| Shortcode::cast(ancestor.clone()))?;

    let content_node = shortcode
        .syntax()
        .children()
        .find(|child| child.kind() == SyntaxKind::SHORTCODE_CONTENT)?;
    let content_range = content_node.text_range();
    let content_start: usize = content_range.start().into();
    let content_end: usize = content_range.end().into();
    if offset < content_start || offset > content_end {
        return None;
    }
    let content_text = text.get(content_start..content_end)?;
    let rel = offset - content_start;

    let tokens = shortcode_tokens(content_text);
    if tokens.is_empty() {
        return None;
    }

    // First positional token is the shortcode name. Determine the active
    // token, treating whitespace/end-of-content as an empty next arg.
    let name_token = tokens.first().copied()?;
    let name_value_span = shortcode_token_value_span(content_text, name_token)?;
    let name = content_text
        .get(name_value_span.0..name_value_span.1)?
        .to_string();
    let kind = ShortcodeKind::from_name(&name)?;

    // Locate the token whose range contains `rel`, if any.
    let active_idx = tokens.iter().position(|&(s, e)| rel >= s && rel <= e);
    let (active_token, active_idx) = match active_idx {
        Some(0) => {
            // Cursor sits on the shortcode name itself; don't complete the name in v1.
            return None;
        }
        Some(i) => (tokens[i], i),
        None => {
            // Cursor is in whitespace or past the last token: start a new arg.
            (
                (rel.min(content_text.len()), rel.min(content_text.len())),
                tokens.len(),
            )
        }
    };

    // Skip named args (`key=value`) — v1 handles positional args only.
    if active_idx > 0 && token_is_named(content_text, active_token) {
        return None;
    }

    // Count positional tokens (no `=`) up to and including the active one.
    let positional_index = tokens
        .iter()
        .take(active_idx)
        .filter(|&&t| !token_is_named(content_text, t))
        .count();
    // Positional arg #1 (after the name at #0) is the path arg for all
    // four supported shortcodes; bail if the cursor is on a later
    // positional arg.
    if positional_index != 1 {
        return None;
    }

    // Reduce the active token to its value span (strips `key=` and surrounding quotes).
    let value_span = if active_token.0 == active_token.1 {
        active_token
    } else {
        shortcode_token_value_span(content_text, active_token)?
    };
    if rel < value_span.0 || rel > value_span.1 {
        return None;
    }

    let prefix = content_text.get(value_span.0..rel)?.to_string();

    // Out-of-scope prefixes: URLs and (for embed) the cell-id portion after `#`.
    if prefix.contains("://") {
        return None;
    }
    if matches!(kind, ShortcodeKind::Embed) && prefix.contains('#') {
        return None;
    }

    Some(ShortcodeArgContext { kind, prefix })
}

/// A normalized request to enumerate filesystem entries.
struct PathRequest {
    /// Directory whose entries to enumerate (already absolute).
    base_dir: PathBuf,
    /// Path prefix relative to `base_dir` (may contain `/` separators).
    effective_prefix: String,
    /// Decides whether a file entry should appear in the completion list.
    /// Directories always appear regardless.
    accept_file: Box<dyn Fn(&str) -> bool + Send + 'static>,
}

fn link_dest_path_request(ctx: &LinkDestContext, doc_path: Option<&Path>) -> Option<PathRequest> {
    let doc_dir = doc_path?.parent()?.to_path_buf();
    let first = ctx.prefix.chars().next();
    // Absolute paths, fragment-only anchors, and URLs are out of scope.
    if matches!(first, Some('/') | Some('#') | Some('<')) || ctx.prefix.contains("://") {
        return None;
    }
    let is_image = ctx.is_image;
    Some(PathRequest {
        base_dir: doc_dir,
        effective_prefix: ctx.prefix.clone(),
        accept_file: Box::new(move |name| {
            if is_image {
                has_extension(name, STILL_IMAGE_EXTENSIONS) || has_extension(name, VIDEO_EXTENSIONS)
            } else {
                true
            }
        }),
    })
}

fn shortcode_path_request(
    ctx: &ShortcodeArgContext,
    doc_path: Option<&Path>,
    workspace_root: Option<&Path>,
) -> Option<PathRequest> {
    let kind = ctx.kind;
    let (base_dir, effective_prefix) = if let Some(stripped) = ctx.prefix.strip_prefix('/') {
        (workspace_root?.to_path_buf(), stripped.to_string())
    } else {
        (doc_path?.parent()?.to_path_buf(), ctx.prefix.clone())
    };
    Some(PathRequest {
        base_dir,
        effective_prefix,
        accept_file: Box::new(move |name| kind.accepts(name)),
    })
}

fn path_completion_items(
    req: PathRequest,
    text: &str,
    offset: usize,
) -> Option<Vec<CompletionItem>> {
    let (subdir, name_prefix) = match req.effective_prefix.rsplit_once('/') {
        Some((before, after)) => (before.to_string(), after.to_string()),
        None => (String::new(), req.effective_prefix.clone()),
    };
    let target_dir = req.base_dir.join(&subdir);
    let accept = req.accept_file;

    let entries = read_dir_entries(&target_dir, &name_prefix, accept.as_ref());

    let name_start = offset.saturating_sub(name_prefix.len());
    let index = crate::lsp::line_index::LineIndex::new(text);
    let range = Range::new(
        offset_to_position(&index, name_start),
        offset_to_position(&index, offset),
    );

    let mut items: Vec<CompletionItem> = entries
        .into_iter()
        .map(|entry| {
            let new_text = if entry.is_dir {
                format!("{}/", entry.name)
            } else {
                entry.name.clone()
            };
            CompletionItem {
                label: new_text.clone(),
                kind: Some(if entry.is_dir {
                    CompletionItemKind::FOLDER
                } else {
                    CompletionItemKind::FILE
                }),
                filter_text: Some(new_text.clone()),
                text_edit: Some(CompletionTextEdit::Edit(TextEdit { range, new_text })),
                insert_text_format: Some(InsertTextFormat::PLAIN_TEXT),
                ..Default::default()
            }
        })
        .collect();

    items.truncate(MAX_PATH_COMPLETIONS);
    Some(items)
}

struct PathEntry {
    name: String,
    is_dir: bool,
}

fn read_dir_entries(
    dir: &Path,
    name_prefix: &str,
    accept_file: &(dyn Fn(&str) -> bool + Send + 'static),
) -> Vec<PathEntry> {
    let Ok(read) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    let prefix_lower = name_prefix.to_ascii_lowercase();
    let include_hidden = name_prefix.starts_with('.');

    let mut dirs: Vec<PathEntry> = Vec::new();
    let mut files: Vec<PathEntry> = Vec::new();

    for entry in read.flatten() {
        let name_os = entry.file_name();
        let Some(name) = name_os.to_str() else {
            continue;
        };
        if !include_hidden && name.starts_with('.') {
            continue;
        }
        if !name.to_ascii_lowercase().starts_with(&prefix_lower) {
            continue;
        }
        let Ok(metadata) = entry.metadata() else {
            continue;
        };
        if metadata.is_dir() {
            dirs.push(PathEntry {
                name: name.to_string(),
                is_dir: true,
            });
        } else if metadata.is_file() {
            if !accept_file(name) {
                continue;
            }
            files.push(PathEntry {
                name: name.to_string(),
                is_dir: false,
            });
        }
    }

    let cmp = |a: &PathEntry, b: &PathEntry| {
        a.name
            .to_ascii_lowercase()
            .cmp(&b.name.to_ascii_lowercase())
    };
    dirs.sort_by(cmp);
    files.sort_by(cmp);
    dirs.into_iter().chain(files).collect()
}

fn has_extension(name: &str, allowed: &[&str]) -> bool {
    let Some(dot) = name.rfind('.') else {
        return false;
    };
    let ext = name[dot + 1..].to_ascii_lowercase();
    allowed.contains(&ext.as_str())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn citation_query_prefix_basic_ascii() {
        // Cursor at end of "see @smith".
        assert_eq!(
            citation_query_prefix("see @smith", "see @smith".len()),
            Some("smith".to_string())
        );
    }

    #[test]
    fn citation_query_prefix_no_at_sign() {
        assert_eq!(citation_query_prefix("see smith", "see smith".len()), None);
    }

    #[test]
    fn citation_query_prefix_does_not_panic_inside_multibyte() {
        // Regression for #298: the look-back window start (`offset - 8`) must
        // not slice inside a multi-byte UTF-8 character. Here the cursor sits
        // at the end of three 3-byte CJK chars (9 bytes), so `offset - 8`
        // lands at byte 1, inside the first `あ` (bytes 0..3), and the old
        // `&text[start..offset]` panicked.
        let text = "あああ";
        assert_eq!(citation_query_prefix(text, text.len()), None);
    }

    #[test]
    fn citation_query_prefix_finds_query_after_multibyte() {
        // `offset - 8` lands inside the first `あ`; flooring to a char boundary
        // keeps the `@fig` query reachable instead of crashing or losing it.
        let text = "ああ@fig";
        assert_eq!(
            citation_query_prefix(text, text.len()),
            Some("fig".to_string())
        );
    }
}