panache 2.43.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
use crate::config::Config;
#[cfg(feature = "lsp")]
use crate::external_formatters_common::{
    find_missing_formatter_commands, log_missing_formatter_commands,
};
use crate::external_formatters_sync;
use crate::syntax::{SyntaxKind, SyntaxNode, YamlFrontmatterRegion};
use panache_formatter::FormattedCodeMap;
use std::collections::HashMap;

fn to_formatter_config(config: &Config) -> panache_formatter::Config {
    let line_ending = config.line_ending.as_ref().map(|ending| match ending {
        crate::config::LineEnding::Auto => panache_formatter::LineEnding::Auto,
        crate::config::LineEnding::Lf => panache_formatter::LineEnding::Lf,
        crate::config::LineEnding::Crlf => panache_formatter::LineEnding::Crlf,
    });
    let math_delimiter_style = match config.math_delimiter_style {
        crate::config::MathDelimiterStyle::Preserve => {
            panache_formatter::MathDelimiterStyle::Preserve
        }
        crate::config::MathDelimiterStyle::Dollars => {
            panache_formatter::MathDelimiterStyle::Dollars
        }
        crate::config::MathDelimiterStyle::Backslash => {
            panache_formatter::MathDelimiterStyle::Backslash
        }
    };
    let tab_stops = match config.tab_stops {
        crate::config::TabStopMode::Normalize => panache_formatter::TabStopMode::Normalize,
        crate::config::TabStopMode::Preserve => panache_formatter::TabStopMode::Preserve,
    };
    let wrap = config.wrap.as_ref().map(|wrap| match wrap {
        crate::config::WrapMode::Preserve => panache_formatter::WrapMode::Preserve,
        crate::config::WrapMode::Reflow => panache_formatter::WrapMode::Reflow,
        crate::config::WrapMode::Sentence => panache_formatter::WrapMode::Sentence,
    });
    let blank_lines = match config.blank_lines {
        crate::config::BlankLines::Preserve => panache_formatter::BlankLines::Preserve,
        crate::config::BlankLines::Collapse => panache_formatter::BlankLines::Collapse,
    };
    let formatter_extensions = panache_formatter::config::FormatterExtensions {
        // Keep shared extension behavior aligned with parser-facing extensions.
        blank_before_header: config.extensions.blank_before_header,
        bookdown_references: config.extensions.bookdown_references,
        escaped_line_breaks: config.extensions.escaped_line_breaks,
        gfm_auto_identifiers: config.extensions.gfm_auto_identifiers,
        quarto_crossrefs: config.extensions.quarto_crossrefs,
        // Formatter-only smart toggles are owned separately.
        smart: config.formatter_extensions.smart,
        smart_quotes: config.formatter_extensions.smart_quotes,
    };

    let formatters: HashMap<String, Vec<panache_formatter::config::FormatterConfig>> = config
        .formatters
        .iter()
        .map(|(lang, entries)| {
            let mapped_entries = entries
                .iter()
                .map(|entry| panache_formatter::config::FormatterConfig {
                    cmd: entry.cmd.clone(),
                    args: entry.args.clone(),
                    enabled: entry.enabled,
                    stdin: entry.stdin,
                })
                .collect();
            (lang.clone(), mapped_entries)
        })
        .collect();

    panache_formatter::Config {
        flavor: config.flavor,
        parser_extensions: config.extensions.clone(),
        formatter_extensions,
        line_ending,
        line_width: config.line_width,
        math_indent: config.math_indent,
        math_delimiter_style,
        tab_stops,
        tab_width: config.tab_width,
        wrap,
        blank_lines,
        formatters,
        external_max_parallel: config.external_max_parallel,
        parser: config.parser,
    }
}

fn collect_yaml_frontmatter_region(tree: &SyntaxNode) -> Option<YamlFrontmatterRegion> {
    let frontmatter = tree
        .children()
        .find(|node| node.kind() != SyntaxKind::BLANK_LINE)
        .filter(|node| node.kind() == SyntaxKind::YAML_METADATA)?;

    let content = frontmatter
        .children()
        .find(|child| child.kind() == SyntaxKind::YAML_METADATA_CONTENT)?;

    let host_start: usize = frontmatter.text_range().start().into();
    let host_end: usize = frontmatter.text_range().end().into();
    let content_start: usize = content.text_range().start().into();
    let content_end: usize = content.text_range().end().into();

    Some(YamlFrontmatterRegion {
        id: format!("frontmatter:{}:{}", content_start, content_end),
        host_range: host_start..host_end,
        content_range: content_start..content_end,
        content: content.text().to_string(),
    })
}

