panache 2.47.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
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
//! Common types and utilities for external formatter integration.

use std::collections::{HashMap, HashSet};
use std::sync::{Mutex, OnceLock};

use crate::config::FormatterConfig;
use crate::external_tools_common::{find_missing_commands, missing_commands_warning_message};

static MISSING_FORMATTER_MESSAGES_LOGGED: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();

#[derive(Debug, Clone, Copy)]
pub enum FormatterIoMode {
    Stdin,
    File,
}

impl FormatterIoMode {
    fn as_str(self) -> &'static str {
        match self {
            Self::Stdin => "stdin",
            Self::File => "file",
        }
    }
}

/// Errors that can occur when invoking external formatters.
#[derive(Debug)]
pub enum FormatterError {
    /// Formatter command not found or failed to spawn
    SpawnFailed(String),
    /// Formatter process exited with non-zero status
    NonZeroExit { code: i32, stderr: String },
    /// Formatter timed out
    Timeout,
    /// I/O error during communication with formatter
    IoError(std::io::Error),
}

impl std::fmt::Display for FormatterError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::SpawnFailed(cmd) => write!(f, "failed to spawn formatter: {}", cmd),
            Self::NonZeroExit { code, stderr } => {
                write!(f, "formatter exited with code {}: {}", code, stderr)
            }
            Self::Timeout => write!(f, "formatter timed out"),
            Self::IoError(e) => write!(f, "formatter I/O error: {}", e),
        }
    }
}

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

impl From<std::io::Error> for FormatterError {
    fn from(e: std::io::Error) -> Self {
        Self::IoError(e)
    }
}

/// Find external formatter commands that are configured but unavailable.
#[cfg(not(target_arch = "wasm32"))]
pub fn find_missing_formatter_commands(
    formatters: &HashMap<String, Vec<FormatterConfig>>,
) -> HashSet<String> {
    find_missing_commands(
        formatters
            .values()
            .flat_map(|configs| configs.iter().map(|cfg| cfg.cmd.as_str())),
    )
}

/// WASM has no external formatter execution.
#[cfg(target_arch = "wasm32")]
pub fn find_missing_formatter_commands(
    _formatters: &HashMap<String, Vec<FormatterConfig>>,
) -> HashSet<String> {
    HashSet::new()
}

/// Log one consolidated info message for missing external formatter commands.
///
/// Missing commands are a common optional configuration scenario and should not
/// emit warnings by default. We log once at info level so release builds can
/// still surface actionable diagnostics without warning noise.
pub fn log_missing_formatter_commands(missing: &HashSet<String>) {
    let Some(message) = missing_formatter_warning_message(missing) else {
        return;
    };

    let logged_messages =
        MISSING_FORMATTER_MESSAGES_LOGGED.get_or_init(|| Mutex::new(HashSet::new()));
    let mut logged = logged_messages
        .lock()
        .expect("missing formatter message mutex poisoned");
    if !logged.insert(message.clone()) {
        return;
    }

    log::info!("{}", message);
}

/// Substitute the supported placeholders inside a single arg string.
///
/// - `{}`     → `brace_value` (file path in file mode, virtual stdin filename
///   in stdin mode).
/// - `{lang}` → the literal language string from the code fence.
/// - `{ext}`  → the file extension corresponding to the language via
///   [`temp_file_extension_for_language`]. Unknown languages fall back to
///   `txt`.
fn substitute_placeholders(arg: &str, brace_value: &str, language: &str) -> String {
    arg.replace("{lang}", language)
        .replace("{ext}", temp_file_extension_for_language(language))
        .replace("{}", brace_value)
}

/// Resolve stdin argument placeholders against a language-aware virtual filename.
///
/// Some tools (for example Prettier) need a file path hint while still reading
/// from stdin. Supports `{}` (virtual stdin filename), `{lang}`, and `{ext}`.
pub fn resolve_stdin_args(args: &[String], language: &str) -> Vec<String> {
    let virtual_filename = virtual_filename_for_language(language);
    args.iter()
        .map(|arg| substitute_placeholders(arg, &virtual_filename, language))
        .collect()
}

