panache 3.4.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
//! Code block concatenation for external linter invocation.
//!
//! This module provides utilities to concatenate code blocks with blank line
//! preservation for accurate position mapping in diagnostics.

use crate::utils::CodeBlock;

/// Mapping information for a code block in the concatenated file.
#[derive(Debug, Clone)]
pub struct BlockMapping {
    /// Byte offset range in the concatenated file
    pub concatenated_range: std::ops::Range<usize>,
    /// Byte offset range in the original document
    pub original_range: std::ops::Range<usize>,
    /// Starting line number in both files (preserved by blank line padding)
    pub start_line: usize,
    /// Per content line: the line's start offset in the concatenated file
    /// paired with the offset of its first content byte in the original
    /// document. Block content is dedented (container prefixes stripped),
    /// so offsets must map line by line rather than by a single block-start
    /// delta; empty means the content is byte-identical to the original.
    pub line_offsets: Vec<(usize, usize)>,
}

/// Result of concatenating code blocks with mapping information.
#[derive(Debug, Clone)]
pub struct ConcatenatedBlocks {
    /// The concatenated content
    pub content: String,
    /// Mapping information for each block
    pub mappings: Vec<BlockMapping>,
}

/// Concatenate code blocks with blank line preservation and return mapping info.
///
/// Returns the concatenated string where each block appears at its original line number,
/// with blank lines filling the gaps, plus mapping information to convert offsets back.
pub fn concatenate_with_blanks_and_mapping(blocks: &[CodeBlock]) -> ConcatenatedBlocks {
    if blocks.is_empty() {
        return ConcatenatedBlocks {
            content: String::new(),
            mappings: Vec::new(),
        };
    }

    let mut content = String::new();
    let mut mappings = Vec::new();
    let mut current_line = 1;

    for block in blocks {
        // Add blank lines to reach the block's start line
        while current_line < block.start_line {
            content.push('\n');
            current_line += 1;
        }

        // Track the start of this block in the concatenated file
        let concat_start = content.len();

        // Add the block content
        content.push_str(&block.content);

        // Track the end of this block in the concatenated file
        let concat_end = content.len();

        // Pair each content line's concatenated start with the original
        // offset of its first content byte (past the container prefix).
        let mut line_offsets = Vec::with_capacity(block.line_starts.len());
        let mut line_start = concat_start;
        for (idx, line) in block.content.split_inclusive('\n').enumerate() {
            if let Some(&original) = block.line_starts.get(idx) {
                line_offsets.push((line_start, original));
            }
            line_start += line.len();
        }

        // Record the mapping
        mappings.push(BlockMapping {
            concatenated_range: concat_start..concat_end,
            original_range: block.original_range.clone(),
            start_line: block.start_line,
            line_offsets,
        });

        // Update current line based on how many lines we just added
        let lines_added = block.content.lines().count().max(1);
        current_line += lines_added;

        // Add trailing newline if block doesn't end with one
        if !block.content.ends_with('\n') {
            content.push('\n');
            current_line += 1;
        }
    }

    ConcatenatedBlocks { content, mappings }
}

