panache 2.52.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
//! YAML frontmatter parsing with position tracking.

use std::path::Path;

use rowan::TextSize;

use super::{BibliographyInfo, BibliographyParse, DocumentMetadata, InlineReference};
use crate::bib;
use crate::syntax::{YamlBlockMap, YamlBlockMapValue, parse_yaml_document};

/// Errors that can occur during YAML parsing.
#[derive(Debug, Clone)]
pub enum YamlError {
    /// YAML frontmatter not found in document.
    NotFound(String),
    /// YAML syntax error.
    ParseError {
        message: String,
        line: u64,
        column: u64,
        byte_offset: Option<usize>,
    },
    /// Invalid YAML structure.
    StructureError(String),
}

impl std::fmt::Display for YamlError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotFound(msg) => write!(f, "YAML not found: {}", msg),
            Self::ParseError {
                message,
                line,
                column,
                ..
            } => {
                write!(f, "YAML parse error at {}:{}: {}", line, column, message)
            }
            Self::StructureError(msg) => write!(f, "Invalid YAML structure: {}", msg),
        }
    }
}

impl std::error::Error for YamlError {}

#[derive(Debug, Clone)]
struct ScalarValue {
    value: String,
    range: std::ops::Range<usize>,
}

/// Parse YAML frontmatter and extract metadata.
///
/// # Arguments
///
/// * `yaml_text` - The YAML content (without --- delimiters)
/// * `yaml_offset` - Byte offset of YAML content in the document
/// * `doc_path` - Path to the document (for resolving relative paths)
pub(super) fn parse_frontmatter(
    yaml_text: &str,
    yaml_offset: TextSize,
    doc_path: &Path,
) -> Result<DocumentMetadata, YamlError> {
    // Extract just the YAML content (strip delimiters)
    let yaml_content = strip_yaml_delimiters(yaml_text);
    let content_start = yaml_content_start_offset(yaml_text);
    let doc_base_offset = u32::from(yaml_offset) as usize + content_start;

    crate::yaml_engine::validate_yaml(&yaml_content).map_err(|err| {
        let content_byte_offset = err.offset().min(yaml_content.len());
        let (line, column) = byte_offset_to_line_col_1based(&yaml_content, content_byte_offset);
        YamlError::ParseError {
            message: err.message().to_string(),
            line: line as u64,
            column: column as u64,
            byte_offset: Some(doc_base_offset + content_byte_offset),
        }
    })?;

    // The structural validity gate above already produced any parse error;
    // here we only need the tree to extract values from.
    let map = parse_yaml_document(&yaml_content).and_then(|doc| doc.block_map());

    let title = map
        .as_ref()
        .and_then(|map| map_entry_value(map, "title"))
        .as_ref()
        .and_then(block_map_value_to_scalar);
    let bibliography_values = map
        .as_ref()
        .and_then(|map| map_entry_value(map, "bibliography"))
        .map(|value| block_map_value_to_scalar_list(&value))
        .unwrap_or_default();
    let bibliography = if bibliography_values.is_empty() {
        None
    } else {
        let doc_dir = doc_path.parent().unwrap_or_else(|| Path::new("."));
        let paths = bibliography_values
            .iter()
            .map(|entry| doc_dir.join(&entry.value))
            .collect();
        let source_ranges = bibliography_values
            .iter()
            .map(|entry| absolute_text_range(doc_base_offset, entry.range.start..entry.range.end))
            .collect();
        Some(BibliographyInfo {
            paths,
            source_ranges,
        })
    };

    let bibliography_parse = bibliography.as_ref().map(|info| {
        let index = bib::load_bibliography(&info.paths);
        BibliographyParse {
            parse_errors: index
                .errors
                .iter()
                .map(|error| error.message.clone())
                .collect(),
            index,
        }
    });
    let inline_references = map
        .as_ref()
        .and_then(|map| map_entry_value(map, "references"))
        .map(|value| extract_inline_references_from_yaml(&value, doc_base_offset, doc_path))
        .unwrap_or_default();

    Ok(DocumentMetadata {
        source_path: doc_path.to_path_buf(),
        bibliography,
        metadata_files: Vec::new(),
        bibliography_parse,
        inline_references,
        citations: super::CitationInfo { keys: Vec::new() },
        title: title.map(|entry| entry.value),
        raw_yaml: yaml_content.to_string(),
    })
}

