mdbook-lint 0.16.0

A fast markdown linter and preprocessor for mdBook
Documentation
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
//! LSP server implementation for mdbook-lint
//!
//! This module provides a Language Server Protocol server for real-time markdown
//! linting in editors. It supports both general markdown linting and mdBook-specific
//! enhancements.
//!
//! This module is only available when the `lsp` feature is enabled.

use crate::config::Config;
use mdbook_lint_core::{Document, LintEngine, PluginRegistry, Severity, Violation};
#[cfg(feature = "adr")]
use mdbook_lint_rulesets::AdrRuleProvider;
use mdbook_lint_rulesets::{MdBookRuleProvider, StandardRuleProvider};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tower_lsp::jsonrpc::Result;
use tower_lsp::lsp_types::*;
use tower_lsp::{Client, LanguageServer, LspService, Server};

/// The main LSP server implementation
pub struct MdBookLintServer {
    client: Client,
    engine: LintEngine,
    document_map: tokio::sync::RwLock<HashMap<Url, String>>,
    config: tokio::sync::RwLock<Config>,
}

impl MdBookLintServer {
    pub fn new(client: Client) -> Self {
        let mut registry = PluginRegistry::new();
        registry
            .register_provider(Box::new(StandardRuleProvider))
            .expect("Failed to register standard rules");
        registry
            .register_provider(Box::new(MdBookRuleProvider))
            .expect("Failed to register mdbook rules");
        #[cfg(feature = "adr")]
        registry
            .register_provider(Box::new(AdrRuleProvider))
            .expect("Failed to register ADR rules");
        let engine = registry.create_engine().expect("Failed to create engine");

        Self {
            client,
            engine,
            document_map: tokio::sync::RwLock::new(HashMap::new()),
            config: tokio::sync::RwLock::new(Config::default()),
        }
    }

    /// Lint a document and convert violations to LSP diagnostics
    async fn lint_document(&self, uri: &Url, text: &str) -> Vec<Diagnostic> {
        let path = uri
            .to_file_path()
            .unwrap_or_else(|_| PathBuf::from("untitled.md"));

        let document = match Document::new(text.to_string(), path) {
            Ok(doc) => doc,
            Err(_) => return Vec::new(),
        };

        let config = self.config.read().await;
        let effective_core = config.effective_core_config();
        let violations = match self
            .engine
            .lint_document_with_config(&document, &effective_core)
        {
            Ok(violations) => violations,
            Err(_) => return Vec::new(),
        };

        violations
            .into_iter()
            .map(|violation| self.violation_to_diagnostic(violation))
            .collect()
    }

    /// Convert a mdbook-lint violation to an LSP diagnostic
    fn violation_to_diagnostic(&self, violation: Violation) -> Diagnostic {
        let severity = match violation.severity {
            Severity::Error => DiagnosticSeverity::ERROR,
            Severity::Warning => DiagnosticSeverity::WARNING,
            Severity::Info => DiagnosticSeverity::INFORMATION,
        };

        let range = Range {
            start: Position {
                line: (violation.line.saturating_sub(1)) as u32,
                character: (violation.column.saturating_sub(1)) as u32,
            },
            end: Position {
                line: (violation.line.saturating_sub(1)) as u32,
                character: violation.column as u32, // End one character after start for simplicity
            },
        };

        Diagnostic {
            range,
            severity: Some(severity),
            code: Some(NumberOrString::String(violation.rule_id.clone())),
            code_description: None,
            source: Some("mdbook-lint".to_string()),
            message: violation.message,
            related_information: None,
            tags: None,
            data: None,
        }
    }
}

/// Return true if a workspace root looks like an mdBook project.
///
/// Used only to tailor the initialization log message. It must not gate
/// configuration loading, which applies to every markdown workspace.
fn is_mdbook_project(root_path: &Path) -> bool {
    root_path.join("book.toml").exists() || root_path.join("SUMMARY.md").exists()
}

/// Load `.mdbook-lint.toml` from a workspace root.
///
/// Returns the parsed config and the path it came from, or `None` when the file
/// is absent, unreadable, or invalid.
///
/// This applies to any markdown workspace, not only mdBook projects. The CLI
/// discovers this file regardless of whether a `book.toml` is present, so gating
/// it on mdBook detection left plain markdown users with configuration that was
/// silently ignored.
fn load_workspace_config(root_path: &Path) -> Option<(Config, PathBuf)> {
    let config_path = root_path.join(".mdbook-lint.toml");
    let content = std::fs::read_to_string(&config_path).ok()?;
    let config = Config::from_toml_str(&content).ok()?;
    Some((config, config_path))
}