#[cfg(feature = "lsp")]
async fn format_code_blocks_async(
    blocks: Vec<panache_formatter::ExternalCodeBlock>,
    config: &Config,
) -> FormattedCodeMap {
    use std::sync::Arc;
    use std::time::Duration;
    use tokio::sync::Semaphore;
    use tokio::task::JoinSet;

    let timeout = Duration::from_secs(30);
    let semaphore = Arc::new(Semaphore::new(config.external_max_parallel.max(1)));
    let missing_formatters = Arc::new(find_missing_formatter_commands(&config.formatters));
    log_missing_formatter_commands(&missing_formatters);

    let mut join_set = JoinSet::new();

    for block in blocks {
        let lang = block.language.clone();
        let Some(formatter_configs) = config.formatters.get(&lang) else {
            continue;
        };
        if formatter_configs.is_empty() {
            continue;
        }

        let permit = semaphore
            .clone()
            .acquire_owned()
            .await
            .expect("semaphore closed");

        let formatter_configs = formatter_configs.clone();
        let code = block.formatter_input.clone();
        let original = block.original.clone();
        let hashpipe_prefix = block.hashpipe_prefix.clone();
        let missing_formatters = Arc::clone(&missing_formatters);

        join_set.spawn(async move {
            let _permit = permit;
            let mut current_code = code;

            for (idx, formatter_cfg) in formatter_configs.iter().enumerate() {
                let formatter_cmd = formatter_cfg.cmd.trim();
                if formatter_cmd.is_empty() {
                    continue;
                }

                if missing_formatters.contains(formatter_cmd) {
                    return (lang, original, hashpipe_prefix, Ok(current_code));
                }

                log::debug!(
                    "Formatting {} code with {} ({}/{} in chain)",
                    lang,
                    formatter_cfg.cmd,
                    idx + 1,
                    formatter_configs.len()
                );

                match crate::external_formatters::format_code_async(
                    &current_code,
                    &lang,
                    formatter_cfg,
                    timeout,
                )
                .await
                {
                    Ok(formatted) => {
                        current_code = formatted;
                    }
                    Err(e) => {
                        eprintln!(
                            "Warning: {} formatter '{}' failed: {}. Using original code.",
                            lang, formatter_cfg.cmd, e
                        );
                        return (lang, original, hashpipe_prefix, Err(e));
                    }
                }
            }

            (lang, original, hashpipe_prefix, Ok(current_code))
        });
    }

    let mut formatted = FormattedCodeMap::new();

    while let Some(res) = join_set.join_next().await {
        if let Ok((lang, original_code, hashpipe_prefix, result)) = res {
            match result {
                Ok(formatted_code) => {
                    if formatted_code != original_code {
                        let combined = if let Some(prefix) = hashpipe_prefix {
                            format!("{}{}", prefix, formatted_code)
                        } else {
                            formatted_code
                        };
                        formatted.insert((lang, original_code), combined);
                    }
                }
                Err(e) => {
                    log::warn!("Failed to format code: {}", e);
                }
            }
        }
    }

    formatted
}

#[cfg(not(target_arch = "wasm32"))]
fn format_code_blocks_sync(
    blocks: Vec<panache_formatter::ExternalCodeBlock>,
    config: &Config,
) -> FormattedCodeMap {
    use std::time::Duration;
    let timeout = Duration::from_secs(30);
    external_formatters_sync::run_formatters_parallel(
        blocks,
        &config.formatters,
        timeout,
        config.external_max_parallel,
    )
}

#[cfg(target_arch = "wasm32")]
fn format_code_blocks_sync(
    _blocks: Vec<panache_formatter::ExternalCodeBlock>,
    _config: &Config,
) -> FormattedCodeMap {
    FormattedCodeMap::new()
}