fn map_entry_value(map: &YamlBlockMap, key: &str) -> Option<YamlBlockMapValue> {
    map.value_of(key)
}

fn block_map_value_to_scalar(value: &YamlBlockMapValue) -> Option<ScalarValue> {
    value.as_scalar().map(scalar_value)
}

fn block_map_value_to_scalar_list(value: &YamlBlockMapValue) -> Vec<ScalarValue> {
    if let Some(single) = value.as_scalar() {
        return vec![scalar_value(single)];
    }
    if let Some(seq) = value.as_flow_sequence() {
        return seq
            .items()
            .filter_map(|i| i.as_scalar())
            .map(scalar_value)
            .collect();
    }
    if let Some(seq) = value.as_block_sequence() {
        return seq
            .items()
            .filter_map(|i| i.as_scalar())
            .map(scalar_value)
            .collect();
    }
    Vec::new()
}

fn extract_inline_references_from_yaml(
    references: &YamlBlockMapValue,
    doc_base_offset: usize,
    doc_path: &Path,
) -> Vec<InlineReference> {
    let Some(seq) = references.as_block_sequence() else {
        return Vec::new();
    };
    seq.items()
        .filter_map(|item| {
            let map = item.as_block_map()?;
            let id = block_map_value_to_scalar(&map.value_of("id")?)?;
            Some(InlineReference {
                id: id.value,
                range: absolute_text_range(doc_base_offset, id.range),
                path: doc_path.to_path_buf(),
            })
        })
        .collect()
}

fn scalar_value(scalar: crate::syntax::YamlScalar) -> ScalarValue {
    let range = scalar.text_range();
    ScalarValue {
        value: scalar.value(),
        range: range.start().into()..range.end().into(),
    }
}

fn absolute_text_range(base_offset: usize, range: std::ops::Range<usize>) -> rowan::TextRange {
    rowan::TextRange::new(
        rowan::TextSize::from((base_offset + range.start) as u32),
        rowan::TextSize::from((base_offset + range.end) as u32),
    )
}

#[cfg(test)]
fn line_col_to_byte_offset_1based(input: &str, line: usize, column: usize) -> Option<usize> {
    if line == 0 || column == 0 {
        return None;
    }

    let mut offset = 0usize;
    let bytes = input.as_bytes();

    for (idx, text_line) in input.lines().enumerate() {
        let line_no = idx + 1;
        if line_no == line {
            let line_byte_offset = text_line
                .char_indices()
                .nth(column.saturating_sub(1))
                .map(|(byte, _)| byte)
                .unwrap_or(text_line.len());
            return Some(offset + line_byte_offset);
        }

        let line_end_offset = offset + text_line.len();
        let line_ending_len = if line_end_offset + 1 < input.len()
            && bytes[line_end_offset] == b'\r'
            && bytes[line_end_offset + 1] == b'\n'
        {
            2
        } else if line_end_offset < input.len() && bytes[line_end_offset] == b'\n' {
            1
        } else {
            0
        };

        offset += text_line.len() + line_ending_len;
    }

    if line == input.lines().count() + 1 && column == 1 {
        Some(offset)
    } else {
        None
    }
}

fn byte_offset_to_line_col_1based(input: &str, offset: usize) -> (usize, usize) {
    let mut line = 1usize;
    let mut line_start = 0usize;
    let mut i = 0usize;
    let bytes = input.as_bytes();
    let target = offset.min(input.len());

    while i < target {
        if bytes[i] == b'\n' {
            line += 1;
            line_start = i + 1;
        }
        i += 1;
    }
    let col = input[line_start..target].chars().count() + 1;
    (line, col)
}

fn yaml_content_start_offset(text: &str) -> usize {
    let Some(first) = text.lines().next() else {
        return 0;
    };
    if first.trim() != "---" {
        return 0;
    }
    if text[first.len()..].starts_with("\r\n") {
        first.len() + 2
    } else if text[first.len()..].starts_with('\n') {
        first.len() + 1
    } else {
        first.len()
    }
}