#[tower_lsp::async_trait]
impl LanguageServer for MdBookLintServer {
    async fn initialize(&self, params: InitializeParams) -> Result<InitializeResult> {
        // Detect if we're in an mdBook project and load config
        let (is_mdbook_project, config_loaded) = if let Some(root_uri) = &params.root_uri {
            if let Ok(root_path) = root_uri.to_file_path() {
                let is_mdbook = is_mdbook_project(&root_path);

                // Configuration is loaded for any markdown workspace, not only
                // mdBook projects.
                let mut config_loaded = false;
                if let Some((config, config_path)) = load_workspace_config(&root_path) {
                    *self.config.write().await = config;
                    config_loaded = true;
                    self.client
                        .log_message(
                            MessageType::INFO,
                            format!("Loaded config from {}", config_path.display()),
                        )
                        .await;
                }
                (is_mdbook, config_loaded)
            } else {
                (false, false)
            }
        } else {
            (false, false)
        };

        // Log initialization info
        let message = match (is_mdbook_project, config_loaded) {
            (true, true) => "mdbook-lint LSP initialized for mdBook project with custom config",
            (true, false) => "mdbook-lint LSP initialized for mdBook project with default config",
            (false, _) => "mdbook-lint LSP initialized for markdown project",
        };
        self.client.log_message(MessageType::INFO, message).await;

        Ok(InitializeResult {
            capabilities: ServerCapabilities {
                text_document_sync: Some(TextDocumentSyncCapability::Kind(
                    TextDocumentSyncKind::FULL,
                )),
                diagnostic_provider: Some(DiagnosticServerCapabilities::Options(
                    DiagnosticOptions {
                        identifier: Some("mdbook-lint".to_string()),
                        inter_file_dependencies: false,
                        workspace_diagnostics: false,
                        work_done_progress_options: WorkDoneProgressOptions::default(),
                    },
                )),
                ..Default::default()
            },
            server_info: Some(ServerInfo {
                name: "mdbook-lint".to_string(),
                version: Some(env!("CARGO_PKG_VERSION").to_string()),
            }),
        })
    }

    async fn initialized(&self, _: InitializedParams) {
        self.client
            .log_message(MessageType::INFO, "mdbook-lint LSP server initialized")
            .await;
    }

    async fn shutdown(&self) -> Result<()> {
        Ok(())
    }

    async fn did_open(&self, params: DidOpenTextDocumentParams) {
        let uri = params.text_document.uri;
        let text = params.text_document.text;

        // Store document content
        self.document_map
            .write()
            .await
            .insert(uri.clone(), text.clone());

        // Lint and publish diagnostics
        let diagnostics = self.lint_document(&uri, &text).await;

        self.client
            .publish_diagnostics(uri, diagnostics, None)
            .await;
    }

    async fn did_change(&self, params: DidChangeTextDocumentParams) {
        let uri = params.text_document.uri;

        // Get the full new text (we use FULL sync mode)
        if let Some(change) = params.content_changes.into_iter().next() {
            let text = change.text;

            // Store updated content
            self.document_map
                .write()
                .await
                .insert(uri.clone(), text.clone());

            // Lint and publish diagnostics
            let diagnostics = self.lint_document(&uri, &text).await;

            self.client
                .publish_diagnostics(uri, diagnostics, None)
                .await;
        }
    }

    async fn did_save(&self, params: DidSaveTextDocumentParams) {
        // Re-lint on save to ensure consistency
        let uri = params.text_document.uri;

        if let Some(text) = self.document_map.read().await.get(&uri) {
            let diagnostics = self.lint_document(&uri, text).await;

            self.client
                .publish_diagnostics(uri, diagnostics, None)
                .await;
        }
    }

    async fn did_close(&self, params: DidCloseTextDocumentParams) {
        // Remove from document map and clear diagnostics
        self.document_map
            .write()
            .await
            .remove(&params.text_document.uri);

        self.client
            .publish_diagnostics(params.text_document.uri, Vec::new(), None)
            .await;
    }