/// Resolve file-mode argument placeholders against a real temp file path.
///
/// Supports `{}` (file path), `{lang}`, and `{ext}`. Preserves the documented
/// behavior that, when no `{}` placeholder is present, the file path is
/// appended at the end of the resolved args. `{lang}`/`{ext}` are substituted
/// in either case.
pub fn resolve_file_args(args: &[String], language: &str, file_path: &str) -> Vec<String> {
    let has_brace = args.iter().any(|arg| arg.contains("{}"));
    let mut resolved: Vec<String> = args
        .iter()
        .map(|arg| substitute_placeholders(arg, file_path, language))
        .collect();
    if !has_brace {
        resolved.push(file_path.to_string());
    }
    resolved
}

pub fn log_formatter_invocation(
    command: &str,
    language: &str,
    mode: FormatterIoMode,
    args: &[String],
) {
    log::debug!(
        "External formatter start: cmd='{}', language='{}', mode='{}', args={}",
        command,
        language,
        mode.as_str(),
        args.len()
    );
    log::trace!("External formatter args ({}): {:?}", command, args);
}

pub fn log_formatter_spawn_failed(
    command: &str,
    language: &str,
    mode: FormatterIoMode,
    error: &std::io::Error,
) {
    if error.kind() == std::io::ErrorKind::NotFound {
        log::debug!(
            "External formatter unavailable: cmd='{}', language='{}', mode='{}', error={}",
            command,
            language,
            mode.as_str(),
            error
        );
    } else {
        log::warn!(
            "External formatter spawn failed: cmd='{}', language='{}', mode='{}', error={}",
            command,
            language,
            mode.as_str(),
            error
        );
    }
}

pub fn log_formatter_nonzero_exit(
    command: &str,
    language: &str,
    mode: FormatterIoMode,
    exit_code: i32,
    stderr: &str,
) {
    let summary = stderr.lines().next().unwrap_or("").trim();
    log::warn!(
        "External formatter failed: cmd='{}', language='{}', mode='{}', exit_code={}, stderr='{}'",
        command,
        language,
        mode.as_str(),
        exit_code,
        summary
    );
    log::trace!("External formatter stderr ({}): {}", command, stderr);
}

pub fn log_formatter_timeout(command: &str, language: &str, mode: FormatterIoMode) {
    log::warn!(
        "External formatter timed out: cmd='{}', language='{}', mode='{}'",
        command,
        language,
        mode.as_str()
    );
}

pub fn log_formatter_success(
    command: &str,
    language: &str,
    mode: FormatterIoMode,
    output_len: usize,
    elapsed: std::time::Duration,
) {
    log::debug!(
        "External formatter succeeded: cmd='{}', language='{}', mode='{}', output_bytes={}, elapsed_ms={}",
        command,
        language,
        mode.as_str(),
        output_len,
        elapsed.as_millis()
    );
}