/// Concatenate code blocks with blank line preservation.
///
/// Returns the concatenated string where each block appears at its original line number,
/// with blank lines filling the gaps.
pub fn concatenate_with_blanks(blocks: &[CodeBlock]) -> String {
    concatenate_with_blanks_and_mapping(blocks).content
}

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

    #[test]
    fn test_collect_single_r_block() {
        let input = r#"# Test

```r
x <- 1
y <- 2
```
"#;

        let tree = parse(input, None);
        let blocks = collect_code_blocks(&tree, input);

        assert_eq!(blocks.len(), 1);
        assert!(blocks.contains_key("r"));

        let r_blocks = &blocks["r"];
        assert_eq!(r_blocks.len(), 1);
        assert_eq!(r_blocks[0].language, "r");
        assert_eq!(r_blocks[0].content, "x <- 1\ny <- 2\n");
        assert_eq!(r_blocks[0].start_line, 4); // Content starts on line 4, not fence line 3
    }

    #[test]
    fn test_collect_multiple_blocks_same_language() {
        let input = r#"```r
x <- 1
```

Text in between.

```r
y <- 2
```
"#;

        let tree = parse(input, None);
        let blocks = collect_code_blocks(&tree, input);

        assert_eq!(blocks.len(), 1);
        let r_blocks = &blocks["r"];
        assert_eq!(r_blocks.len(), 2);
        assert_eq!(r_blocks[0].start_line, 2); // Content on line 2, fence on line 1
        assert_eq!(r_blocks[1].start_line, 8); // Content on line 8, fence on line 7
    }

    #[test]
    fn test_collect_multiple_languages() {
        let input = r#"```python
print("hello")
```

```r
print("hello")
```
"#;

        let tree = parse(input, None);
        let blocks = collect_code_blocks(&tree, input);

        assert_eq!(blocks.len(), 2);
        assert!(blocks.contains_key("python"));
        assert!(blocks.contains_key("r"));
    }

    #[test]
    fn test_concatenate_with_blanks_single_block() {
        let blocks = vec![CodeBlock {
            language: "r".to_string(),
            content: "x <- 1\n".to_string(),
            start_line: 5,
            original_range: 100..107, // Dummy range for test
            line_starts: vec![100],
        }];

        let result = concatenate_with_blanks(&blocks);

        // Should have 4 blank lines (lines 1-4), then content at line 5
        let expected = "\n\n\n\nx <- 1\n";
        assert_eq!(result, expected);
    }

    #[test]
    fn test_concatenate_with_blanks_multiple_blocks() {
        let blocks = vec![
            CodeBlock {
                language: "r".to_string(),
                content: "x <- 1\n".to_string(),
                start_line: 2,
                original_range: 50..57,
                line_starts: vec![50],
            },
            CodeBlock {
                language: "r".to_string(),
                content: "y <- 2\n".to_string(),
                start_line: 6,
                original_range: 150..157,
                line_starts: vec![150],
            },
        ];

        let result = concatenate_with_blanks(&blocks);

        // Line 1: blank
        // Line 2: x <- 1
        // Lines 3-5: blank
        // Line 6: y <- 2
        let lines: Vec<&str> = result.lines().collect();
        assert_eq!(lines.len(), 6);
        assert_eq!(lines[0], ""); // Line 1 (blank)
        assert_eq!(lines[1], "x <- 1"); // Line 2
        assert_eq!(lines[2], ""); // Line 3
        assert_eq!(lines[3], ""); // Line 4
        assert_eq!(lines[4], ""); // Line 5
        assert_eq!(lines[5], "y <- 2"); // Line 6
    }

    #[test]
    fn test_concatenate_preserves_line_numbers() {
        let blocks = vec![
            CodeBlock {
                language: "r".to_string(),
                content: "a <- 1\n".to_string(),
                start_line: 10,
                original_range: 200..207,
                line_starts: vec![200],
            },
            CodeBlock {
                language: "r".to_string(),
                content: "b <- 2\n".to_string(),
                start_line: 20,
                original_range: 400..407,
                line_starts: vec![400],
            },
        ];

        let result = concatenate_with_blanks(&blocks);

        // Count total lines
        let line_count = result.lines().count();
        assert_eq!(line_count, 20);

        // Check that line 10 has "a <- 1"
        let line_10 = result.lines().nth(9).unwrap(); // 0-indexed
        assert_eq!(line_10, "a <- 1");

        // Check that line 20 has "b <- 2"
        let line_20 = result.lines().nth(19).unwrap();
        assert_eq!(line_20, "b <- 2");
    }

    #[test]
    fn test_offset_to_line() {
        let input = "line1\nline2\nline3\n";

        assert_eq!(offset_to_line(input, 0), 1); // Start of file
        assert_eq!(offset_to_line(input, 5), 1); // Before first \n
        assert_eq!(offset_to_line(input, 6), 2); // Start of line 2
        assert_eq!(offset_to_line(input, 12), 3); // Start of line 3
    }

    #[test]
    fn test_collect_blockquoted_block_dedents_prefix() {
        let input = "> ```python\n> x=1\n> y=2\n> ```\n";
        let tree = parse(input, None);
        let blocks = collect_code_blocks(&tree, input);

        let py_blocks = &blocks["python"];
        assert_eq!(py_blocks.len(), 1);
        assert_eq!(
            py_blocks[0].content, "x=1\ny=2\n",
            "container prefix bytes must not reach external tools"
        );
        assert_eq!(py_blocks[0].start_line, 2);
        assert_eq!(
            py_blocks[0].line_starts,
            vec![input.find("x=1").unwrap(), input.find("y=2").unwrap()]
        );
    }

    #[test]
    fn test_collect_list_item_block_dedents_indent() {
        let input = "- item\n\n  ```python\n  x=1\n  ```\n";
        let tree = parse(input, None);
        let blocks = collect_code_blocks(&tree, input);

        let py_blocks = &blocks["python"];
        assert_eq!(py_blocks.len(), 1);
        assert_eq!(py_blocks[0].content, "x=1\n");
        assert_eq!(py_blocks[0].line_starts, vec![input.find("x=1").unwrap()]);
    }

    #[test]
    fn test_mapping_maps_dedented_offsets_back_through_prefix() {
        let input = "> ```python\n> x=1\n> y=2\n> ```\n";
        let tree = parse(input, None);
        let blocks = collect_code_blocks(&tree, input);
        let result = concatenate_with_blanks_and_mapping(&blocks["python"]);

        // Line numbers are preserved: content starts on document line 2.
        let lines: Vec<&str> = result.content.lines().collect();
        assert_eq!(lines[1], "x=1");
        assert_eq!(lines[2], "y=2");

        // A tool offset inside the dedented view maps back past the `> `
        // prefix of its own line.
        let concat_y = result.content.find("y=2").unwrap();
        assert_eq!(
            crate::linter::external_linters::map_concatenated_offset_to_original(
                concat_y,
                &result.mappings
            ),
            Some(input.find("y=2").unwrap())
        );
        let concat_1 = result.content.find('1').unwrap();
        assert_eq!(
            crate::linter::external_linters::map_concatenated_offset_to_original(
                concat_1,
                &result.mappings
            ),
            Some(input.find('1').unwrap())
        );
    }

    #[test]
    fn test_quarto_style_braces() {
        // Quarto uses {r} instead of just r
        let input = r#"```{r}
x <- 1
```
"#;

        let config = Config {
            flavor: Flavor::Quarto,
            extensions: crate::config::Extensions::for_flavor(Flavor::Quarto),
            ..Default::default()
        };
        let tree = parse(input, Some(config));
        let blocks = collect_code_blocks(&tree, input);

        assert_eq!(blocks.len(), 1);
        assert!(blocks.contains_key("r"), "Should extract 'r' from '{{r}}'");

        let r_blocks = &blocks["r"];
        assert_eq!(r_blocks.len(), 1);
        assert_eq!(r_blocks[0].language, "r");
        assert_eq!(r_blocks[0].content, "x <- 1\n");
    }

    #[test]
    fn test_quarto_style_braces_with_options() {
        // Quarto supports {r label, echo=FALSE}
        let input = r#"```{r my-label, echo=FALSE}
x <- 1
```
"#;

        let config = Config {
            flavor: Flavor::Quarto,
            extensions: crate::config::Extensions::for_flavor(Flavor::Quarto),
            ..Default::default()
        };
        let tree = parse(input, Some(config));
        let blocks = collect_code_blocks(&tree, input);

        assert_eq!(blocks.len(), 1);
        assert!(
            blocks.contains_key("r"),
            "Should extract 'r' from '{{r my-label, echo=FALSE}}'"
        );

        let r_blocks = &blocks["r"];
        assert_eq!(r_blocks.len(), 1);
        assert_eq!(r_blocks[0].language, "r");
    }

    #[test]
    fn test_quarto_display_class_language_normalized() {
        let input = "```{.bash filename=\"Terminal\"}\necho hi\n```\n";
        let config = Config {
            flavor: Flavor::Quarto,
            extensions: crate::config::Extensions::for_flavor(Flavor::Quarto),
            ..Default::default()
        };
        let tree = parse(input, Some(config));
        let blocks = collect_code_blocks(&tree, input);

        assert!(blocks.contains_key("bash"));
        let bash_blocks = &blocks["bash"];
        assert_eq!(bash_blocks.len(), 1);
        assert_eq!(bash_blocks[0].language, "bash");
    }

    #[test]
    fn test_quarto_various_syntaxes() {
        let input = r#"```{r}
a <- 1
```

```{python}
b = 2
```

```{r chunk-label}
c <- 3
```

```{r chunk2, echo=FALSE}
d <- 4
```
"#;

        let config = Config {
            flavor: Flavor::Quarto,
            extensions: crate::config::Extensions::for_flavor(Flavor::Quarto),
            ..Default::default()
        };
        let tree = parse(input, Some(config));
        let blocks = collect_code_blocks(&tree, input);

        assert_eq!(blocks.len(), 2);
        assert!(blocks.contains_key("r"));
        assert!(blocks.contains_key("python"));

        let r_blocks = &blocks["r"];
        assert_eq!(r_blocks.len(), 3, "Should find all three R blocks");

        let py_blocks = &blocks["python"];
        assert_eq!(py_blocks.len(), 1);
    }

    #[test]
    fn test_concatenate_with_mapping() {
        let blocks = vec![
            CodeBlock {
                language: "r".to_string(),
                content: "x <- 1\n".to_string(),
                start_line: 2,
                original_range: 10..17, // Hypothetical original positions
                line_starts: vec![10],
            },
            CodeBlock {
                language: "r".to_string(),
                content: "y <- 2\n".to_string(),
                start_line: 6,
                original_range: 50..57,
                line_starts: vec![50],
            },
        ];

        let result = concatenate_with_blanks_and_mapping(&blocks);

        // Check content is correct
        let lines: Vec<&str> = result.content.lines().collect();
        assert_eq!(lines.len(), 6);
        assert_eq!(lines[1], "x <- 1"); // Line 2
        assert_eq!(lines[5], "y <- 2"); // Line 6

        // Check mappings
        assert_eq!(result.mappings.len(), 2);

        // First block mapping
        assert_eq!(result.mappings[0].start_line, 2);
        assert_eq!(result.mappings[0].original_range, 10..17);
        // In concatenated: "\n" (line 1) + "x <- 1\n" = offset 1 to 8
        assert_eq!(result.mappings[0].concatenated_range.start, 1);
        assert_eq!(result.mappings[0].concatenated_range.end, 8);

        // Second block mapping
        assert_eq!(result.mappings[1].start_line, 6);
        assert_eq!(result.mappings[1].original_range, 50..57);
        // In concatenated: 8 (after first) + "\n\n\n" (lines 3-5) = 11, then "y <- 2\n" = 11 to 18
        assert_eq!(result.mappings[1].concatenated_range.start, 11);
        assert_eq!(result.mappings[1].concatenated_range.end, 18);
    }
}