#[cfg(feature = "lsp")]
pub async fn format_tree_async(
    tree: &SyntaxNode,
    config: &Config,
    range: Option<(usize, usize)>,
) -> String {
    log::info!(
        "Formatting document with config: line_width={}, wrap={:?}",
        config.line_width,
        config.wrap
    );

    let input = tree.text().to_string();
    let frontmatter_region = collect_yaml_frontmatter_region(tree);
    let formatter_config = to_formatter_config(config);
    #[cfg(not(target_arch = "wasm32"))]
    let frontmatter_yaml = frontmatter_region
        .as_ref()
        .map(|region| region.content.trim_end().to_string());

    let formatted_code = if !config.formatters.is_empty() {
        let code_blocks = panache_formatter::collect_code_blocks(tree, &input, &formatter_config);
        if !code_blocks.is_empty() {
            log::debug!(
                "Found {} code blocks, spawning formatters...",
                code_blocks.len()
            );
            format_code_blocks_async(code_blocks, config).await
        } else {
            FormattedCodeMap::new()
        }
    } else {
        FormattedCodeMap::new()
    };

    let yaml_config = config.clone();
    let formatted_yaml_future = frontmatter_yaml.clone().map(|yaml_content| {
        tokio::spawn(async move {
            crate::yaml_engine::format_yaml_with_config(&yaml_content, &yaml_config)
        })
    });

    let mut output =
        panache_formatter::formatter::Formatter::new(formatter_config, formatted_code, range)
            .format(tree);

    if let Some(handle) = formatted_yaml_future
        && let Ok(Ok(formatted_yaml)) = handle.await
    {
        let original_yaml = frontmatter_yaml.unwrap_or_default();
        log::debug!(
            "Applying formatted YAML: {} bytes -> {} bytes",
            original_yaml.len(),
            formatted_yaml.len()
        );
        if let Some(region) = frontmatter_region.as_ref()
            && let Some(replaced) = apply_formatted_yaml_at_range(
                &output,
                region,
                &format!("{}\n", formatted_yaml.trim_end()),
            )
        {
            output = replaced;
        } else {
            log::warn!("Skipping YAML apply: no valid frontmatter region range");
        }
    }

    log::info!("Formatting complete: {} bytes output", output.len());
    output.trim_end().to_string() + "\n"
}

pub fn format_tree(tree: &SyntaxNode, config: &Config, range: Option<(usize, usize)>) -> String {
    log::debug!(
        "Formatting document with config: line_width={}, wrap={:?}",
        config.line_width,
        config.wrap
    );

    let input = tree.text().to_string();
    let frontmatter_region = collect_yaml_frontmatter_region(tree);
    let formatter_config = to_formatter_config(config);
    #[cfg(not(target_arch = "wasm32"))]
    let frontmatter_yaml = frontmatter_region
        .as_ref()
        .map(|region| region.content.trim_end().to_string());

    let formatted_code = if !config.formatters.is_empty() {
        let code_blocks = panache_formatter::collect_code_blocks(tree, &input, &formatter_config);
        if !code_blocks.is_empty() {
            log::debug!(
                "Found {} code blocks, spawning formatters...",
                code_blocks.len()
            );
            format_code_blocks_sync(code_blocks, config)
        } else {
            FormattedCodeMap::new()
        }
    } else {
        FormattedCodeMap::new()
    };

    #[cfg(not(target_arch = "wasm32"))]
    let formatted_yaml = if let Some(yaml_content) = frontmatter_yaml.clone() {
        match crate::yaml_engine::format_yaml_with_config(&yaml_content, config) {
            Ok(formatted) if formatted != yaml_content => Some((yaml_content, formatted)),
            _ => None,
        }
    } else {
        None
    };

    #[cfg(target_arch = "wasm32")]
    let formatted_yaml: Option<(String, String)> = None;

    let mut output =
        panache_formatter::formatter::Formatter::new(formatter_config, formatted_code, range)
            .format(tree);

    if let Some((original_yaml, formatted_yaml)) = formatted_yaml {
        log::debug!(
            "Applying formatted YAML: {} bytes -> {} bytes",
            original_yaml.len(),
            formatted_yaml.len()
        );
        if let Some(region) = frontmatter_region.as_ref()
            && let Some(replaced) = apply_formatted_yaml_at_range(
                &output,
                region,
                &format!("{}\n", formatted_yaml.trim_end()),
            )
        {
            output = replaced;
        } else {
            log::warn!("Skipping YAML apply: no valid frontmatter region range");
        }
    }

    log::debug!("Formatting complete: {} bytes output", output.len());
    output.trim_end().to_string() + "\n"
}

fn apply_formatted_yaml_at_range(
    output: &str,
    region: &YamlFrontmatterRegion,
    formatted_yaml_with_trailing_newline: &str,
) -> Option<String> {
    if region.content_range.end > output.len()
        || region.content_range.start > region.content_range.end
    {
        return None;
    }
    let mut out = String::with_capacity(
        output.len() - (region.content_range.end - region.content_range.start)
            + formatted_yaml_with_trailing_newline.len(),
    );
    out.push_str(&output[..region.content_range.start]);
    out.push_str(formatted_yaml_with_trailing_newline);
    out.push_str(&output[region.content_range.end..]);
    Some(out)
}