pub(crate) fn temp_file_extension_for_language(language: &str) -> &'static str {
    match normalized_language(language).as_str() {
        "javascript" | "js" => "js",
        "typescript" | "ts" => "ts",
        "jsx" => "jsx",
        "tsx" => "tsx",
        "json" => "json",
        "jsonc" => "jsonc",
        "yaml" | "yml" => "yaml",
        "markdown" | "md" | "qmd" | "rmd" => "md",
        "css" => "css",
        "scss" => "scss",
        "less" => "less",
        "html" => "html",
        "vue" => "vue",
        "svelte" => "svelte",
        "graphql" | "gql" => "graphql",
        "r" => "r",
        "python" | "py" => "py",
        "rust" | "rs" => "rs",
        "go" => "go",
        "bash" | "sh" | "zsh" => "sh",
        "c" => "c",
        "cpp" | "c++" | "cxx" => "cpp",
        "csharp" | "c-sharp" | "cs" => "cs",
        "java" => "java",
        "kotlin" | "kt" => "kt",
        "ruby" | "rb" => "rb",
        "swift" => "swift",
        "php" => "php",
        "lua" => "lua",
        "perl" | "pl" => "pl",
        "elixir" | "ex" => "exs",
        "haskell" | "hs" => "hs",
        "scala" => "scala",
        "julia" | "jl" => "jl",
        "ocaml" | "ml" => "ml",
        "clojure" | "clj" => "clj",
        "dart" => "dart",
        "zig" => "zig",
        "nix" => "nix",
        "toml" => "toml",
        "xml" => "xml",
        "sql" => "sql",
        "tex" | "latex" => "tex",
        "bibtex" | "bib" => "bib",
        "dockerfile" => "dockerfile",
        "makefile" => "makefile",
        _ => "txt",
    }
}

fn virtual_filename_for_language(language: &str) -> String {
    format!("stdin.{}", temp_file_extension_for_language(language))
}

fn normalized_language(language: &str) -> String {
    language.trim().to_ascii_lowercase().replace('_', "-")
}