/// Strip YAML delimiters (---) from frontmatter text.
pub(super) fn strip_yaml_delimiters(text: &str) -> String {
    let lines: Vec<&str> = text.lines().collect();

    if lines.is_empty() {
        return text.to_string();
    }

    // Check if starts with ---
    let start_idx = if lines[0].trim() == "---" { 1 } else { 0 };

    // Check if ends with --- or ...
    let mut end_idx = lines.len();
    if end_idx > start_idx {
        let last_line = lines[end_idx - 1].trim();
        if last_line == "---" || last_line == "..." {
            end_idx -= 1;
        }
    }

    // Reconstruct the content
    lines[start_idx..end_idx].join("\n")
}

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

    #[test]
    fn test_strip_yaml_delimiters() {
        let input = "---\ntitle: Test\n---";
        let stripped = strip_yaml_delimiters(input);
        assert_eq!(stripped, "title: Test");
    }

    #[test]
    fn test_strip_yaml_delimiters_dots() {
        let input = "---\ntitle: Test\n...";
        let stripped = strip_yaml_delimiters(input);
        assert_eq!(stripped, "title: Test");
    }

    #[test]
    fn test_title_cooks_single_quoted_escaped_apostrophe() {
        // The in-tree wrappers cook quoted scalars (vs. the old naive
        // `trim_matches`), so a doubled single quote decodes to one apostrophe.
        let yaml = "---\ntitle: 'it''s a test'\n---";
        let metadata = parse_frontmatter(yaml, TextSize::from(0), Path::new("test.qmd")).unwrap();
        assert_eq!(metadata.title.as_deref(), Some("it's a test"));
    }

    #[test]
    fn test_parse_simple_frontmatter() {
        let yaml = "title: My Document\nauthor: John Doe";
        let result = parse_frontmatter(yaml, TextSize::from(0), Path::new("test.qmd"));
        assert!(result.is_ok());

        let metadata = result.unwrap();
        assert_eq!(metadata.title.as_deref(), Some("My Document"));
        assert!(metadata.citations.keys.is_empty());
    }

    #[test]
    fn test_parse_with_delimiters() {
        let yaml = "---\ntitle: My Document\n---";
        let result = parse_frontmatter(yaml, TextSize::from(0), Path::new("test.qmd"));
        assert!(result.is_ok());

        let metadata = result.unwrap();
        assert_eq!(metadata.title.as_deref(), Some("My Document"));
    }

    #[test]
    fn test_yaml_content_start_offset() {
        let yaml = "---\ntitle: Test\n---";
        assert_eq!(yaml_content_start_offset(yaml), 4);
    }

    #[test]
    fn test_yaml_content_start_offset_crlf() {
        let yaml = "---\r\ntitle: Test\r\n---";
        assert_eq!(yaml_content_start_offset(yaml), 5);
    }

    #[test]
    fn test_parse_error_includes_document_byte_offset() {
        let yaml = "---\ntitle: [\n---";
        let base = TextSize::from(10);
        let err = parse_frontmatter(yaml, base, Path::new("test.qmd")).expect_err("parse error");
        match err {
            YamlError::ParseError {
                line,
                column,
                byte_offset,
                ..
            } => {
                let local =
                    line_col_to_byte_offset_1based("title: [", line as usize, column as usize)
                        .unwrap_or("title: [".len());
                let expected = 10 + yaml_content_start_offset(yaml) + local;
                assert_eq!(byte_offset, Some(expected));
            }
            other => panic!("unexpected error: {:?}", other),
        }
    }

    #[test]
    fn test_string_or_array_single() {
        let yaml = "---\nbibliography: refs.bib\n---";
        let metadata = parse_frontmatter(yaml, TextSize::from(0), Path::new("test.qmd")).unwrap();
        let bib = metadata.bibliography.expect("bibliography");
        assert_eq!(bib.paths.len(), 1);
        assert!(bib.paths[0].ends_with("refs.bib"));
    }

    #[test]
    fn test_string_or_array_multiple() {
        let yaml = "---\nbibliography:\n  - refs.bib\n  - other.bib\n---";
        let metadata = parse_frontmatter(yaml, TextSize::from(0), Path::new("test.qmd")).unwrap();
        let bib = metadata.bibliography.expect("bibliography");
        assert_eq!(bib.paths.len(), 2);
        assert!(bib.paths[0].ends_with("refs.bib"));
        assert!(bib.paths[1].ends_with("other.bib"));
    }

    #[test]
    fn test_byte_offset_to_line_col_1based() {
        let input = "a\néx\n";
        assert_eq!(byte_offset_to_line_col_1based(input, 0), (1, 1));
        assert_eq!(byte_offset_to_line_col_1based(input, 2), (2, 1));
        assert_eq!(byte_offset_to_line_col_1based(input, 4), (2, 2));
    }
}