panache 2.41.1

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
use crate::config::Config;
use crate::linter::diagnostics::{Diagnostic, Location};
use crate::linter::rules::Rule;
use crate::syntax::SyntaxNode;

pub struct DuplicateReferencesRule;

impl Rule for DuplicateReferencesRule {
    fn name(&self) -> &str {
        "duplicate-reference-labels"
    }

    fn check(
        &self,
        tree: &SyntaxNode,
        input: &str,
        _config: &Config,
        _metadata: Option<&crate::metadata::DocumentMetadata>,
    ) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        // Check for duplicate reference definitions
        diagnostics.extend(check_duplicate_references(tree, input));
        diagnostics.extend(check_duplicate_crossref_labels(tree, input));

        // Check for duplicate footnote definitions
        diagnostics.extend(check_duplicate_footnotes(tree, input));

        diagnostics
    }
}

fn check_duplicate_references(tree: &SyntaxNode, input: &str) -> Vec<Diagnostic> {
    let mut diagnostics = Vec::new();
    let db = crate::salsa::SalsaDb::default();
    let extensions = crate::config::Extensions::default();
    let index = crate::salsa::symbol_usage_index_from_tree(&db, tree, &extensions);

    for (label, ranges) in index.reference_definition_entries() {
        if ranges.len() < 2 {
            continue;
        }
        let first_location = Location::from_range(ranges[0], input);
        for range in ranges.iter().skip(1) {
            let display = extract_definition_label(input, *range).unwrap_or_else(|| label.clone());
            diagnostics.push(Diagnostic::warning(
                Location::from_range(*range, input),
                "duplicate-reference-labels",
                format!(
                    "Duplicate reference label '[{}]' (first defined at line {})",
                    display, first_location.line
                ),
            ));
        }
    }

    diagnostics
}

fn check_duplicate_footnotes(tree: &SyntaxNode, input: &str) -> Vec<Diagnostic> {
    let mut diagnostics = Vec::new();
    let db = crate::salsa::SalsaDb::default();
    let extensions = crate::config::Extensions::default();
    let index = crate::salsa::symbol_usage_index_from_tree(&db, tree, &extensions);

    for (id, ranges) in index.footnote_definition_entries() {
        if ranges.len() < 2 {
            continue;
        }
        let first_location = Location::from_range(ranges[0], input);
        for range in ranges.iter().skip(1) {
            let display =
                extract_definition_label(input, *range).unwrap_or_else(|| format!("^{}", id));
            diagnostics.push(Diagnostic::warning(
                Location::from_range(*range, input),
                "duplicate-reference-labels",
                format!(
                    "Duplicate footnote ID '[^{}]' (first defined at line {})",
                    display.trim_start_matches('^'),
                    first_location.line
                ),
            ));
        }
    }

    diagnostics
}

fn extract_definition_label(input: &str, range: rowan::TextRange) -> Option<String> {
    let start: usize = range.start().into();
    let end: usize = range.end().into();
    let text = input.get(start..end)?;
    let open = text.find('[')?;
    let close = text[open + 1..].find(']')?;
    let label = &text[open + 1..open + 1 + close];
    if label.is_empty() {
        None
    } else {
        Some(label.to_string())
    }
}