fn missing_formatter_warning_message(missing: &HashSet<String>) -> Option<String> {
    missing_commands_warning_message(missing, "formatter", "formatting")
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::{
        find_missing_formatter_commands, missing_formatter_warning_message, resolve_file_args,
        resolve_stdin_args, substitute_placeholders, temp_file_extension_for_language,
    };
    use crate::config::FormatterConfig;
    use std::collections::{HashMap, HashSet};

    #[test]
    fn reports_missing_commands_once() {
        let mut formatters = HashMap::new();
        formatters.insert(
            "python".to_string(),
            vec![
                FormatterConfig {
                    cmd: "definitely-not-a-real-formatter-123".to_string(),
                    args: vec![],
                    enabled: true,
                    stdin: true,
                },
                FormatterConfig {
                    cmd: "definitely-not-a-real-formatter-123".to_string(),
                    args: vec![],
                    enabled: true,
                    stdin: true,
                },
            ],
        );

        let missing = find_missing_formatter_commands(&formatters);
        assert_eq!(missing.len(), 1);
        assert!(missing.contains("definitely-not-a-real-formatter-123"));
    }

    #[test]
    fn skips_empty_commands() {
        let mut formatters = HashMap::new();
        formatters.insert(
            "python".to_string(),
            vec![FormatterConfig {
                cmd: "   ".to_string(),
                args: vec![],
                enabled: true,
                stdin: true,
            }],
        );

        let missing = find_missing_formatter_commands(&formatters);
        assert!(missing.is_empty());
    }

    #[test]
    fn warning_message_sorts_and_deduplicates_commands() {
        let missing = HashSet::from([
            "black".to_string(),
            "rustfmt".to_string(),
            "black".to_string(),
        ]);

        let message = missing_formatter_warning_message(&missing).expect("message expected");
        assert_eq!(
            message,
            "External formatter command(s) not found: black, rustfmt. Configured external formatting for these tools will be skipped."
        );
    }

    #[test]
    fn resolve_stdin_args_replaces_placeholder_with_language_filename() {
        let args = vec!["--stdin-filepath".to_string(), "{}".to_string()];
        let resolved = resolve_stdin_args(&args, "typescript");
        assert_eq!(
            resolved,
            vec!["--stdin-filepath".to_string(), "stdin.ts".to_string()]
        );
    }

    #[test]
    fn resolve_stdin_args_falls_back_for_unknown_language() {
        let args = vec!["--stdin-filepath".to_string(), "{}".to_string()];
        let resolved = resolve_stdin_args(&args, "unknownlang");
        assert_eq!(
            resolved,
            vec!["--stdin-filepath".to_string(), "stdin.txt".to_string()]
        );
    }

    #[test]
    fn temp_file_extension_is_language_aware() {
        assert_eq!(temp_file_extension_for_language("r"), "r");
        assert_eq!(temp_file_extension_for_language("TypeScript"), "ts");
        assert_eq!(temp_file_extension_for_language("unknownlang"), "txt");

        // Expanded mappings.
        assert_eq!(temp_file_extension_for_language("python"), "py");
        assert_eq!(temp_file_extension_for_language("py"), "py");
        assert_eq!(temp_file_extension_for_language("Rust"), "rs");
        assert_eq!(temp_file_extension_for_language("bash"), "sh");
        assert_eq!(temp_file_extension_for_language("zsh"), "sh");
        assert_eq!(temp_file_extension_for_language("c++"), "cpp");
        assert_eq!(temp_file_extension_for_language("c_sharp"), "cs");
        assert_eq!(temp_file_extension_for_language("elixir"), "exs");
        assert_eq!(temp_file_extension_for_language("go"), "go");
        assert_eq!(temp_file_extension_for_language("LaTeX"), "tex");
    }

    #[test]
    fn substitute_placeholders_handles_lang() {
        let out = substitute_placeholders("--parser={lang}", "ignored", "python");
        assert_eq!(out, "--parser=python");
    }

    #[test]
    fn substitute_placeholders_handles_ext() {
        let out = substitute_placeholders("snippet.{ext}", "ignored", "rust");
        assert_eq!(out, "snippet.rs");
    }

    #[test]
    fn substitute_placeholders_handles_brace() {
        let out = substitute_placeholders("--path={}", "/tmp/foo.py", "python");
        assert_eq!(out, "--path=/tmp/foo.py");
    }

    #[test]
    fn substitute_placeholders_combines_all_three() {
        let out = substitute_placeholders(
            "--lang={lang} --file=stdin.{ext} --path={}",
            "/tmp/x",
            "python",
        );
        assert_eq!(out, "--lang=python --file=stdin.py --path=/tmp/x");
    }

    #[test]
    fn resolve_stdin_args_substitutes_lang_and_ext() {
        let args = vec![
            "fmt".to_string(),
            "--stdin".to_string(),
            "snippet.{ext}".to_string(),
            "--lang={lang}".to_string(),
        ];
        let resolved = resolve_stdin_args(&args, "python");
        assert_eq!(
            resolved,
            vec![
                "fmt".to_string(),
                "--stdin".to_string(),
                "snippet.py".to_string(),
                "--lang=python".to_string(),
            ]
        );
    }

    #[test]
    fn resolve_file_args_substitutes_brace_in_place() {
        let args = vec!["format".to_string(), "{}".to_string()];
        let resolved = resolve_file_args(&args, "python", "/tmp/x.py");
        assert_eq!(
            resolved,
            vec!["format".to_string(), "/tmp/x.py".to_string()]
        );
    }

    #[test]
    fn resolve_file_args_appends_path_when_brace_missing() {
        let args = vec!["format".to_string(), "--lang={lang}".to_string()];
        let resolved = resolve_file_args(&args, "rust", "/tmp/x.rs");
        assert_eq!(
            resolved,
            vec![
                "format".to_string(),
                "--lang=rust".to_string(),
                "/tmp/x.rs".to_string(),
            ]
        );
    }

    #[test]
    fn resolve_file_args_substitutes_lang_and_ext_with_brace() {
        let args = vec![
            "fmt".to_string(),
            "--lang={lang}".to_string(),
            "--ext={ext}".to_string(),
            "{}".to_string(),
        ];
        let resolved = resolve_file_args(&args, "python", "/tmp/x.py");
        assert_eq!(
            resolved,
            vec![
                "fmt".to_string(),
                "--lang=python".to_string(),
                "--ext=py".to_string(),
                "/tmp/x.py".to_string(),
            ]
        );
    }
}