Skip to main content

rumdl_lib/config/
types.rs

1use crate::discovery::PathAliases;
2use crate::types::LineLength;
3use globset::{Glob, GlobBuilder, GlobMatcher, GlobSet, GlobSetBuilder};
4use indexmap::IndexMap;
5use serde::{Deserialize, Serialize};
6use std::collections::{BTreeMap, HashSet};
7use std::fs;
8use std::io;
9use std::path::{Path, PathBuf};
10use std::sync::{Arc, OnceLock};
11
12use super::flavor::{MarkdownFlavor, normalize_key};
13
14/// Represents a rule-specific configuration
15#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, schemars::JsonSchema)]
16pub struct RuleConfig {
17    /// Severity override for this rule (Error, Warning, or Info)
18    #[serde(default, skip_serializing_if = "Option::is_none")]
19    pub severity: Option<crate::rule::Severity>,
20
21    /// Configuration values for the rule
22    #[serde(flatten)]
23    #[schemars(schema_with = "arbitrary_value_schema")]
24    pub values: BTreeMap<String, toml::Value>,
25}
26
27/// Generate a JSON schema for arbitrary configuration values
28fn arbitrary_value_schema(_gen: &mut schemars::SchemaGenerator) -> schemars::Schema {
29    schemars::json_schema!({
30        "type": "object",
31        "additionalProperties": true
32    })
33}
34
35/// Represents the complete configuration loaded from rumdl.toml
36#[derive(Debug, Clone, Serialize, Deserialize, Default, schemars::JsonSchema)]
37#[schemars(
38    description = "rumdl configuration for linting Markdown files. Rules can be configured individually using [MD###] sections with rule-specific options."
39)]
40pub struct Config {
41    /// Path to a base config file to inherit settings from.
42    /// Supports relative paths, absolute paths, `~/` for the home directory, and
43    /// `$VAR` / `${VAR}` environment-variable expansion (a literal `$` is written `$$`).
44    /// Example: `extends = "../base.rumdl.toml"` or `extends = "$GEM_PATH/base.rumdl.toml"`
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub extends: Option<String>,
47
48    /// Global configuration options
49    #[serde(default)]
50    pub global: GlobalConfig,
51
52    /// Per-file rule ignores: maps file patterns to lists of rules to ignore.
53    /// Patterns are relative to the project root; a leading `~/` expands to the
54    /// home directory and absolute paths are matched as written.
55    /// Example: { "README.md": ["MD033"], "docs/**/*.md": ["MD013"] }
56    #[serde(default, rename = "per-file-ignores")]
57    pub per_file_ignores: BTreeMap<String, Vec<String>>,
58
59    /// Per-file flavor overrides: maps file patterns to Markdown flavors.
60    /// Patterns are relative to the project root; a leading `~/` expands to the
61    /// home directory and absolute paths are matched as written.
62    /// Example: { "docs/**/*.md": MkDocs, "**/*.mdx": MDX }
63    /// Uses IndexMap to preserve config file order for "first match wins" semantics
64    #[serde(default, rename = "per-file-flavor")]
65    #[schemars(with = "BTreeMap<String, MarkdownFlavor>")]
66    pub per_file_flavor: IndexMap<String, MarkdownFlavor>,
67
68    /// Code block tools configuration for per-language linting and formatting
69    /// using external tools like ruff, prettier, shellcheck, etc.
70    #[serde(default, rename = "code-block-tools")]
71    pub code_block_tools: crate::code_block_tools::CodeBlockToolsConfig,
72
73    /// Rule-specific configurations (e.g., MD013, MD007, MD044)
74    /// Each rule section can contain options specific to that rule.
75    ///
76    /// Common examples:
77    /// - MD013: line_length, code_blocks, tables, headings
78    /// - MD007: indent
79    /// - MD003: style ("atx", "atx-closed", "setext")
80    /// - MD044: names (array of proper names to check)
81    ///
82    /// See <https://github.com/rvben/rumdl> for full rule documentation.
83    #[serde(flatten)]
84    pub rules: BTreeMap<String, RuleConfig>,
85
86    /// Rules holding at least one option value that came from a config file
87    /// whose contents may not be quoted back (an `extends` target, whose path
88    /// is arbitrary and whose text the extending project need not be able to
89    /// read). The values apply as written; only a message about one has to
90    /// leave it out.
91    ///
92    /// Granularity is the rule section, because that is what a rule's options
93    /// are deserialized as: an error names one value but not which key it came
94    /// from, so a section mixing an extended value with a directly named one
95    /// withholds both. Erring that way keeps a message from carrying text the
96    /// project never wrote.
97    ///
98    /// Provenance rather than configuration, so it stays out of the serialized
99    /// form and the JSON schema.
100    #[serde(skip)]
101    #[schemars(skip)]
102    pub withheld_rule_values: std::collections::BTreeSet<String>,
103
104    /// Project root directory, used for resolving relative paths in per-file-ignores
105    #[serde(skip)]
106    pub project_root: Option<std::path::PathBuf>,
107
108    #[serde(skip)]
109    #[schemars(skip)]
110    pub(super) per_file_ignores_cache: Arc<OnceLock<PerFileIgnoreCache>>,
111
112    #[serde(skip)]
113    #[schemars(skip)]
114    pub(super) per_file_flavor_cache: Arc<OnceLock<PerFileFlavorCache>>,
115
116    /// Lazily-computed canonical form of `project_root`.
117    ///
118    /// `normalize_match_path` needs the canonical project root to strip
119    /// prefixes from absolute file paths. Without this cache, every per-file
120    /// lookup would re-canonicalize the project root (one syscall per file).
121    ///
122    /// ## Invariants
123    ///
124    /// - **Single-shot**: computed once on first use of [`Config::canonical_project_root`].
125    /// - **Never invalidated**: callers must not mutate `project_root` after
126    ///   the first call. `Config` is treated as immutable post-construction
127    ///   (the same assumption as `per_file_ignores_cache` and `per_file_flavor_cache`).
128    /// - **Construction-time existence**: the cache stores `None` if
129    ///   `project_root` is unset, missing on disk, or otherwise can't be
130    ///   canonicalized. In practice `project_root` is set after walking up to
131    ///   `.git`, so the directory always exists at the time the cache is first
132    ///   read; if a caller sets `project_root` to a not-yet-existing path,
133    ///   the cache will permanently store `None`.
134    /// - **`Arc` wrapping**: `Config` derives `Clone`, and clones share the
135    ///   same `OnceLock` so a value computed by one clone is observable to all.
136    ///
137    /// `cwd` deliberately is NOT cached symmetrically: callers read it fresh
138    /// from `std::env::current_dir()` per call because tests (and embedding
139    /// hosts like LSP servers) may legitimately mutate the process cwd
140    /// between lookups.
141    #[serde(skip)]
142    #[schemars(skip)]
143    pub(super) canonical_project_root_cache: Arc<OnceLock<Option<PathBuf>>>,
144}
145
146impl PartialEq for Config {
147    fn eq(&self, other: &Self) -> bool {
148        self.global == other.global
149            && self.per_file_ignores == other.per_file_ignores
150            && self.per_file_flavor == other.per_file_flavor
151            && self.code_block_tools == other.code_block_tools
152            && self.rules == other.rules
153            && self.project_root == other.project_root
154    }
155}
156
157#[derive(Debug)]
158pub(super) struct PerFileIgnoreCache {
159    globset: GlobSet,
160    rules: Vec<Vec<String>>,
161    /// Whether any pattern is absolute, i.e. whether matching has to consider
162    /// the file's absolute path as well as its project-relative form.
163    has_absolute: bool,
164    /// Spellings of the file that absolute patterns reach through a symlink.
165    aliases: PathAliases,
166}
167
168#[derive(Debug)]
169pub(super) struct PerFileFlavorCache {
170    matchers: Vec<(GlobMatcher, MarkdownFlavor)>,
171    /// See [`PerFileIgnoreCache::has_absolute`].
172    has_absolute: bool,
173    /// See [`PerFileIgnoreCache::aliases`].
174    aliases: PathAliases,
175}
176
177/// The file's absolute path, for matching against absolute patterns, resolved
178/// whether or not the file exists yet. `None` when the caller has no absolute
179/// pattern to match (the common case, which must not pay for the resolution).
180fn absolute_match_path(file_path: &Path, has_absolute: bool) -> Option<PathBuf> {
181    if !has_absolute {
182        return None;
183    }
184    Some(crate::discovery::resolve_for_matching(file_path))
185}
186
187/// The file's other spellings, for matching against absolute patterns that
188/// named a location through a symlink (`/var/folders/**` on macOS, whose files
189/// canonicalize to `/private/var/folders/…`). Empty for the configurations that
190/// have no such pattern, which is nearly all of them.
191fn alias_match_paths(aliases: &PathAliases, absolute: Option<&Path>) -> Vec<String> {
192    match absolute {
193        Some(absolute) if !aliases.is_empty() => aliases.spellings_of(absolute),
194        _ => Vec::new(),
195    }
196}
197
198impl Config {
199    /// Check if the Markdown flavor is set to MkDocs
200    pub fn is_mkdocs_flavor(&self) -> bool {
201        self.global.flavor == MarkdownFlavor::MkDocs
202    }
203
204    // Future methods for when GFM and CommonMark are implemented:
205    // pub fn is_gfm_flavor(&self) -> bool
206    // pub fn is_commonmark_flavor(&self) -> bool
207
208    /// Get the configured Markdown flavor
209    pub fn markdown_flavor(&self) -> MarkdownFlavor {
210        self.global.flavor
211    }
212
213    /// Legacy method for backwards compatibility - redirects to is_mkdocs_flavor
214    pub fn is_mkdocs_project(&self) -> bool {
215        self.is_mkdocs_flavor()
216    }
217
218    /// Apply per-rule `enabled` config to the global enable/disable lists.
219    ///
220    /// For `[MD060] enabled = true`: adds the rule to `extend_enable` and
221    /// removes it from `disable` and `extend_disable`, ensuring the rule is active.
222    ///
223    /// For `[MD041] enabled = false`: adds the rule to `disable` and
224    /// removes it from `extend_enable`, ensuring the rule is inactive.
225    ///
226    /// Per-rule `enabled` takes precedence over global lists when there
227    /// is a conflict, since it represents a more specific intent.
228    pub fn apply_per_rule_enabled(&mut self) {
229        let mut to_enable: Vec<String> = Vec::new();
230        let mut to_disable: Vec<String> = Vec::new();
231
232        for (name, cfg) in &self.rules {
233            match cfg.values.get("enabled") {
234                Some(toml::Value::Boolean(true)) => {
235                    to_enable.push(name.clone());
236                }
237                Some(toml::Value::Boolean(false)) => {
238                    to_disable.push(name.clone());
239                }
240                _ => {}
241            }
242        }
243
244        for name in to_enable {
245            if !self.global.extend_enable.contains(&name) {
246                self.global.extend_enable.push(name.clone());
247            }
248            self.global.disable.retain(|n| n != &name);
249            self.global.extend_disable.retain(|n| n != &name);
250        }
251
252        for name in to_disable {
253            if !self.global.disable.contains(&name) {
254                self.global.disable.push(name.clone());
255            }
256            self.global.extend_enable.retain(|n| n != &name);
257        }
258    }
259
260    /// Get the severity override for a specific rule, if configured
261    pub fn get_rule_severity(&self, rule_name: &str) -> Option<crate::rule::Severity> {
262        self.rules.get(rule_name).and_then(|r| r.severity)
263    }
264
265    /// Return the canonical form of `project_root`, computed once and cached.
266    ///
267    /// Returns `None` if `project_root` is unset, doesn't exist on disk, or
268    /// otherwise cannot be canonicalized. Subsequent calls reuse the cached
269    /// value, eliminating the per-file `canonicalize()` syscall that
270    /// `normalize_match_path` would otherwise perform.
271    pub(super) fn canonical_project_root(&self) -> Option<&Path> {
272        self.canonical_project_root_cache
273            .get_or_init(|| {
274                self.project_root
275                    .as_deref()
276                    .and_then(crate::discovery::canonicalize_for_matching)
277            })
278            .as_deref()
279    }
280
281    /// Get the set of rules that should be ignored for a specific file based on per-file-ignores configuration
282    /// Returns a HashSet of rule names (uppercase, e.g., "MD033") that match the given file path
283    pub fn get_ignored_rules_for_file(&self, file_path: &Path) -> HashSet<String> {
284        let mut ignored_rules = HashSet::new();
285
286        if self.per_file_ignores.is_empty() {
287            return ignored_rules;
288        }
289
290        let cwd = std::env::current_dir().ok();
291        let path_for_matching = normalize_match_path(file_path, self.canonical_project_root(), cwd.as_deref());
292
293        let cache = self
294            .per_file_ignores_cache
295            .get_or_init(|| PerFileIgnoreCache::new(&self.per_file_ignores));
296
297        // Match the file path against all patterns, by its project-relative
298        // form and - for absolute patterns, including expanded `~` ones - by
299        // its absolute path and by the spellings of that path a pattern named
300        // through a symlink.
301        let absolute = absolute_match_path(file_path, cache.has_absolute);
302        let aliases = alias_match_paths(&cache.aliases, absolute.as_deref());
303        let matches = cache
304            .globset
305            .matches(path_for_matching.as_ref())
306            .into_iter()
307            .chain(absolute.iter().flat_map(|abs| cache.globset.matches(abs)))
308            .chain(aliases.iter().flat_map(|alias| cache.globset.matches(alias)));
309
310        for match_idx in matches {
311            if let Some(rules) = cache.rules.get(match_idx) {
312                for rule in rules {
313                    // Normalize rule names to uppercase (MD033, md033 -> MD033)
314                    ignored_rules.insert(rule.clone());
315                }
316            }
317        }
318
319        ignored_rules
320    }
321
322    /// Get the MarkdownFlavor for a specific file based on per-file-flavor configuration.
323    /// Returns the first matching pattern's flavor, or falls back to global flavor,
324    /// or auto-detects from extension, or defaults to Standard.
325    pub fn get_flavor_for_file(&self, file_path: &Path) -> MarkdownFlavor {
326        // If no per-file patterns, use fallback logic
327        if self.per_file_flavor.is_empty() {
328            return self.resolve_flavor_fallback(file_path);
329        }
330
331        let cwd = std::env::current_dir().ok();
332        let path_for_matching = normalize_match_path(file_path, self.canonical_project_root(), cwd.as_deref());
333
334        let cache = self
335            .per_file_flavor_cache
336            .get_or_init(|| PerFileFlavorCache::new(&self.per_file_flavor));
337
338        // Iterate in config order and return first match (IndexMap preserves order).
339        // Each pattern sees the file's project-relative form and - for absolute
340        // patterns, including expanded `~` ones - its absolute path and the
341        // spellings of that path a pattern named through a symlink.
342        let absolute = absolute_match_path(file_path, cache.has_absolute);
343        let aliases = alias_match_paths(&cache.aliases, absolute.as_deref());
344        for (matcher, flavor) in &cache.matchers {
345            if matcher.is_match(path_for_matching.as_ref())
346                || absolute.as_ref().is_some_and(|abs| matcher.is_match(abs))
347                || aliases.iter().any(|alias| matcher.is_match(alias))
348            {
349                return *flavor;
350            }
351        }
352
353        // No pattern matched, use fallback
354        self.resolve_flavor_fallback(file_path)
355    }
356
357    /// Fallback flavor resolution: global flavor → auto-detect → Standard
358    fn resolve_flavor_fallback(&self, file_path: &Path) -> MarkdownFlavor {
359        // If global flavor is explicitly set to non-Standard, use it
360        if self.global.flavor != MarkdownFlavor::Standard {
361            return self.global.flavor;
362        }
363        // Auto-detect from extension
364        MarkdownFlavor::from_path(file_path)
365    }
366
367    /// Canonicalize every rule-name list inside this `Config`.
368    ///
369    /// This is the single enforcement point for the runtime invariant:
370    /// **after a `Config` is fully built, every rule-name list contains
371    /// canonical rule IDs (`"MD033"`) — never aliases (`"no-inline-html"`).**
372    ///
373    /// The invariant lets every consumer (`rules::filter_rules`, the LSP,
374    /// WASM, fix coordinator, per-file-ignore lookups) match against
375    /// `Rule::name()` with simple string equality. Mutation boundaries
376    /// (`From<SourcedConfig> for Config`, LSP `apply_lsp_settings_*`, WASM
377    /// `to_config_with_warnings`) call this before handing the `Config` to
378    /// the linting pipeline.
379    ///
380    /// Covers `global.{enable,disable,extend_enable,extend_disable,fixable,unfixable}`
381    /// and the values of `per_file_ignores`. Idempotent.
382    pub fn canonicalize_rule_lists(&mut self) {
383        use super::registry::canonicalize_rule_list_in_place;
384        self.global.canonicalize_rule_lists();
385        for rules in self.per_file_ignores.values_mut() {
386            canonicalize_rule_list_in_place(rules);
387        }
388    }
389
390    /// Merge inline configuration overrides into a copy of this config
391    ///
392    /// This enables automatic inline config support - the engine can merge
393    /// inline overrides and recreate rules without any per-rule changes.
394    ///
395    /// Returns a new Config with the inline overrides merged in.
396    /// If there are no inline overrides, returns a clone of self.
397    pub fn merge_with_inline_config(&self, inline_config: &crate::inline_config::InlineConfig) -> Self {
398        let overrides = inline_config.get_all_rule_configs();
399        if overrides.is_empty() {
400            return self.clone();
401        }
402
403        let mut merged = self.clone();
404
405        for (rule_name, json_override) in overrides {
406            // Get or create the rule config entry
407            let rule_config = merged.rules.entry(rule_name.clone()).or_default();
408
409            // Merge JSON values into the rule's config
410            if let Some(obj) = json_override.as_object() {
411                for (key, value) in obj {
412                    // Normalize key to kebab-case for consistency
413                    let normalized_key = key.replace('_', "-");
414
415                    // Convert JSON value to TOML value
416                    if let Some(toml_value) = json_to_toml(value) {
417                        rule_config.values.insert(normalized_key, toml_value);
418                    }
419                }
420            }
421        }
422
423        merged
424    }
425}
426
427/// Normalize a file path for matching against a glob pattern from configuration.
428///
429/// Glob patterns in `per-file-ignores` and `per-file-flavor` are written relative
430/// to the project root (e.g. `docs/**/*.md`), and a glob is anchored at the start
431/// of the string it matches, so an absolute path like `/home/user/proj/docs/x.md`
432/// will not match `docs/**/*.md`. This helper produces the form the glob expects:
433///
434/// 1. **Relative path** → return as-is.
435/// 2. **Absolute path under `project_root`** → return path relative to `project_root`.
436/// 3. **Absolute path under `cwd`** → return path relative to `cwd`. This is the
437///    safety net for invocations where `project_root` could not be discovered
438///    (no `.git` upward, LSP/CLI calls outside a project) but the file still
439///    lives somewhere under the working directory.
440/// 4. **Anywhere else** → return the raw path. A relative glob simply won't
441///    match it, which is the desired outcome for files outside any known root.
442///
443/// An absolute path need not exist: an editor buffer or a file about to be
444/// created is resolved through its deepest existing ancestor (see
445/// [`crate::discovery::resolve_for_matching`]), so it matches the patterns it
446/// will match once written.
447///
448/// `canonical_project_root` is expected to already be canonical (via
449/// `Config::canonical_project_root`). `cwd` is canonicalized internally on each
450/// call since it is read fresh from the environment per invocation.
451pub(super) fn normalize_match_path<'a>(
452    file_path: &'a Path,
453    canonical_project_root: Option<&Path>,
454    cwd: Option<&Path>,
455) -> std::borrow::Cow<'a, Path> {
456    use std::borrow::Cow;
457
458    if file_path.is_relative() {
459        return Cow::Borrowed(file_path);
460    }
461
462    let canonical_file = crate::discovery::resolve_for_matching(file_path);
463
464    if let Some(root) = canonical_project_root
465        && let Ok(rel) = canonical_file.strip_prefix(root)
466    {
467        return Cow::Owned(rel.to_path_buf());
468    }
469
470    if let Some(working_dir) = cwd
471        && let Some(canonical_cwd) = crate::discovery::canonicalize_for_matching(working_dir)
472        && let Ok(rel) = canonical_file.strip_prefix(&canonical_cwd)
473    {
474        return Cow::Owned(rel.to_path_buf());
475    }
476
477    // Surface the silent fallback once per process at warn level so users with
478    // per-file glob configs notice when their patterns can't match a file.
479    // Subsequent occurrences stay at debug to avoid log spam.
480    static SILENT_FALLBACK_WARNED: OnceLock<()> = OnceLock::new();
481    log::log!(
482        first_call_warn_else_debug(&SILENT_FALLBACK_WARNED),
483        "{}",
484        format_silent_fallback_message(file_path, canonical_project_root, cwd),
485    );
486    Cow::Borrowed(file_path)
487}
488
489/// Returns [`log::Level::Warn`] the first time it is called with a given
490/// `latch`, and [`log::Level::Debug`] on every subsequent call. The latch
491/// is consumed by the first caller via `OnceLock::set`; later callers
492/// observe the latch as already set and downgrade.
493///
494/// Used to flag a fallback condition once per process without flooding
495/// logs when the same condition recurs (e.g. once per linted file).
496pub(super) fn first_call_warn_else_debug(latch: &OnceLock<()>) -> log::Level {
497    if latch.set(()).is_ok() {
498        log::Level::Warn
499    } else {
500        log::Level::Debug
501    }
502}
503
504/// Format the diagnostic emitted when [`normalize_match_path`] cannot
505/// relativise `file_path` against either the project root or the current
506/// working directory. Extracted so the exact wording can be asserted in
507/// tests without capturing log output.
508pub(super) fn format_silent_fallback_message(
509    file_path: &Path,
510    canonical_project_root: Option<&Path>,
511    cwd: Option<&Path>,
512) -> String {
513    format!(
514        "Per-file glob patterns will not match {}: file is outside project_root ({}) and cwd ({})",
515        file_path.display(),
516        DisplayPathOrUnset(canonical_project_root),
517        DisplayPathOrUnset(cwd),
518    )
519}
520
521/// Display adapter for `Option<&Path>` that renders the path via
522/// [`Path::display`] when present, or the literal `<unset>` when absent.
523/// Angle brackets follow Rust's diagnostic convention (e.g. `<unknown>`)
524/// and avoid double-paren rendering when the surrounding format string
525/// already wraps the value in `(…)`.
526struct DisplayPathOrUnset<'a>(Option<&'a Path>);
527
528impl std::fmt::Display for DisplayPathOrUnset<'_> {
529    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
530        match self.0 {
531            Some(path) => std::fmt::Display::fmt(&path.display(), f),
532            None => f.write_str("<unset>"),
533        }
534    }
535}
536
537/// Convert a serde_json::Value to a toml::Value
538pub(super) fn json_to_toml(json: &serde_json::Value) -> Option<toml::Value> {
539    match json {
540        serde_json::Value::Null => None,
541        serde_json::Value::Bool(b) => Some(toml::Value::Boolean(*b)),
542        serde_json::Value::Number(n) => n
543            .as_i64()
544            .map(toml::Value::Integer)
545            .or_else(|| n.as_f64().map(toml::Value::Float)),
546        serde_json::Value::String(s) => Some(toml::Value::String(s.clone())),
547        serde_json::Value::Array(arr) => {
548            let toml_arr: Vec<toml::Value> = arr.iter().filter_map(json_to_toml).collect();
549            Some(toml::Value::Array(toml_arr))
550        }
551        serde_json::Value::Object(obj) => {
552            let mut table = toml::map::Map::new();
553            for (k, v) in obj {
554                if let Some(tv) = json_to_toml(v) {
555                    table.insert(k.clone(), tv);
556                }
557            }
558            Some(toml::Value::Table(table))
559        }
560    }
561}
562
563impl PerFileIgnoreCache {
564    fn new(per_file_ignores: &BTreeMap<String, Vec<String>>) -> Self {
565        let mut builder = GlobSetBuilder::new();
566        let mut rules = Vec::new();
567
568        let mut has_absolute = false;
569        for (pattern, rules_list) in per_file_ignores {
570            let pattern = crate::discovery::expand_home_prefix(pattern);
571            has_absolute |= crate::discovery::has_absolute_spelling(&pattern);
572            if let Ok(glob) = Glob::new(&pattern) {
573                builder.add(glob);
574                // Canonicalize defensively: callers should have run
575                // Config::canonicalize_rule_lists already, but per-file-ignores
576                // has reached this cache directly from a few code paths
577                // historically, so we re-canonicalize here to keep the cache
578                // sound regardless of caller discipline.
579                rules.push(
580                    rules_list
581                        .iter()
582                        .map(|rule| super::registry::resolve_rule_name(rule))
583                        .collect(),
584                );
585            } else {
586                log::warn!("Invalid glob pattern in per-file-ignores: {pattern}");
587            }
588        }
589
590        let globset = builder.build().unwrap_or_else(|e| {
591            log::error!("Failed to build globset for per-file-ignores: {e}");
592            GlobSetBuilder::new().build().unwrap()
593        });
594
595        Self {
596            globset,
597            rules,
598            has_absolute,
599            aliases: PathAliases::new(per_file_ignores.keys().map(String::as_str)),
600        }
601    }
602}
603
604impl PerFileFlavorCache {
605    fn new(per_file_flavor: &IndexMap<String, MarkdownFlavor>) -> Self {
606        let mut matchers = Vec::new();
607
608        let mut has_absolute = false;
609        for (pattern, flavor) in per_file_flavor {
610            let pattern = crate::discovery::expand_home_prefix(pattern);
611            has_absolute |= crate::discovery::has_absolute_spelling(&pattern);
612            if let Ok(glob) = GlobBuilder::new(&pattern).literal_separator(true).build() {
613                matchers.push((glob.compile_matcher(), *flavor));
614            } else {
615                log::warn!("Invalid glob pattern in per-file-flavor: {pattern}");
616            }
617        }
618
619        Self {
620            matchers,
621            has_absolute,
622            aliases: PathAliases::new(per_file_flavor.keys().map(String::as_str)),
623        }
624    }
625}
626
627/// Global configuration options
628#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
629#[serde(default, rename_all = "kebab-case")]
630pub struct GlobalConfig {
631    /// Enabled rules
632    #[serde(default)]
633    pub enable: Vec<String>,
634
635    /// Disabled rules
636    #[serde(default)]
637    pub disable: Vec<String>,
638
639    /// Files to exclude. Glob patterns, relative to the project root; a
640    /// leading `~/` expands to the home directory and absolute paths are
641    /// matched as written.
642    #[serde(default)]
643    pub exclude: Vec<String>,
644
645    /// Files to include. Glob patterns, relative to the project root; a
646    /// leading `~/` expands to the home directory and absolute paths are
647    /// matched as written.
648    #[serde(default)]
649    pub include: Vec<String>,
650
651    /// Respect .gitignore, .ignore and git exclude files when scanning
652    /// directories. .markdownlintignore applies regardless, and explicitly
653    /// named files bypass both.
654    #[serde(default = "default_respect_gitignore", alias = "respect_gitignore")]
655    pub respect_gitignore: bool,
656
657    /// Global line length setting (used by MD013 and other rules if not overridden)
658    #[serde(default, alias = "line_length")]
659    pub line_length: LineLength,
660
661    /// Output format for linting results (e.g., "text", "json", "pylint", etc.)
662    #[serde(skip_serializing_if = "Option::is_none", alias = "output_format")]
663    pub output_format: Option<String>,
664
665    /// Rules that are allowed to be fixed when --fix is used
666    /// If specified, only these rules will be fixed
667    #[serde(default)]
668    pub fixable: Vec<String>,
669
670    /// Rules that should never be fixed, even when --fix is used
671    /// Takes precedence over fixable
672    #[serde(default)]
673    pub unfixable: Vec<String>,
674
675    /// Markdown flavor/dialect to use (mkdocs, gfm, commonmark, etc.)
676    /// When set, adjusts parsing and validation rules for that specific Markdown variant
677    #[serde(default)]
678    pub flavor: MarkdownFlavor,
679
680    /// \[DEPRECATED\] Whether to enforce exclude patterns for explicitly passed paths.
681    /// This option is deprecated as of v0.0.156 and has no effect.
682    /// Exclude patterns are now always respected, even for explicitly provided files.
683    /// This prevents duplication between rumdl config and tool configs like pre-commit.
684    #[serde(default, alias = "force_exclude")]
685    #[deprecated(since = "0.0.156", note = "Exclude patterns are now always respected")]
686    pub force_exclude: bool,
687
688    /// Directory to store cache files (default: .rumdl_cache).
689    /// A leading `~/` expands to the home directory; a relative path resolves
690    /// against the project root.
691    /// Can also be set via --cache-dir CLI flag or RUMDL_CACHE_DIR environment variable
692    #[serde(default, alias = "cache_dir", skip_serializing_if = "Option::is_none")]
693    pub cache_dir: Option<String>,
694
695    /// Whether caching is enabled (default: true)
696    /// Can also be disabled via --no-cache CLI flag
697    #[serde(default = "default_true")]
698    pub cache: bool,
699
700    /// Additional rules to enable on top of the base set (additive)
701    #[serde(default, alias = "extend_enable")]
702    pub extend_enable: Vec<String>,
703
704    /// Additional rules to disable on top of the base set (additive)
705    #[serde(default, alias = "extend_disable")]
706    pub extend_disable: Vec<String>,
707
708    /// Whether to read settings from `.editorconfig` files (default: false).
709    /// When enabled, the `.editorconfig` properties that map onto rumdl
710    /// settings fill in anything no rumdl config sets, resolved per file so
711    /// section globs and nested `.editorconfig` files apply as written.
712    #[serde(default)]
713    pub editorconfig: bool,
714
715    /// Whether the enable list was explicitly set (even if empty).
716    /// Used to distinguish "no enable list configured" from "enable list is empty"
717    /// (e.g., markdownlint `default: false` with no rules enabled).
718    #[serde(skip)]
719    pub enable_is_explicit: bool,
720
721    /// How to name the file that supplied [`Self::include`] when a message about
722    /// those patterns may not quote them (an `extends` target, whose path is
723    /// arbitrary and whose text the extending project need not be able to read),
724    /// and `None` when it may. Provenance rather than configuration, so it stays
725    /// out of the serialized form and the JSON schema.
726    #[serde(skip)]
727    pub include_withheld: Option<String>,
728}
729
730fn default_respect_gitignore() -> bool {
731    true
732}
733
734fn default_true() -> bool {
735    true
736}
737
738// Add the Default impl
739impl Default for GlobalConfig {
740    #[allow(deprecated)]
741    fn default() -> Self {
742        Self {
743            enable: Vec::new(),
744            disable: Vec::new(),
745            exclude: Vec::new(),
746            include: Vec::new(),
747            respect_gitignore: true,
748            line_length: LineLength::default(),
749            output_format: None,
750            fixable: Vec::new(),
751            unfixable: Vec::new(),
752            flavor: MarkdownFlavor::default(),
753            force_exclude: false,
754            cache_dir: None,
755            cache: true,
756            extend_enable: Vec::new(),
757            extend_disable: Vec::new(),
758            editorconfig: false,
759            enable_is_explicit: false,
760            include_withheld: None,
761        }
762    }
763}
764
765impl GlobalConfig {
766    /// Canonicalize every rule-name list in this `GlobalConfig`.
767    ///
768    /// Rewrites `enable`, `disable`, `extend_enable`, `extend_disable`, `fixable`,
769    /// and `unfixable` so that all entries are canonical rule IDs (`"MD033"`)
770    /// rather than aliases (`"no-inline-html"`). Duplicates are removed,
771    /// preserving first-occurrence order; the special `"all"` keyword is
772    /// preserved.
773    ///
774    /// This must be called by every code path that mutates a runtime
775    /// `Config`'s rule lists from external input (markdownlint configs,
776    /// `.rumdl.toml`, LSP `initializationOptions`, WASM bindings, etc.) so
777    /// that downstream consumers (`rules::filter_rules`, the LSP, WASM) can
778    /// match against `Rule::name()` with simple string equality.
779    pub fn canonicalize_rule_lists(&mut self) {
780        use super::registry::canonicalize_rule_list_in_place;
781        canonicalize_rule_list_in_place(&mut self.enable);
782        canonicalize_rule_list_in_place(&mut self.disable);
783        canonicalize_rule_list_in_place(&mut self.extend_enable);
784        canonicalize_rule_list_in_place(&mut self.extend_disable);
785        canonicalize_rule_list_in_place(&mut self.fixable);
786        canonicalize_rule_list_in_place(&mut self.unfixable);
787    }
788}
789
790/// Names of rumdl-native config files, searched in precedence order when
791/// walking up a directory tree.
792///
793/// This is the single source of truth for config discovery. Both the CLI
794/// (`SourcedConfig::discover_config_upward`, `discover_config_for_dir`) and
795/// the LSP (`RumdlLanguageServer::resolve_config_for_file`) must use this
796/// list; any deviation causes silent config-not-found bugs where the CLI
797/// recognises a config but the LSP does not (or vice versa).
798///
799/// See `src/lsp/tests.rs::test_lsp_cli_resolver_parity_on_fixtures` for
800/// the side-by-side resolver parity test that pins this invariant across
801/// several directory layouts.
802pub const RUMDL_CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", ".config/rumdl.toml", "pyproject.toml"];
803
804pub const MARKDOWNLINT_CONFIG_FILES: &[&str] = &[
805    ".markdownlint-cli2.jsonc",
806    ".markdownlint-cli2.yaml",
807    ".markdownlint-cli2.yml",
808    ".markdownlint.json",
809    ".markdownlint.jsonc",
810    ".markdownlint.yaml",
811    ".markdownlint.yml",
812    "markdownlint.json",
813    "markdownlint.jsonc",
814    "markdownlint.yaml",
815    "markdownlint.yml",
816];
817
818/// Create a default configuration file at the specified path
819pub fn create_default_config(path: &str) -> Result<(), ConfigError> {
820    create_preset_config("default", path)
821}
822
823/// Create a configuration file with a specific style preset
824pub fn create_preset_config(preset: &str, path: &str) -> Result<(), ConfigError> {
825    if Path::new(path).exists() {
826        return Err(ConfigError::FileExists { path: path.to_string() });
827    }
828
829    let config_content = match preset {
830        "default" => generate_default_preset(),
831        "google" => generate_google_preset(),
832        "relaxed" => generate_relaxed_preset(),
833        _ => {
834            return Err(ConfigError::UnknownPreset {
835                name: preset.to_string(),
836            });
837        }
838    };
839
840    match fs::write(path, config_content) {
841        Ok(_) => Ok(()),
842        Err(err) => Err(ConfigError::IoError {
843            source: err,
844            path: path.to_string(),
845        }),
846    }
847}
848
849/// Generate the default preset configuration content.
850/// Returns the same content as `create_default_config`.
851fn generate_default_preset() -> String {
852    r#"# rumdl configuration file
853
854# Inherit settings from another config file (relative to this file's directory)
855# extends = "../base.rumdl.toml"
856
857# Global configuration options
858[global]
859# List of rules to disable (uncomment and modify as needed)
860# disable = ["MD013", "MD033"]
861
862# List of rules to enable exclusively (replaces defaults; only these rules will run)
863# enable = ["MD001", "MD003", "MD004"]
864
865# Additional rules to enable on top of defaults (additive, does not replace)
866# Use this to activate opt-in rules like MD060, MD063, MD072, MD073, MD074
867# extend-enable = ["MD060", "MD063"]
868
869# Additional rules to disable on top of the disable list (additive)
870# extend-disable = ["MD041"]
871
872# List of file/directory patterns to include for linting (if provided, only these will be linted)
873# include = [
874#    "docs/*.md",
875#    "src/**/*.md",
876#    "README.md"
877# ]
878
879# List of file/directory patterns to exclude from linting
880exclude = [
881    # Common directories to exclude
882    ".git",
883    ".github",
884    "node_modules",
885    "vendor",
886    "dist",
887    "build",
888
889    # Specific files or patterns
890    "CHANGELOG.md",
891    "LICENSE.md",
892]
893
894# Respect .gitignore, .ignore and git exclude files when scanning directories
895# (default: true). .markdownlintignore applies regardless.
896respect-gitignore = true
897
898# Markdown flavor/dialect (uncomment to enable)
899# Options: standard (default), gfm, commonmark, mkdocs, mdx, pandoc, quarto, obsidian, kramdown, azure_devops, myst, hugo, mdg, gh-aw
900# flavor = "mkdocs"
901
902# Rule-specific configurations (uncomment and modify as needed)
903
904# [MD003]
905# style = "atx"  # Heading style (atx, atx_closed, setext)
906
907# [MD004]
908# style = "asterisk"  # Unordered list style (asterisk, plus, dash, consistent)
909
910# [MD007]
911# indent = 4  # Unordered list indentation
912
913# [MD013]
914# line-length = 100  # Line length
915# code-blocks = false  # Exclude code blocks from line length check
916# tables = false  # Exclude tables from line length check
917# headings = true  # Include headings in line length check
918
919# [MD044]
920# names = ["rumdl", "Markdown", "GitHub"]  # Proper names that should be capitalized correctly
921# code-blocks = false  # Check code blocks for proper names (default: false, skips code blocks)
922"#
923    .to_string()
924}
925
926/// Generate Google developer documentation style preset.
927/// Based on <https://google.github.io/styleguide/docguide/style.html>
928fn generate_google_preset() -> String {
929    r#"# rumdl configuration - Google developer documentation style
930# Based on https://google.github.io/styleguide/docguide/style.html
931
932[global]
933exclude = [
934    ".git",
935    ".github",
936    "node_modules",
937    "vendor",
938    "dist",
939    "build",
940    "CHANGELOG.md",
941    "LICENSE.md",
942]
943respect-gitignore = true
944
945# ATX-style headings required
946[MD003]
947style = "atx"
948
949# Unordered list style: dash
950[MD004]
951style = "dash"
952
953# 4-space indent for nested lists
954[MD007]
955indent = 4
956
957# Strict mode: no trailing spaces allowed (Google uses backslash for line breaks)
958[MD009]
959strict = true
960
961# 80-character line length
962[MD013]
963line-length = 80
964code-blocks = false
965tables = false
966
967# No trailing punctuation in headings
968[MD026]
969punctuation = ".,;:!。,;:!"
970
971# Fenced code blocks only (no indented code blocks)
972[MD046]
973style = "fenced"
974
975# Emphasis with underscores
976[MD049]
977style = "underscore"
978
979# Strong with asterisks
980[MD050]
981style = "asterisk"
982"#
983    .to_string()
984}
985
986/// Generate relaxed preset for existing projects adopting rumdl incrementally.
987/// Longer line lengths, fewer rules, lenient settings to minimize initial warnings.
988fn generate_relaxed_preset() -> String {
989    r#"# rumdl configuration - Relaxed preset
990# Lenient settings for existing projects adopting rumdl incrementally.
991# Minimizes initial warnings while still catching important issues.
992
993[global]
994exclude = [
995    ".git",
996    ".github",
997    "node_modules",
998    "vendor",
999    "dist",
1000    "build",
1001    "CHANGELOG.md",
1002    "LICENSE.md",
1003]
1004respect-gitignore = true
1005
1006# Disable rules that produce the most noise on existing projects
1007disable = [
1008    "MD013",  # Line length - most existing files exceed 80 chars
1009    "MD033",  # Inline HTML - commonly used in real-world markdown
1010    "MD041",  # First line heading - not all files need it
1011]
1012
1013# Consistent heading style (any style, just be consistent)
1014[MD003]
1015style = "consistent"
1016
1017# Consistent list style
1018[MD004]
1019style = "consistent"
1020
1021# Consistent emphasis style
1022[MD049]
1023style = "consistent"
1024
1025# Consistent strong style
1026[MD050]
1027style = "consistent"
1028"#
1029    .to_string()
1030}
1031
1032/// How a config file being loaded was reached, which decides how much of it may
1033/// appear in a message about it.
1034///
1035/// A `Direct` file is one the user named: discovered in their project, or given
1036/// on the command line. Naming its path and quoting the line a parse error
1037/// points at tells them nothing they could not already read.
1038///
1039/// An `Extends` file was reached by following an `extends` value, and two things
1040/// about it are not the user's to see. Its path is built by substituting
1041/// environment variables, so printing the path prints their values wherever the
1042/// error goes, which under CI is the build log. And `extends` names an arbitrary
1043/// path chosen by whichever config declared it, so the file need not be config
1044/// at all: a repository you merely cloned can point rumdl at a private key and
1045/// have the parse error quote a line of it. Such a file is named by the
1046/// `extends` value as written, and its text is never quoted back.
1047///
1048/// This governs errors and warnings, which any lint run can emit unasked and
1049/// which therefore reach a build log that had no reason to hold a variable's
1050/// value. Output that answers a question about the configuration itself still
1051/// shows resolved paths, because that is the answer: `rumdl config` reports which
1052/// files took effect, a language server reports the same thing to the editor that
1053/// started it, and debug logging is how an `extends` chain gets diagnosed at all.
1054/// The first two read [`crate::config::SourcedConfig::loaded_files`], which is a
1055/// record of what loaded rather than a message about a problem, and it holds
1056/// resolved paths deliberately.
1057#[derive(Debug, Clone, Copy)]
1058pub(crate) enum ConfigOrigin<'a> {
1059    Direct,
1060    Extends {
1061        /// The reference together with the config that declared it. This is how
1062        /// the file is named by a message reporting a problem with the file
1063        /// itself, where knowing which config reached for it is what makes the
1064        /// problem diagnosable.
1065        described_as: &'a str,
1066        /// The reference alone, for the places a message only needs to identify
1067        /// the file: listing an `extends` chain, or naming it as the config that
1068        /// declared a further `extends`. Repeating the full form at every link
1069        /// nests one description inside the next.
1070        short_name: &'a str,
1071    },
1072}
1073
1074/// Stands in for text that came out of a file reached through `extends`.
1075///
1076/// Public because the file walk raises one of these messages itself: an `include`
1077/// pattern is judged where it is used rather than where it is parsed.
1078pub const WITHHELD: &str = "<withheld>";
1079
1080impl ConfigOrigin<'_> {
1081    /// How to name the file this origin describes in a message about the file.
1082    pub(crate) fn display_name(&self, path: &str) -> String {
1083        match self {
1084            Self::Direct => crate::config::validation::to_relative_display_path(path),
1085            Self::Extends { described_as, .. } => (*described_as).to_string(),
1086        }
1087    }
1088
1089    /// How to name this file when a message is about something else and only has
1090    /// to say which file it means.
1091    pub(crate) fn short_name(&self, path: &str) -> String {
1092        match self {
1093            Self::Direct => crate::config::validation::to_relative_display_path(path),
1094            Self::Extends { short_name, .. } => (*short_name).to_string(),
1095        }
1096    }
1097
1098    /// Whether a message about this file may quote the file's own text.
1099    pub(crate) fn may_quote_contents(&self) -> bool {
1100        matches!(self, Self::Direct)
1101    }
1102
1103    /// A piece of text read from this file, as a message about the file may
1104    /// show it.
1105    ///
1106    /// A `Direct` file's text is shown as written. An `Extends` target's is
1107    /// replaced by [`WITHHELD`], because an unrecognized key or an invalid value
1108    /// is still text out of a file rumdl was merely pointed at. The message
1109    /// keeps saying what kind of problem it found and which file holds it, and
1110    /// leaves the rest to whoever can open that file.
1111    pub(crate) fn quote<'t>(&self, text: &'t str) -> &'t str {
1112        if self.may_quote_contents() { text } else { WITHHELD }
1113    }
1114}
1115
1116/// A config file as a message about it refers to it: the name to use, and
1117/// whether the file's own text may be shown alongside.
1118///
1119/// Pairs the display name, worked out once when a file is parsed, with the
1120/// [`ConfigOrigin`] that decided it. Every warning a parser emits names the file
1121/// and asks the same question about its contents, so both travel together rather
1122/// than as two parameters that could drift apart.
1123#[derive(Debug, Clone, Copy)]
1124pub(crate) struct ConfigRef<'a> {
1125    name: &'a str,
1126    origin: ConfigOrigin<'a>,
1127}
1128
1129impl<'a> ConfigRef<'a> {
1130    pub(crate) fn new(name: &'a str, origin: ConfigOrigin<'a>) -> Self {
1131        Self { name, origin }
1132    }
1133
1134    /// See [`ConfigOrigin::quote`].
1135    pub(crate) fn quote<'t>(&self, text: &'t str) -> &'t str {
1136        self.origin.quote(text)
1137    }
1138
1139    /// See [`ConfigOrigin::may_quote_contents`].
1140    pub(crate) fn may_quote_contents(&self) -> bool {
1141        self.origin.may_quote_contents()
1142    }
1143}
1144
1145/// Displays as the file's name, so a message can name the file by interpolating
1146/// the reference itself.
1147impl std::fmt::Display for ConfigRef<'_> {
1148    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1149        f.write_str(self.name)
1150    }
1151}
1152
1153/// Errors that can occur when loading configuration
1154#[derive(Debug, thiserror::Error)]
1155pub enum ConfigError {
1156    /// Failed to read the configuration file
1157    #[error("Failed to read config file at {path}: {source}")]
1158    IoError { source: io::Error, path: String },
1159
1160    /// Failed to parse the configuration content (TOML or JSON)
1161    #[error("Failed to parse config: {0}")]
1162    ParseError(String),
1163
1164    /// Configuration file already exists
1165    #[error("Configuration file already exists at {path}")]
1166    FileExists { path: String },
1167
1168    /// Circular extends reference detected
1169    #[error("Circular extends reference: {path} already in chain {chain:?}")]
1170    CircularExtends { path: String, chain: Vec<String> },
1171
1172    /// Extends chain exceeds maximum depth
1173    #[error("Extends chain exceeds maximum depth of {max_depth} at {path}")]
1174    ExtendsDepthExceeded { path: String, max_depth: usize },
1175
1176    /// Extends target file not found
1177    #[error("extends target not found: {path} (referenced from {from})")]
1178    ExtendsNotFound { path: String, from: String },
1179
1180    /// An `extends` path referenced an environment variable that is not set
1181    #[error("extends path references undefined environment variable {var} (referenced from {from})")]
1182    ExtendsUndefinedVar {
1183        /// The variable as the message may name it: `$NAME`, or [`WITHHELD`] when
1184        /// the file that wrote it was itself reached through `extends` and its
1185        /// text may not be repeated.
1186        var: String,
1187        from: String,
1188    },
1189
1190    /// Unknown preset name
1191    #[error("Unknown preset: {name}. Valid presets: default, google, relaxed")]
1192    UnknownPreset { name: String },
1193}
1194
1195/// Why a config file found by discovery could not be loaded.
1196///
1197/// The two cases call for different handling. A discovered project file that
1198/// cannot be parsed is local to one project and a caller may reasonably skip it
1199/// and keep looking. A broken user config is machine-wide: every project that
1200/// merges onto it resolves to something other than what the user configured, so
1201/// it has to be surfaced instead of worked around.
1202#[derive(Debug, thiserror::Error)]
1203pub enum DiscoveredConfigError {
1204    /// The discovered file itself is unusable.
1205    #[error(transparent)]
1206    ProjectConfig(ConfigError),
1207
1208    /// The discovered file is fine, but the user config it merges on top of is
1209    /// unusable. Only a discovered markdownlint config has such a base.
1210    #[error(transparent)]
1211    UserConfig(ConfigError),
1212}
1213
1214impl From<DiscoveredConfigError> for ConfigError {
1215    fn from(error: DiscoveredConfigError) -> Self {
1216        match error {
1217            DiscoveredConfigError::ProjectConfig(error) | DiscoveredConfigError::UserConfig(error) => error,
1218        }
1219    }
1220}
1221
1222/// Get a rule-specific configuration value
1223/// Automatically tries both the original key and normalized variants (kebab-case ↔ snake_case)
1224/// for better markdownlint compatibility
1225pub fn get_rule_config_value<T: serde::de::DeserializeOwned>(config: &Config, rule_name: &str, key: &str) -> Option<T> {
1226    let norm_rule_name = rule_name.to_ascii_uppercase(); // Use uppercase for lookup
1227
1228    let rule_config = config.rules.get(&norm_rule_name)?;
1229
1230    // Try multiple key variants to support both underscore and kebab-case formats
1231    let key_variants = [
1232        key.to_string(),       // Original key as provided
1233        normalize_key(key),    // Normalized key (lowercase, kebab-case)
1234        key.replace('-', "_"), // Convert kebab-case to snake_case
1235        key.replace('_', "-"), // Convert snake_case to kebab-case
1236    ];
1237
1238    // Try each variant until we find a match
1239    for variant in &key_variants {
1240        if let Some(value) = rule_config.values.get(variant)
1241            && let Ok(result) = T::deserialize(value.clone())
1242        {
1243            return Some(result);
1244        }
1245    }
1246
1247    None
1248}
1249
1250/// Generate preset configuration for pyproject.toml format.
1251/// Converts the .rumdl.toml preset to pyproject.toml section format.
1252pub fn generate_pyproject_preset_config(preset: &str) -> Result<String, ConfigError> {
1253    match preset {
1254        "default" => Ok(generate_pyproject_config()),
1255        other => {
1256            let rumdl_config = match other {
1257                "google" => generate_google_preset(),
1258                "relaxed" => generate_relaxed_preset(),
1259                _ => {
1260                    return Err(ConfigError::UnknownPreset {
1261                        name: other.to_string(),
1262                    });
1263                }
1264            };
1265            Ok(convert_rumdl_to_pyproject(&rumdl_config))
1266        }
1267    }
1268}
1269
1270/// Convert a .rumdl.toml config string to pyproject.toml format.
1271/// Rewrites `[global]` → `[tool.rumdl]` and `[MDXXX]` → `[tool.rumdl.MDXXX]`.
1272fn convert_rumdl_to_pyproject(rumdl_config: &str) -> String {
1273    let mut output = String::with_capacity(rumdl_config.len() + 128);
1274    for line in rumdl_config.lines() {
1275        let trimmed = line.trim();
1276        if trimmed.starts_with('[') && trimmed.ends_with(']') && !trimmed.starts_with("# [") {
1277            let section = &trimmed[1..trimmed.len() - 1];
1278            if section == "global" {
1279                output.push_str("[tool.rumdl]");
1280            } else {
1281                output.push_str(&format!("[tool.rumdl.{section}]"));
1282            }
1283        } else {
1284            output.push_str(line);
1285        }
1286        output.push('\n');
1287    }
1288    output
1289}
1290
1291/// Generate default rumdl configuration for pyproject.toml
1292pub fn generate_pyproject_config() -> String {
1293    let config_content = r#"
1294[tool.rumdl]
1295# Global configuration options
1296line-length = 100
1297disable = []
1298# extend-enable = ["MD060"]  # Add opt-in rules (additive, keeps defaults)
1299# extend-disable = []  # Additional rules to disable (additive)
1300exclude = [
1301    # Common directories to exclude
1302    ".git",
1303    ".github",
1304    "node_modules",
1305    "vendor",
1306    "dist",
1307    "build",
1308]
1309respect-gitignore = true
1310
1311# Rule-specific configurations (uncomment and modify as needed)
1312
1313# [tool.rumdl.MD003]
1314# style = "atx"  # Heading style (atx, atx_closed, setext)
1315
1316# [tool.rumdl.MD004]
1317# style = "asterisk"  # Unordered list style (asterisk, plus, dash, consistent)
1318
1319# [tool.rumdl.MD007]
1320# indent = 4  # Unordered list indentation
1321
1322# [tool.rumdl.MD013]
1323# line-length = 100  # Line length
1324# code-blocks = false  # Exclude code blocks from line length check
1325# tables = false  # Exclude tables from line length check
1326# headings = true  # Include headings in line length check
1327
1328# [tool.rumdl.MD044]
1329# names = ["rumdl", "Markdown", "GitHub"]  # Proper names that should be capitalized correctly
1330# code-blocks = false  # Check code blocks for proper names (default: false, skips code blocks)
1331"#;
1332
1333    config_content.to_string()
1334}