fn check_duplicate_crossref_labels(tree: &SyntaxNode, input: &str) -> Vec<Diagnostic> {
    let mut diagnostics = Vec::new();
    let db = crate::salsa::SalsaDb::default();
    let extensions = crate::config::Extensions::default();
    let index = crate::salsa::symbol_usage_index_from_tree(&db, tree, &extensions);

    for (label, ranges) in index.crossref_declaration_entries() {
        if ranges.len() < 2 {
            continue;
        }

        let declaration_value_ranges = index
            .crossref_declaration_value_ranges(label)
            .cloned()
            .unwrap_or_default();
        let chunk_label_declaration_ranges = index
            .chunk_label_declaration_ranges(label)
            .cloned()
            .unwrap_or_default();

        // Cross-reference labels are case-sensitive in Quarto/Bookdown contexts.
        // The symbol index groups by normalized label for lookup features, so this
        // lint rule must compare raw declaration values to avoid false positives.
        if declaration_value_ranges.len() == ranges.len() {
            use std::collections::HashMap;

            let mut declarations_by_raw_label: HashMap<(String, bool), Vec<rowan::TextRange>> =
                HashMap::new();

            for (declaration_range, value_range) in
                ranges.iter().zip(declaration_value_ranges.iter())
            {
                let raw_label = range_text(input, *value_range).to_string();
                let is_chunk_label_declaration =
                    chunk_label_declaration_ranges.contains(declaration_range);
                declarations_by_raw_label
                    .entry((raw_label, is_chunk_label_declaration))
                    .or_default()
                    .push(*declaration_range);
            }

            for ((raw_label, _is_chunk_label_declaration), declaration_ranges) in
                declarations_by_raw_label
            {
                if declaration_ranges.len() < 2 {
                    continue;
                }
                let first_location = Location::from_range(declaration_ranges[0], input);
                for range in declaration_ranges.iter().skip(1) {
                    diagnostics.push(Diagnostic::warning(
                        Location::from_range(*range, input),
                        "duplicate-reference-labels",
                        format!(
                            "Duplicate cross-reference label '[{}]' (first defined at line {})",
                            raw_label, first_location.line
                        ),
                    ));
                }
            }
            continue;
        }

        // Fallback if declaration/value range alignment is unavailable.
        let first_location = Location::from_range(ranges[0], input);
        for range in ranges.iter().skip(1) {
            diagnostics.push(Diagnostic::warning(
                Location::from_range(*range, input),
                "duplicate-reference-labels",
                format!(
                    "Duplicate cross-reference label '[{}]' (first defined at line {})",
                    label, first_location.line
                ),
            ));
        }
    }

    diagnostics
}