    async fn diagnostic(
        &self,
        params: DocumentDiagnosticParams,
    ) -> Result<DocumentDiagnosticReportResult> {
        let uri = params.text_document.uri;

        if let Some(text) = self.document_map.read().await.get(&uri) {
            let diagnostics = self.lint_document(&uri, text).await;

            Ok(DocumentDiagnosticReportResult::Report(
                DocumentDiagnosticReport::Full(RelatedFullDocumentDiagnosticReport {
                    related_documents: None,
                    full_document_diagnostic_report: FullDocumentDiagnosticReport {
                        result_id: None,
                        items: diagnostics,
                    },
                }),
            ))
        } else {
            Ok(DocumentDiagnosticReportResult::Report(
                DocumentDiagnosticReport::Full(RelatedFullDocumentDiagnosticReport {
                    related_documents: None,
                    full_document_diagnostic_report: FullDocumentDiagnosticReport {
                        result_id: None,
                        items: Vec::new(),
                    },
                }),
            ))
        }
    }
}

/// Run the LSP server
pub async fn run_lsp_server(_stdio: bool, port: Option<u16>) -> mdbook_lint_core::Result<()> {
    if let Some(port) = port {
        // TCP mode
        let listener = tokio::net::TcpListener::bind(format!("127.0.0.1:{port}")).await?;
        eprintln!("mdbook-lint LSP server listening on port {port}");

        let (stream, _) = listener.accept().await?;
        let (read, write) = tokio::io::split(stream);

        let (service, socket) = LspService::new(MdBookLintServer::new);
        Server::new(read, write, socket).serve(service).await;
    } else {
        // stdio mode (default)
        let stdin = tokio::io::stdin();
        let stdout = tokio::io::stdout();

        let (service, socket) = LspService::new(MdBookLintServer::new);
        Server::new(stdin, stdout, socket).serve(service).await;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    const CONFIG: &str = "preset = \"baseline\"\ndisabled-rules = [\"MD013\"]\n";

    #[test]
    fn test_config_loads_without_mdbook_markers() {
        // Regression: the LSP previously loaded .mdbook-lint.toml only when
        // book.toml or SUMMARY.md was present, so plain markdown projects had
        // their configuration silently ignored.
        let temp = TempDir::new().unwrap();
        fs::write(temp.path().join(".mdbook-lint.toml"), CONFIG).unwrap();

        assert!(
            !is_mdbook_project(temp.path()),
            "fixture must not look like an mdBook project"
        );

        let (config, path) =
            load_workspace_config(temp.path()).expect("config should load without mdBook markers");
        assert_eq!(config.core.disabled_rules, vec!["MD013"]);
        assert_eq!(
            config.preset,
            Some(mdbook_lint_rulesets::RulePreset::Baseline)
        );
        assert_eq!(
            config.effective_core_config().enabled_rules,
            mdbook_lint_rulesets::BASELINE_RULE_IDS
        );
        assert_eq!(path, temp.path().join(".mdbook-lint.toml"));
    }

    #[test]
    fn test_config_still_loads_in_mdbook_project() {
        for marker in ["book.toml", "SUMMARY.md"] {
            let temp = TempDir::new().unwrap();
            fs::write(temp.path().join(marker), "").unwrap();
            fs::write(temp.path().join(".mdbook-lint.toml"), CONFIG).unwrap();

            assert!(
                is_mdbook_project(temp.path()),
                "{marker} should be detected"
            );
            let (config, _) =
                load_workspace_config(temp.path()).expect("config should load for {marker}");
            assert_eq!(config.core.disabled_rules, vec!["MD013"]);
        }
    }

    #[test]
    fn test_no_config_file_returns_none() {
        let temp = TempDir::new().unwrap();
        assert!(load_workspace_config(temp.path()).is_none());
    }

    #[test]
    fn test_invalid_config_returns_none() {
        // A malformed file must not take down initialization.
        let temp = TempDir::new().unwrap();
        fs::write(
            temp.path().join(".mdbook-lint.toml"),
            "this is not = valid = toml",
        )
        .unwrap();
        assert!(load_workspace_config(temp.path()).is_none());
    }

    #[test]
    fn test_is_mdbook_project_detection() {
        let temp = TempDir::new().unwrap();
        assert!(!is_mdbook_project(temp.path()));

        fs::write(temp.path().join("book.toml"), "").unwrap();
        assert!(is_mdbook_project(temp.path()));
    }
}