fn range_text(input: &str, range: rowan::TextRange) -> &str {
    let start: usize = range.start().into();
    let end: usize = range.end().into();
    input.get(start..end).unwrap_or("")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{Config, Flavor};

    fn parse_and_lint(input: &str) -> Vec<Diagnostic> {
        let config = Config::default();
        // Use main parse function which now includes inline parsing
        let tree = crate::parser::parse(input, Some(config.clone()));

        let rule = DuplicateReferencesRule;
        rule.check(&tree, input, &config, None)
    }

    #[test]
    fn test_no_duplicates() {
        let input = r#"[ref1]: https://example.com
[ref2]: https://another.com
[ref3]: https://third.com
"#;
        let diagnostics = parse_and_lint(input);
        assert_eq!(diagnostics.len(), 0);
    }

    #[test]
    fn test_duplicate_reference_labels() {
        let input = r#"[ref1]: https://example.com
[ref1]: https://duplicate.com
"#;
        let diagnostics = parse_and_lint(input);
        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].code, "duplicate-reference-labels");
        assert!(diagnostics[0].message.contains("[ref1]"));
        assert!(diagnostics[0].message.contains("line 1"));
    }

    #[test]
    fn test_multiple_duplicates() {
        let input = r#"[ref1]: https://example.com
[ref1]: https://duplicate1.com
[ref2]: https://another.com
[ref1]: https://duplicate2.com
[ref2]: https://duplicate3.com
"#;
        let diagnostics = parse_and_lint(input);
        assert_eq!(diagnostics.len(), 3); // 2 duplicates of ref1, 1 duplicate of ref2
        assert!(
            diagnostics
                .iter()
                .all(|d| d.code == "duplicate-reference-labels")
        );
    }

    #[test]
    fn test_case_insensitive_matching() {
        let input = r#"[MyRef]: https://example.com
[myref]: https://duplicate.com
[MYREF]: https://another-duplicate.com
"#;
        let diagnostics = parse_and_lint(input);
        assert_eq!(diagnostics.len(), 2); // Second and third are duplicates of first
        let joined = diagnostics
            .iter()
            .map(|d| d.message.clone())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(joined.contains("[myref]"));
        assert!(joined.contains("[MYREF]"));
    }

    #[test]
    fn test_whitespace_normalization() {
        let input = r#"[my ref]: https://example.com
[my  ref]: https://duplicate.com
[my   ref]: https://another-duplicate.com
"#;
        let diagnostics = parse_and_lint(input);
        assert_eq!(diagnostics.len(), 2); // Extra whitespace should be normalized
    }

    #[test]
    fn test_duplicate_footnotes() {
        let input = r#"[^1]: First footnote
[^1]: Duplicate footnote
"#;
        let diagnostics = parse_and_lint(input);
        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].code, "duplicate-reference-labels");
        assert!(diagnostics[0].message.contains("[^1]"));
    }

    #[test]
    fn test_footnote_case_insensitive() {
        let input = r#"[^Note]: First footnote
[^note]: Duplicate footnote
[^NOTE]: Another duplicate
"#;
        let diagnostics = parse_and_lint(input);
        assert_eq!(diagnostics.len(), 2);
        let joined = diagnostics
            .iter()
            .map(|d| d.message.clone())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(joined.contains("[^note]"));
        assert!(joined.contains("[^NOTE]"));
    }

    #[test]
    fn test_mixed_references_and_footnotes() {
        let input = r#"[ref]: https://example.com
[ref]: https://duplicate.com

[^1]: Footnote content
[^1]: Duplicate footnote
"#;
        let diagnostics = parse_and_lint(input);
        assert_eq!(diagnostics.len(), 2); // One duplicate ref, one duplicate footnote
    }

    #[test]
    fn test_first_definition_not_flagged() {
        let input = r#"[ref]: https://example.com
[ref]: https://duplicate.com
"#;
        let diagnostics = parse_and_lint(input);
        // Only the second occurrence should be flagged
        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].location.line, 2);
    }

    #[test]
    fn test_duplicate_chunk_label_and_attribute_id() {
        let input = r#"See @fig-plot.

```{r}
#| label: fig-plot
plot(1:10)
```

```{r}
#| label: fig-plot
plot(1:10)
```
"#;
        let config = Config {
            flavor: Flavor::Quarto,
            extensions: crate::config::Extensions::for_flavor(Flavor::Quarto),
            ..Default::default()
        };
        let tree = crate::parser::parse(input, Some(config.clone()));
        let rule = DuplicateReferencesRule;
        let diagnostics = rule.check(&tree, input, &config, None);
        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].code, "duplicate-reference-labels");
        assert!(diagnostics[0].message.contains("fig-plot"));
    }

    #[test]
    fn test_crossref_chunk_labels_are_case_sensitive() {
        let input = r#"See @fig-foo and @fig-FOO.

```{r}
#| label: fig-foo
plot(1:10)
```

```{r}
#| label: fig-FOO
plot(1:10)
```
"#;
        let config = Config {
            flavor: Flavor::Quarto,
            extensions: crate::config::Extensions::for_flavor(Flavor::Quarto),
            ..Default::default()
        };
        let tree = crate::parser::parse(input, Some(config.clone()));
        let rule = DuplicateReferencesRule;
        let diagnostics = rule.check(&tree, input, &config, None);
        assert_eq!(diagnostics.len(), 0);
    }

    #[test]
    fn test_crossref_heading_ids_are_case_sensitive() {
        let input = r#"# Heading {#em}

A reference to [Heading](#em).

# Heading {#EM}

A reference to [Heading](#EM).
"#;
        let config = Config {
            flavor: Flavor::Pandoc,
            extensions: crate::config::Extensions::for_flavor(Flavor::Pandoc),
            ..Default::default()
        };
        let tree = crate::parser::parse(input, Some(config.clone()));
        let rule = DuplicateReferencesRule;
        let diagnostics = rule.check(&tree, input, &config, None);
        assert_eq!(diagnostics.len(), 0);
    }

    #[test]
    fn test_chunk_labels_do_not_conflict_with_heading_ids() {
        let input = r#"# A {#gammasim}

```{r}
#| label: gammasim
```
"#;
        let config = Config {
            flavor: Flavor::RMarkdown,
            extensions: crate::config::Extensions::for_flavor(Flavor::RMarkdown),
            ..Default::default()
        };
        let tree = crate::parser::parse(input, Some(config.clone()));
        let rule = DuplicateReferencesRule;
        let diagnostics = rule.check(&tree, input, &config, None);
        assert_eq!(diagnostics.len(), 0);
    }
}