1use std::collections::HashMap;
7use std::path::PathBuf;
8use std::sync::Arc;
9
10use anyhow::Result;
11use tokio::sync::RwLock;
12use tower_lsp::jsonrpc::Result as JsonRpcResult;
13use tower_lsp::lsp_types::*;
14use tower_lsp::{Client, LanguageServer};
15
16use crate::config::Config;
17use crate::lint;
18use crate::lsp::types::{RumdlLspConfig, warning_to_code_actions, warning_to_diagnostic};
19use crate::rule::Rule;
20use crate::rules;
21
22#[derive(Clone, Debug, PartialEq)]
24struct DocumentEntry {
25 content: String,
27 version: Option<i32>,
29 from_disk: bool,
31}
32
33#[derive(Clone, Debug)]
35pub(crate) struct ConfigCacheEntry {
36 pub(crate) config: Config,
38 pub(crate) config_file: Option<PathBuf>,
40 pub(crate) from_global_fallback: bool,
42}
43
44#[derive(Clone)]
53pub struct RumdlLanguageServer {
54 client: Client,
55 config: Arc<RwLock<RumdlLspConfig>>,
57 #[cfg_attr(test, allow(dead_code))]
59 pub(crate) rumdl_config: Arc<RwLock<Config>>,
60 documents: Arc<RwLock<HashMap<Url, DocumentEntry>>>,
62 #[cfg_attr(test, allow(dead_code))]
64 pub(crate) workspace_roots: Arc<RwLock<Vec<PathBuf>>>,
65 #[cfg_attr(test, allow(dead_code))]
68 pub(crate) config_cache: Arc<RwLock<HashMap<PathBuf, ConfigCacheEntry>>>,
69}
70
71impl RumdlLanguageServer {
72 pub fn new(client: Client) -> Self {
73 Self {
74 client,
75 config: Arc::new(RwLock::new(RumdlLspConfig::default())),
76 rumdl_config: Arc::new(RwLock::new(Config::default())),
77 documents: Arc::new(RwLock::new(HashMap::new())),
78 workspace_roots: Arc::new(RwLock::new(Vec::new())),
79 config_cache: Arc::new(RwLock::new(HashMap::new())),
80 }
81 }
82
83 async fn get_document_content(&self, uri: &Url) -> Option<String> {
89 {
91 let docs = self.documents.read().await;
92 if let Some(entry) = docs.get(uri) {
93 return Some(entry.content.clone());
94 }
95 }
96
97 if let Ok(path) = uri.to_file_path() {
99 if let Ok(content) = tokio::fs::read_to_string(&path).await {
100 let entry = DocumentEntry {
102 content: content.clone(),
103 version: None,
104 from_disk: true,
105 };
106
107 let mut docs = self.documents.write().await;
108 docs.insert(uri.clone(), entry);
109
110 log::debug!("Loaded document from disk and cached: {uri}");
111 return Some(content);
112 } else {
113 log::debug!("Failed to read file from disk: {uri}");
114 }
115 }
116
117 None
118 }
119
120 fn apply_lsp_config_overrides(
122 &self,
123 mut filtered_rules: Vec<Box<dyn Rule>>,
124 lsp_config: &RumdlLspConfig,
125 ) -> Vec<Box<dyn Rule>> {
126 if let Some(enable) = &lsp_config.enable_rules
128 && !enable.is_empty()
129 {
130 let enable_set: std::collections::HashSet<String> = enable.iter().cloned().collect();
131 filtered_rules.retain(|rule| enable_set.contains(rule.name()));
132 }
133
134 if let Some(disable) = &lsp_config.disable_rules
136 && !disable.is_empty()
137 {
138 let disable_set: std::collections::HashSet<String> = disable.iter().cloned().collect();
139 filtered_rules.retain(|rule| !disable_set.contains(rule.name()));
140 }
141
142 filtered_rules
143 }
144
145 async fn should_exclude_uri(&self, uri: &Url) -> bool {
147 let file_path = match uri.to_file_path() {
149 Ok(path) => path,
150 Err(_) => return false, };
152
153 let rumdl_config = self.resolve_config_for_file(&file_path).await;
155 let exclude_patterns = &rumdl_config.global.exclude;
156
157 if exclude_patterns.is_empty() {
159 return false;
160 }
161
162 let path_to_check = if file_path.is_absolute() {
165 if let Ok(cwd) = std::env::current_dir() {
167 if let (Ok(canonical_cwd), Ok(canonical_path)) = (cwd.canonicalize(), file_path.canonicalize()) {
169 if let Ok(relative) = canonical_path.strip_prefix(&canonical_cwd) {
170 relative.to_string_lossy().to_string()
171 } else {
172 file_path.to_string_lossy().to_string()
174 }
175 } else {
176 file_path.to_string_lossy().to_string()
178 }
179 } else {
180 file_path.to_string_lossy().to_string()
181 }
182 } else {
183 file_path.to_string_lossy().to_string()
185 };
186
187 for pattern in exclude_patterns {
189 if let Ok(glob) = globset::Glob::new(pattern) {
190 let matcher = glob.compile_matcher();
191 if matcher.is_match(&path_to_check) {
192 log::debug!("Excluding file from LSP linting: {path_to_check}");
193 return true;
194 }
195 }
196 }
197
198 false
199 }
200
201 pub(crate) async fn lint_document(&self, uri: &Url, text: &str) -> Result<Vec<Diagnostic>> {
203 let config_guard = self.config.read().await;
204
205 if !config_guard.enable_linting {
207 return Ok(Vec::new());
208 }
209
210 let lsp_config = config_guard.clone();
211 drop(config_guard); if self.should_exclude_uri(uri).await {
215 return Ok(Vec::new());
216 }
217
218 let rumdl_config = if let Ok(file_path) = uri.to_file_path() {
220 self.resolve_config_for_file(&file_path).await
221 } else {
222 (*self.rumdl_config.read().await).clone()
224 };
225
226 let all_rules = rules::all_rules(&rumdl_config);
227 let flavor = rumdl_config.markdown_flavor();
228
229 let mut filtered_rules = rules::filter_rules(&all_rules, &rumdl_config.global);
231
232 filtered_rules = self.apply_lsp_config_overrides(filtered_rules, &lsp_config);
234
235 match crate::lint(text, &filtered_rules, false, flavor) {
237 Ok(warnings) => {
238 let diagnostics = warnings.iter().map(warning_to_diagnostic).collect();
239 Ok(diagnostics)
240 }
241 Err(e) => {
242 log::error!("Failed to lint document {uri}: {e}");
243 Ok(Vec::new())
244 }
245 }
246 }
247
248 async fn update_diagnostics(&self, uri: Url, text: String) {
250 let version = {
252 let docs = self.documents.read().await;
253 docs.get(&uri).and_then(|entry| entry.version)
254 };
255
256 match self.lint_document(&uri, &text).await {
257 Ok(diagnostics) => {
258 self.client.publish_diagnostics(uri, diagnostics, version).await;
259 }
260 Err(e) => {
261 log::error!("Failed to update diagnostics: {e}");
262 }
263 }
264 }
265
266 async fn apply_all_fixes(&self, uri: &Url, text: &str) -> Result<Option<String>> {
268 if self.should_exclude_uri(uri).await {
270 return Ok(None);
271 }
272
273 let config_guard = self.config.read().await;
274 let lsp_config = config_guard.clone();
275 drop(config_guard);
276
277 let rumdl_config = if let Ok(file_path) = uri.to_file_path() {
279 self.resolve_config_for_file(&file_path).await
280 } else {
281 (*self.rumdl_config.read().await).clone()
283 };
284
285 let all_rules = rules::all_rules(&rumdl_config);
286 let flavor = rumdl_config.markdown_flavor();
287
288 let mut filtered_rules = rules::filter_rules(&all_rules, &rumdl_config.global);
290
291 filtered_rules = self.apply_lsp_config_overrides(filtered_rules, &lsp_config);
293
294 let mut rules_with_warnings = std::collections::HashSet::new();
297 let mut fixed_text = text.to_string();
298
299 match lint(&fixed_text, &filtered_rules, false, flavor) {
300 Ok(warnings) => {
301 for warning in warnings {
302 if let Some(rule_name) = &warning.rule_name {
303 rules_with_warnings.insert(rule_name.clone());
304 }
305 }
306 }
307 Err(e) => {
308 log::warn!("Failed to lint document for auto-fix: {e}");
309 return Ok(None);
310 }
311 }
312
313 if rules_with_warnings.is_empty() {
315 return Ok(None);
316 }
317
318 let mut any_changes = false;
320
321 for rule in &filtered_rules {
322 if !rules_with_warnings.contains(rule.name()) {
324 continue;
325 }
326
327 let ctx = crate::lint_context::LintContext::new(&fixed_text, flavor);
328 match rule.fix(&ctx) {
329 Ok(new_text) => {
330 if new_text != fixed_text {
331 fixed_text = new_text;
332 any_changes = true;
333 }
334 }
335 Err(e) => {
336 let msg = e.to_string();
338 if !msg.contains("does not support automatic fixing") {
339 log::warn!("Failed to apply fix for rule {}: {}", rule.name(), e);
340 }
341 }
342 }
343 }
344
345 if any_changes { Ok(Some(fixed_text)) } else { Ok(None) }
346 }
347
348 fn get_end_position(&self, text: &str) -> Position {
350 let mut line = 0u32;
351 let mut character = 0u32;
352
353 for ch in text.chars() {
354 if ch == '\n' {
355 line += 1;
356 character = 0;
357 } else {
358 character += 1;
359 }
360 }
361
362 Position { line, character }
363 }
364
365 async fn get_code_actions(&self, uri: &Url, text: &str, range: Range) -> Result<Vec<CodeAction>> {
367 let config_guard = self.config.read().await;
368 let lsp_config = config_guard.clone();
369 drop(config_guard);
370
371 let rumdl_config = if let Ok(file_path) = uri.to_file_path() {
373 self.resolve_config_for_file(&file_path).await
374 } else {
375 (*self.rumdl_config.read().await).clone()
377 };
378
379 let all_rules = rules::all_rules(&rumdl_config);
380 let flavor = rumdl_config.markdown_flavor();
381
382 let mut filtered_rules = rules::filter_rules(&all_rules, &rumdl_config.global);
384
385 filtered_rules = self.apply_lsp_config_overrides(filtered_rules, &lsp_config);
387
388 match crate::lint(text, &filtered_rules, false, flavor) {
389 Ok(warnings) => {
390 let mut actions = Vec::new();
391 let mut fixable_count = 0;
392
393 for warning in &warnings {
394 let warning_line = (warning.line.saturating_sub(1)) as u32;
396 if warning_line >= range.start.line && warning_line <= range.end.line {
397 let mut warning_actions = warning_to_code_actions(warning, uri, text);
399 actions.append(&mut warning_actions);
400
401 if warning.fix.is_some() {
402 fixable_count += 1;
403 }
404 }
405 }
406
407 if fixable_count > 1 {
409 let total_fixable = warnings.iter().filter(|w| w.fix.is_some()).count();
411
412 if let Ok(fixed_content) = crate::utils::fix_utils::apply_warning_fixes(text, &warnings)
413 && fixed_content != text
414 {
415 let mut line = 0u32;
417 let mut character = 0u32;
418 for ch in text.chars() {
419 if ch == '\n' {
420 line += 1;
421 character = 0;
422 } else {
423 character += 1;
424 }
425 }
426
427 let fix_all_action = CodeAction {
428 title: format!("Fix all rumdl issues ({total_fixable} fixable)"),
429 kind: Some(CodeActionKind::QUICKFIX),
430 diagnostics: Some(Vec::new()),
431 edit: Some(WorkspaceEdit {
432 changes: Some(
433 [(
434 uri.clone(),
435 vec![TextEdit {
436 range: Range {
437 start: Position { line: 0, character: 0 },
438 end: Position { line, character },
439 },
440 new_text: fixed_content,
441 }],
442 )]
443 .into_iter()
444 .collect(),
445 ),
446 ..Default::default()
447 }),
448 command: None,
449 is_preferred: Some(true),
450 disabled: None,
451 data: None,
452 };
453
454 actions.insert(0, fix_all_action);
456 }
457 }
458
459 Ok(actions)
460 }
461 Err(e) => {
462 log::error!("Failed to get code actions: {e}");
463 Ok(Vec::new())
464 }
465 }
466 }
467
468 async fn load_configuration(&self, notify_client: bool) {
470 let config_guard = self.config.read().await;
471 let explicit_config_path = config_guard.config_path.clone();
472 drop(config_guard);
473
474 match Self::load_config_for_lsp(explicit_config_path.as_deref()) {
476 Ok(sourced_config) => {
477 let loaded_files = sourced_config.loaded_files.clone();
478 *self.rumdl_config.write().await = sourced_config.into();
479
480 if !loaded_files.is_empty() {
481 let message = format!("Loaded rumdl config from: {}", loaded_files.join(", "));
482 log::info!("{message}");
483 if notify_client {
484 self.client.log_message(MessageType::INFO, &message).await;
485 }
486 } else {
487 log::info!("Using default rumdl configuration (no config files found)");
488 }
489 }
490 Err(e) => {
491 let message = format!("Failed to load rumdl config: {e}");
492 log::warn!("{message}");
493 if notify_client {
494 self.client.log_message(MessageType::WARNING, &message).await;
495 }
496 *self.rumdl_config.write().await = crate::config::Config::default();
498 }
499 }
500 }
501
502 async fn reload_configuration(&self) {
504 self.load_configuration(true).await;
505 }
506
507 fn load_config_for_lsp(
509 config_path: Option<&str>,
510 ) -> Result<crate::config::SourcedConfig, crate::config::ConfigError> {
511 crate::config::SourcedConfig::load_with_discovery(config_path, None, false)
513 }
514
515 pub(crate) async fn resolve_config_for_file(&self, file_path: &std::path::Path) -> Config {
522 let search_dir = file_path.parent().unwrap_or(file_path).to_path_buf();
524
525 {
527 let cache = self.config_cache.read().await;
528 if let Some(entry) = cache.get(&search_dir) {
529 let source_owned: String; let source: &str = if entry.from_global_fallback {
531 "global/user fallback"
532 } else if let Some(path) = &entry.config_file {
533 source_owned = path.to_string_lossy().to_string();
534 &source_owned
535 } else {
536 "<unknown>"
537 };
538 log::debug!(
539 "Config cache hit for directory: {} (loaded from: {})",
540 search_dir.display(),
541 source
542 );
543 return entry.config.clone();
544 }
545 }
546
547 log::debug!(
549 "Config cache miss for directory: {}, searching for config...",
550 search_dir.display()
551 );
552
553 let workspace_root = {
555 let workspace_roots = self.workspace_roots.read().await;
556 workspace_roots
557 .iter()
558 .find(|root| search_dir.starts_with(root))
559 .map(|p| p.to_path_buf())
560 };
561
562 let mut current_dir = search_dir.clone();
564 let mut found_config: Option<(Config, Option<PathBuf>)> = None;
565
566 loop {
567 const CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", "pyproject.toml", ".markdownlint.json"];
569
570 for config_file_name in CONFIG_FILES {
571 let config_path = current_dir.join(config_file_name);
572 if config_path.exists() {
573 log::debug!("Found config file: {}", config_path.display());
574
575 if let Ok(sourced) = Self::load_config_for_lsp(Some(config_path.to_str().unwrap())) {
577 found_config = Some((sourced.into(), Some(config_path)));
578 break;
579 }
580 }
581 }
582
583 if found_config.is_some() {
584 break;
585 }
586
587 if let Some(ref root) = workspace_root
589 && ¤t_dir == root
590 {
591 log::debug!("Hit workspace root without finding config: {}", root.display());
592 break;
593 }
594
595 if let Some(parent) = current_dir.parent() {
597 current_dir = parent.to_path_buf();
598 } else {
599 break;
601 }
602 }
603
604 let (config, config_file) = if let Some((cfg, path)) = found_config {
606 (cfg, path)
607 } else {
608 log::debug!("No project config found; using global/user fallback config");
609 let fallback = self.rumdl_config.read().await.clone();
610 (fallback, None)
611 };
612
613 let from_global = config_file.is_none();
615 let entry = ConfigCacheEntry {
616 config: config.clone(),
617 config_file,
618 from_global_fallback: from_global,
619 };
620
621 self.config_cache.write().await.insert(search_dir, entry);
622
623 config
624 }
625}
626
627#[tower_lsp::async_trait]
628impl LanguageServer for RumdlLanguageServer {
629 async fn initialize(&self, params: InitializeParams) -> JsonRpcResult<InitializeResult> {
630 log::info!("Initializing rumdl Language Server");
631
632 if let Some(options) = params.initialization_options
634 && let Ok(config) = serde_json::from_value::<RumdlLspConfig>(options)
635 {
636 *self.config.write().await = config;
637 }
638
639 let mut roots = Vec::new();
641 if let Some(workspace_folders) = params.workspace_folders {
642 for folder in workspace_folders {
643 if let Ok(path) = folder.uri.to_file_path() {
644 log::info!("Workspace root: {}", path.display());
645 roots.push(path);
646 }
647 }
648 } else if let Some(root_uri) = params.root_uri
649 && let Ok(path) = root_uri.to_file_path()
650 {
651 log::info!("Workspace root: {}", path.display());
652 roots.push(path);
653 }
654 *self.workspace_roots.write().await = roots;
655
656 self.load_configuration(false).await;
658
659 Ok(InitializeResult {
660 capabilities: ServerCapabilities {
661 text_document_sync: Some(TextDocumentSyncCapability::Options(TextDocumentSyncOptions {
662 open_close: Some(true),
663 change: Some(TextDocumentSyncKind::FULL),
664 will_save: Some(false),
665 will_save_wait_until: Some(true),
666 save: Some(TextDocumentSyncSaveOptions::SaveOptions(SaveOptions {
667 include_text: Some(false),
668 })),
669 })),
670 code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
671 document_formatting_provider: Some(OneOf::Left(true)),
672 document_range_formatting_provider: Some(OneOf::Left(true)),
673 diagnostic_provider: Some(DiagnosticServerCapabilities::Options(DiagnosticOptions {
674 identifier: Some("rumdl".to_string()),
675 inter_file_dependencies: false,
676 workspace_diagnostics: false,
677 work_done_progress_options: WorkDoneProgressOptions::default(),
678 })),
679 workspace: Some(WorkspaceServerCapabilities {
680 workspace_folders: Some(WorkspaceFoldersServerCapabilities {
681 supported: Some(true),
682 change_notifications: Some(OneOf::Left(true)),
683 }),
684 file_operations: None,
685 }),
686 ..Default::default()
687 },
688 server_info: Some(ServerInfo {
689 name: "rumdl".to_string(),
690 version: Some(env!("CARGO_PKG_VERSION").to_string()),
691 }),
692 })
693 }
694
695 async fn initialized(&self, _: InitializedParams) {
696 let version = env!("CARGO_PKG_VERSION");
697
698 let (binary_path, build_time) = std::env::current_exe()
700 .ok()
701 .map(|path| {
702 let path_str = path.to_str().unwrap_or("unknown").to_string();
703 let build_time = std::fs::metadata(&path)
704 .ok()
705 .and_then(|metadata| metadata.modified().ok())
706 .and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok())
707 .and_then(|duration| {
708 let secs = duration.as_secs();
709 chrono::DateTime::from_timestamp(secs as i64, 0)
710 .map(|dt| dt.format("%Y-%m-%d %H:%M:%S UTC").to_string())
711 })
712 .unwrap_or_else(|| "unknown".to_string());
713 (path_str, build_time)
714 })
715 .unwrap_or_else(|| ("unknown".to_string(), "unknown".to_string()));
716
717 let working_dir = std::env::current_dir()
718 .ok()
719 .and_then(|p| p.to_str().map(|s| s.to_string()))
720 .unwrap_or_else(|| "unknown".to_string());
721
722 log::info!("rumdl Language Server v{version} initialized (built: {build_time}, binary: {binary_path})");
723 log::info!("Working directory: {working_dir}");
724
725 self.client
726 .log_message(MessageType::INFO, format!("rumdl v{version} Language Server started"))
727 .await;
728 }
729
730 async fn did_change_workspace_folders(&self, params: DidChangeWorkspaceFoldersParams) {
731 let mut roots = self.workspace_roots.write().await;
733
734 for removed in ¶ms.event.removed {
736 if let Ok(path) = removed.uri.to_file_path() {
737 roots.retain(|r| r != &path);
738 log::info!("Removed workspace root: {}", path.display());
739 }
740 }
741
742 for added in ¶ms.event.added {
744 if let Ok(path) = added.uri.to_file_path()
745 && !roots.contains(&path)
746 {
747 log::info!("Added workspace root: {}", path.display());
748 roots.push(path);
749 }
750 }
751 drop(roots);
752
753 self.config_cache.write().await.clear();
755
756 self.reload_configuration().await;
758 }
759
760 async fn shutdown(&self) -> JsonRpcResult<()> {
761 log::info!("Shutting down rumdl Language Server");
762 Ok(())
763 }
764
765 async fn did_open(&self, params: DidOpenTextDocumentParams) {
766 let uri = params.text_document.uri;
767 let text = params.text_document.text;
768 let version = params.text_document.version;
769
770 let entry = DocumentEntry {
771 content: text.clone(),
772 version: Some(version),
773 from_disk: false,
774 };
775 self.documents.write().await.insert(uri.clone(), entry);
776
777 self.update_diagnostics(uri, text).await;
778 }
779
780 async fn did_change(&self, params: DidChangeTextDocumentParams) {
781 let uri = params.text_document.uri;
782 let version = params.text_document.version;
783
784 if let Some(change) = params.content_changes.into_iter().next() {
785 let text = change.text;
786
787 let entry = DocumentEntry {
788 content: text.clone(),
789 version: Some(version),
790 from_disk: false,
791 };
792 self.documents.write().await.insert(uri.clone(), entry);
793
794 self.update_diagnostics(uri, text).await;
795 }
796 }
797
798 async fn will_save_wait_until(&self, params: WillSaveTextDocumentParams) -> JsonRpcResult<Option<Vec<TextEdit>>> {
799 let config_guard = self.config.read().await;
800 let enable_auto_fix = config_guard.enable_auto_fix;
801 drop(config_guard);
802
803 if !enable_auto_fix {
804 return Ok(None);
805 }
806
807 let text = match self.get_document_content(¶ms.text_document.uri).await {
809 Some(content) => content,
810 None => return Ok(None),
811 };
812
813 match self.apply_all_fixes(¶ms.text_document.uri, &text).await {
815 Ok(Some(fixed_text)) => {
816 Ok(Some(vec![TextEdit {
818 range: Range {
819 start: Position { line: 0, character: 0 },
820 end: self.get_end_position(&text),
821 },
822 new_text: fixed_text,
823 }]))
824 }
825 Ok(None) => Ok(None),
826 Err(e) => {
827 log::error!("Failed to generate fixes in will_save_wait_until: {e}");
828 Ok(None)
829 }
830 }
831 }
832
833 async fn did_save(&self, params: DidSaveTextDocumentParams) {
834 if let Some(entry) = self.documents.read().await.get(¶ms.text_document.uri) {
837 self.update_diagnostics(params.text_document.uri, entry.content.clone())
838 .await;
839 }
840 }
841
842 async fn did_close(&self, params: DidCloseTextDocumentParams) {
843 self.documents.write().await.remove(¶ms.text_document.uri);
845
846 self.client
848 .publish_diagnostics(params.text_document.uri, Vec::new(), None)
849 .await;
850 }
851
852 async fn did_change_watched_files(&self, params: DidChangeWatchedFilesParams) {
853 const CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", "pyproject.toml", ".markdownlint.json"];
855
856 for change in ¶ms.changes {
857 if let Ok(path) = change.uri.to_file_path()
858 && let Some(file_name) = path.file_name().and_then(|f| f.to_str())
859 && CONFIG_FILES.contains(&file_name)
860 {
861 log::info!("Config file changed: {}, invalidating config cache", path.display());
862
863 let mut cache = self.config_cache.write().await;
865 cache.retain(|_, entry| {
866 if let Some(config_file) = &entry.config_file {
867 config_file != &path
868 } else {
869 true
870 }
871 });
872
873 drop(cache);
875 self.reload_configuration().await;
876
877 let docs_to_update: Vec<(Url, String)> = {
880 let docs = self.documents.read().await;
881 docs.iter()
882 .filter(|(_, entry)| !entry.from_disk)
883 .map(|(uri, entry)| (uri.clone(), entry.content.clone()))
884 .collect()
885 };
886
887 for (uri, text) in docs_to_update {
889 self.update_diagnostics(uri, text).await;
890 }
891
892 break;
893 }
894 }
895 }
896
897 async fn code_action(&self, params: CodeActionParams) -> JsonRpcResult<Option<CodeActionResponse>> {
898 let uri = params.text_document.uri;
899 let range = params.range;
900
901 if let Some(text) = self.get_document_content(&uri).await {
902 match self.get_code_actions(&uri, &text, range).await {
903 Ok(actions) => {
904 let response: Vec<CodeActionOrCommand> =
905 actions.into_iter().map(CodeActionOrCommand::CodeAction).collect();
906 Ok(Some(response))
907 }
908 Err(e) => {
909 log::error!("Failed to get code actions: {e}");
910 Ok(None)
911 }
912 }
913 } else {
914 Ok(None)
915 }
916 }
917
918 async fn range_formatting(&self, params: DocumentRangeFormattingParams) -> JsonRpcResult<Option<Vec<TextEdit>>> {
919 log::debug!(
924 "Range formatting requested for {:?}, formatting entire document due to rule interdependencies",
925 params.range
926 );
927
928 let formatting_params = DocumentFormattingParams {
929 text_document: params.text_document,
930 options: params.options,
931 work_done_progress_params: params.work_done_progress_params,
932 };
933
934 self.formatting(formatting_params).await
935 }
936
937 async fn formatting(&self, params: DocumentFormattingParams) -> JsonRpcResult<Option<Vec<TextEdit>>> {
938 let uri = params.text_document.uri;
939
940 log::debug!("Formatting request for: {uri}");
941
942 if let Some(text) = self.get_document_content(&uri).await {
943 let config_guard = self.config.read().await;
945 let lsp_config = config_guard.clone();
946 drop(config_guard);
947
948 let rumdl_config = if let Ok(file_path) = uri.to_file_path() {
950 self.resolve_config_for_file(&file_path).await
951 } else {
952 self.rumdl_config.read().await.clone()
954 };
955
956 let all_rules = rules::all_rules(&rumdl_config);
957 let flavor = rumdl_config.markdown_flavor();
958
959 let mut filtered_rules = rules::filter_rules(&all_rules, &rumdl_config.global);
961
962 filtered_rules = self.apply_lsp_config_overrides(filtered_rules, &lsp_config);
964
965 match crate::lint(&text, &filtered_rules, false, flavor) {
967 Ok(warnings) => {
968 log::debug!(
969 "Found {} warnings, {} with fixes",
970 warnings.len(),
971 warnings.iter().filter(|w| w.fix.is_some()).count()
972 );
973
974 let has_fixes = warnings.iter().any(|w| w.fix.is_some());
975 if has_fixes {
976 match crate::utils::fix_utils::apply_warning_fixes(&text, &warnings) {
977 Ok(fixed_content) => {
978 if fixed_content != text {
979 log::debug!("Returning formatting edits");
980 let end_position = self.get_end_position(&text);
981 let edit = TextEdit {
982 range: Range {
983 start: Position { line: 0, character: 0 },
984 end: end_position,
985 },
986 new_text: fixed_content,
987 };
988 return Ok(Some(vec![edit]));
989 }
990 }
991 Err(e) => {
992 log::error!("Failed to apply fixes: {e}");
993 }
994 }
995 }
996 Ok(Some(Vec::new()))
997 }
998 Err(e) => {
999 log::error!("Failed to format document: {e}");
1000 Ok(Some(Vec::new()))
1001 }
1002 }
1003 } else {
1004 log::warn!("Document not found: {uri}");
1005 Ok(None)
1006 }
1007 }
1008
1009 async fn diagnostic(&self, params: DocumentDiagnosticParams) -> JsonRpcResult<DocumentDiagnosticReportResult> {
1010 let uri = params.text_document.uri;
1011
1012 if let Some(text) = self.get_document_content(&uri).await {
1013 match self.lint_document(&uri, &text).await {
1014 Ok(diagnostics) => Ok(DocumentDiagnosticReportResult::Report(DocumentDiagnosticReport::Full(
1015 RelatedFullDocumentDiagnosticReport {
1016 related_documents: None,
1017 full_document_diagnostic_report: FullDocumentDiagnosticReport {
1018 result_id: None,
1019 items: diagnostics,
1020 },
1021 },
1022 ))),
1023 Err(e) => {
1024 log::error!("Failed to get diagnostics: {e}");
1025 Ok(DocumentDiagnosticReportResult::Report(DocumentDiagnosticReport::Full(
1026 RelatedFullDocumentDiagnosticReport {
1027 related_documents: None,
1028 full_document_diagnostic_report: FullDocumentDiagnosticReport {
1029 result_id: None,
1030 items: Vec::new(),
1031 },
1032 },
1033 )))
1034 }
1035 }
1036 } else {
1037 Ok(DocumentDiagnosticReportResult::Report(DocumentDiagnosticReport::Full(
1038 RelatedFullDocumentDiagnosticReport {
1039 related_documents: None,
1040 full_document_diagnostic_report: FullDocumentDiagnosticReport {
1041 result_id: None,
1042 items: Vec::new(),
1043 },
1044 },
1045 )))
1046 }
1047 }
1048}
1049
1050#[cfg(test)]
1051mod tests {
1052 use super::*;
1053 use crate::rule::LintWarning;
1054 use tower_lsp::LspService;
1055
1056 fn create_test_server() -> RumdlLanguageServer {
1057 let (service, _socket) = LspService::new(RumdlLanguageServer::new);
1058 service.inner().clone()
1059 }
1060
1061 #[tokio::test]
1062 async fn test_server_creation() {
1063 let server = create_test_server();
1064
1065 let config = server.config.read().await;
1067 assert!(config.enable_linting);
1068 assert!(!config.enable_auto_fix);
1069 }
1070
1071 #[tokio::test]
1072 async fn test_lint_document() {
1073 let server = create_test_server();
1074
1075 let uri = Url::parse("file:///test.md").unwrap();
1077 let text = "# Test\n\nThis is a test \nWith trailing spaces ";
1078
1079 let diagnostics = server.lint_document(&uri, text).await.unwrap();
1080
1081 assert!(!diagnostics.is_empty());
1083 assert!(diagnostics.iter().any(|d| d.message.contains("trailing")));
1084 }
1085
1086 #[tokio::test]
1087 async fn test_lint_document_disabled() {
1088 let server = create_test_server();
1089
1090 server.config.write().await.enable_linting = false;
1092
1093 let uri = Url::parse("file:///test.md").unwrap();
1094 let text = "# Test\n\nThis is a test \nWith trailing spaces ";
1095
1096 let diagnostics = server.lint_document(&uri, text).await.unwrap();
1097
1098 assert!(diagnostics.is_empty());
1100 }
1101
1102 #[tokio::test]
1103 async fn test_get_code_actions() {
1104 let server = create_test_server();
1105
1106 let uri = Url::parse("file:///test.md").unwrap();
1107 let text = "# Test\n\nThis is a test \nWith trailing spaces ";
1108
1109 let range = Range {
1111 start: Position { line: 0, character: 0 },
1112 end: Position { line: 3, character: 21 },
1113 };
1114
1115 let actions = server.get_code_actions(&uri, text, range).await.unwrap();
1116
1117 assert!(!actions.is_empty());
1119 assert!(actions.iter().any(|a| a.title.contains("trailing")));
1120 }
1121
1122 #[tokio::test]
1123 async fn test_get_code_actions_outside_range() {
1124 let server = create_test_server();
1125
1126 let uri = Url::parse("file:///test.md").unwrap();
1127 let text = "# Test\n\nThis is a test \nWith trailing spaces ";
1128
1129 let range = Range {
1131 start: Position { line: 0, character: 0 },
1132 end: Position { line: 0, character: 6 },
1133 };
1134
1135 let actions = server.get_code_actions(&uri, text, range).await.unwrap();
1136
1137 assert!(actions.is_empty());
1139 }
1140
1141 #[tokio::test]
1142 async fn test_document_storage() {
1143 let server = create_test_server();
1144
1145 let uri = Url::parse("file:///test.md").unwrap();
1146 let text = "# Test Document";
1147
1148 let entry = DocumentEntry {
1150 content: text.to_string(),
1151 version: Some(1),
1152 from_disk: false,
1153 };
1154 server.documents.write().await.insert(uri.clone(), entry);
1155
1156 let stored = server.documents.read().await.get(&uri).map(|e| e.content.clone());
1158 assert_eq!(stored, Some(text.to_string()));
1159
1160 server.documents.write().await.remove(&uri);
1162
1163 let stored = server.documents.read().await.get(&uri).cloned();
1165 assert_eq!(stored, None);
1166 }
1167
1168 #[tokio::test]
1169 async fn test_configuration_loading() {
1170 let server = create_test_server();
1171
1172 server.load_configuration(false).await;
1174
1175 let rumdl_config = server.rumdl_config.read().await;
1178 drop(rumdl_config); }
1181
1182 #[tokio::test]
1183 async fn test_load_config_for_lsp() {
1184 let result = RumdlLanguageServer::load_config_for_lsp(None);
1186 assert!(result.is_ok());
1187
1188 let result = RumdlLanguageServer::load_config_for_lsp(Some("/nonexistent/config.toml"));
1190 assert!(result.is_err());
1191 }
1192
1193 #[tokio::test]
1194 async fn test_warning_conversion() {
1195 let warning = LintWarning {
1196 message: "Test warning".to_string(),
1197 line: 1,
1198 column: 1,
1199 end_line: 1,
1200 end_column: 10,
1201 severity: crate::rule::Severity::Warning,
1202 fix: None,
1203 rule_name: Some("MD001".to_string()),
1204 };
1205
1206 let diagnostic = warning_to_diagnostic(&warning);
1208 assert_eq!(diagnostic.message, "Test warning");
1209 assert_eq!(diagnostic.severity, Some(DiagnosticSeverity::WARNING));
1210 assert_eq!(diagnostic.code, Some(NumberOrString::String("MD001".to_string())));
1211
1212 let uri = Url::parse("file:///test.md").unwrap();
1214 let actions = warning_to_code_actions(&warning, &uri, "Test content");
1215 assert_eq!(actions.len(), 1);
1217 assert_eq!(actions[0].title, "Ignore MD001 for this line");
1218 }
1219
1220 #[tokio::test]
1221 async fn test_multiple_documents() {
1222 let server = create_test_server();
1223
1224 let uri1 = Url::parse("file:///test1.md").unwrap();
1225 let uri2 = Url::parse("file:///test2.md").unwrap();
1226 let text1 = "# Document 1";
1227 let text2 = "# Document 2";
1228
1229 {
1231 let mut docs = server.documents.write().await;
1232 let entry1 = DocumentEntry {
1233 content: text1.to_string(),
1234 version: Some(1),
1235 from_disk: false,
1236 };
1237 let entry2 = DocumentEntry {
1238 content: text2.to_string(),
1239 version: Some(1),
1240 from_disk: false,
1241 };
1242 docs.insert(uri1.clone(), entry1);
1243 docs.insert(uri2.clone(), entry2);
1244 }
1245
1246 let docs = server.documents.read().await;
1248 assert_eq!(docs.len(), 2);
1249 assert_eq!(docs.get(&uri1).map(|s| s.content.as_str()), Some(text1));
1250 assert_eq!(docs.get(&uri2).map(|s| s.content.as_str()), Some(text2));
1251 }
1252
1253 #[tokio::test]
1254 async fn test_auto_fix_on_save() {
1255 let server = create_test_server();
1256
1257 {
1259 let mut config = server.config.write().await;
1260 config.enable_auto_fix = true;
1261 }
1262
1263 let uri = Url::parse("file:///test.md").unwrap();
1264 let text = "#Heading without space"; let entry = DocumentEntry {
1268 content: text.to_string(),
1269 version: Some(1),
1270 from_disk: false,
1271 };
1272 server.documents.write().await.insert(uri.clone(), entry);
1273
1274 let fixed = server.apply_all_fixes(&uri, text).await.unwrap();
1276 assert!(fixed.is_some());
1277 assert_eq!(fixed.unwrap(), "# Heading without space\n");
1279 }
1280
1281 #[tokio::test]
1282 async fn test_get_end_position() {
1283 let server = create_test_server();
1284
1285 let pos = server.get_end_position("Hello");
1287 assert_eq!(pos.line, 0);
1288 assert_eq!(pos.character, 5);
1289
1290 let pos = server.get_end_position("Hello\nWorld\nTest");
1292 assert_eq!(pos.line, 2);
1293 assert_eq!(pos.character, 4);
1294
1295 let pos = server.get_end_position("");
1297 assert_eq!(pos.line, 0);
1298 assert_eq!(pos.character, 0);
1299
1300 let pos = server.get_end_position("Hello\n");
1302 assert_eq!(pos.line, 1);
1303 assert_eq!(pos.character, 0);
1304 }
1305
1306 #[tokio::test]
1307 async fn test_empty_document_handling() {
1308 let server = create_test_server();
1309
1310 let uri = Url::parse("file:///empty.md").unwrap();
1311 let text = "";
1312
1313 let diagnostics = server.lint_document(&uri, text).await.unwrap();
1315 assert!(diagnostics.is_empty());
1316
1317 let range = Range {
1319 start: Position { line: 0, character: 0 },
1320 end: Position { line: 0, character: 0 },
1321 };
1322 let actions = server.get_code_actions(&uri, text, range).await.unwrap();
1323 assert!(actions.is_empty());
1324 }
1325
1326 #[tokio::test]
1327 async fn test_config_update() {
1328 let server = create_test_server();
1329
1330 {
1332 let mut config = server.config.write().await;
1333 config.enable_auto_fix = true;
1334 config.config_path = Some("/custom/path.toml".to_string());
1335 }
1336
1337 let config = server.config.read().await;
1339 assert!(config.enable_auto_fix);
1340 assert_eq!(config.config_path, Some("/custom/path.toml".to_string()));
1341 }
1342
1343 #[tokio::test]
1344 async fn test_document_formatting() {
1345 let server = create_test_server();
1346 let uri = Url::parse("file:///test.md").unwrap();
1347 let text = "# Test\n\nThis is a test \nWith trailing spaces ";
1348
1349 let entry = DocumentEntry {
1351 content: text.to_string(),
1352 version: Some(1),
1353 from_disk: false,
1354 };
1355 server.documents.write().await.insert(uri.clone(), entry);
1356
1357 let params = DocumentFormattingParams {
1359 text_document: TextDocumentIdentifier { uri: uri.clone() },
1360 options: FormattingOptions {
1361 tab_size: 4,
1362 insert_spaces: true,
1363 properties: HashMap::new(),
1364 trim_trailing_whitespace: Some(true),
1365 insert_final_newline: Some(true),
1366 trim_final_newlines: Some(true),
1367 },
1368 work_done_progress_params: WorkDoneProgressParams::default(),
1369 };
1370
1371 let result = server.formatting(params).await.unwrap();
1373
1374 assert!(result.is_some());
1376 let edits = result.unwrap();
1377 assert!(!edits.is_empty());
1378
1379 let edit = &edits[0];
1381 let expected = "# Test\n\nThis is a test \nWith trailing spaces\n";
1384 assert_eq!(edit.new_text, expected);
1385 }
1386
1387 #[tokio::test]
1389 async fn test_resolve_config_for_file_multi_root() {
1390 use std::fs;
1391 use tempfile::tempdir;
1392
1393 let temp_dir = tempdir().unwrap();
1394 let temp_path = temp_dir.path();
1395
1396 let project_a = temp_path.join("project_a");
1398 let project_a_docs = project_a.join("docs");
1399 fs::create_dir_all(&project_a_docs).unwrap();
1400
1401 let config_a = project_a.join(".rumdl.toml");
1402 fs::write(
1403 &config_a,
1404 r#"
1405[global]
1406
1407[MD013]
1408line_length = 60
1409"#,
1410 )
1411 .unwrap();
1412
1413 let project_b = temp_path.join("project_b");
1415 fs::create_dir(&project_b).unwrap();
1416
1417 let config_b = project_b.join(".rumdl.toml");
1418 fs::write(
1419 &config_b,
1420 r#"
1421[global]
1422
1423[MD013]
1424line_length = 120
1425"#,
1426 )
1427 .unwrap();
1428
1429 let server = create_test_server();
1431
1432 {
1434 let mut roots = server.workspace_roots.write().await;
1435 roots.push(project_a.clone());
1436 roots.push(project_b.clone());
1437 }
1438
1439 let file_a = project_a_docs.join("test.md");
1441 fs::write(&file_a, "# Test A\n").unwrap();
1442
1443 let config_for_a = server.resolve_config_for_file(&file_a).await;
1444 let line_length_a = crate::config::get_rule_config_value::<usize>(&config_for_a, "MD013", "line_length");
1445 assert_eq!(line_length_a, Some(60), "File in project_a should get line_length=60");
1446
1447 let file_b = project_b.join("test.md");
1449 fs::write(&file_b, "# Test B\n").unwrap();
1450
1451 let config_for_b = server.resolve_config_for_file(&file_b).await;
1452 let line_length_b = crate::config::get_rule_config_value::<usize>(&config_for_b, "MD013", "line_length");
1453 assert_eq!(line_length_b, Some(120), "File in project_b should get line_length=120");
1454 }
1455
1456 #[tokio::test]
1458 async fn test_config_resolution_respects_workspace_boundaries() {
1459 use std::fs;
1460 use tempfile::tempdir;
1461
1462 let temp_dir = tempdir().unwrap();
1463 let temp_path = temp_dir.path();
1464
1465 let parent_config = temp_path.join(".rumdl.toml");
1467 fs::write(
1468 &parent_config,
1469 r#"
1470[global]
1471
1472[MD013]
1473line_length = 80
1474"#,
1475 )
1476 .unwrap();
1477
1478 let workspace_root = temp_path.join("workspace");
1480 let workspace_subdir = workspace_root.join("subdir");
1481 fs::create_dir_all(&workspace_subdir).unwrap();
1482
1483 let workspace_config = workspace_root.join(".rumdl.toml");
1484 fs::write(
1485 &workspace_config,
1486 r#"
1487[global]
1488
1489[MD013]
1490line_length = 100
1491"#,
1492 )
1493 .unwrap();
1494
1495 let server = create_test_server();
1496
1497 {
1499 let mut roots = server.workspace_roots.write().await;
1500 roots.push(workspace_root.clone());
1501 }
1502
1503 let test_file = workspace_subdir.join("deep").join("test.md");
1505 fs::create_dir_all(test_file.parent().unwrap()).unwrap();
1506 fs::write(&test_file, "# Test\n").unwrap();
1507
1508 let config = server.resolve_config_for_file(&test_file).await;
1509 let line_length = crate::config::get_rule_config_value::<usize>(&config, "MD013", "line_length");
1510
1511 assert_eq!(
1513 line_length,
1514 Some(100),
1515 "Should find workspace config, not parent config outside workspace"
1516 );
1517 }
1518
1519 #[tokio::test]
1521 async fn test_config_cache_hit() {
1522 use std::fs;
1523 use tempfile::tempdir;
1524
1525 let temp_dir = tempdir().unwrap();
1526 let temp_path = temp_dir.path();
1527
1528 let project = temp_path.join("project");
1529 fs::create_dir(&project).unwrap();
1530
1531 let config_file = project.join(".rumdl.toml");
1532 fs::write(
1533 &config_file,
1534 r#"
1535[global]
1536
1537[MD013]
1538line_length = 75
1539"#,
1540 )
1541 .unwrap();
1542
1543 let server = create_test_server();
1544 {
1545 let mut roots = server.workspace_roots.write().await;
1546 roots.push(project.clone());
1547 }
1548
1549 let test_file = project.join("test.md");
1550 fs::write(&test_file, "# Test\n").unwrap();
1551
1552 let config1 = server.resolve_config_for_file(&test_file).await;
1554 let line_length1 = crate::config::get_rule_config_value::<usize>(&config1, "MD013", "line_length");
1555 assert_eq!(line_length1, Some(75));
1556
1557 {
1559 let cache = server.config_cache.read().await;
1560 let search_dir = test_file.parent().unwrap();
1561 assert!(
1562 cache.contains_key(search_dir),
1563 "Cache should be populated after first call"
1564 );
1565 }
1566
1567 let config2 = server.resolve_config_for_file(&test_file).await;
1569 let line_length2 = crate::config::get_rule_config_value::<usize>(&config2, "MD013", "line_length");
1570 assert_eq!(line_length2, Some(75));
1571 }
1572
1573 #[tokio::test]
1575 async fn test_nested_directory_config_search() {
1576 use std::fs;
1577 use tempfile::tempdir;
1578
1579 let temp_dir = tempdir().unwrap();
1580 let temp_path = temp_dir.path();
1581
1582 let project = temp_path.join("project");
1583 fs::create_dir(&project).unwrap();
1584
1585 let config = project.join(".rumdl.toml");
1587 fs::write(
1588 &config,
1589 r#"
1590[global]
1591
1592[MD013]
1593line_length = 110
1594"#,
1595 )
1596 .unwrap();
1597
1598 let deep_dir = project.join("src").join("docs").join("guides");
1600 fs::create_dir_all(&deep_dir).unwrap();
1601 let deep_file = deep_dir.join("test.md");
1602 fs::write(&deep_file, "# Test\n").unwrap();
1603
1604 let server = create_test_server();
1605 {
1606 let mut roots = server.workspace_roots.write().await;
1607 roots.push(project.clone());
1608 }
1609
1610 let resolved_config = server.resolve_config_for_file(&deep_file).await;
1611 let line_length = crate::config::get_rule_config_value::<usize>(&resolved_config, "MD013", "line_length");
1612
1613 assert_eq!(
1614 line_length,
1615 Some(110),
1616 "Should find config by searching upward from deep directory"
1617 );
1618 }
1619
1620 #[tokio::test]
1622 async fn test_fallback_to_default_config() {
1623 use std::fs;
1624 use tempfile::tempdir;
1625
1626 let temp_dir = tempdir().unwrap();
1627 let temp_path = temp_dir.path();
1628
1629 let project = temp_path.join("project");
1630 fs::create_dir(&project).unwrap();
1631
1632 let test_file = project.join("test.md");
1635 fs::write(&test_file, "# Test\n").unwrap();
1636
1637 let server = create_test_server();
1638 {
1639 let mut roots = server.workspace_roots.write().await;
1640 roots.push(project.clone());
1641 }
1642
1643 let config = server.resolve_config_for_file(&test_file).await;
1644
1645 assert_eq!(
1647 config.global.line_length, 80,
1648 "Should fall back to default config when no config file found"
1649 );
1650 }
1651
1652 #[tokio::test]
1654 async fn test_config_priority_closer_wins() {
1655 use std::fs;
1656 use tempfile::tempdir;
1657
1658 let temp_dir = tempdir().unwrap();
1659 let temp_path = temp_dir.path();
1660
1661 let project = temp_path.join("project");
1662 fs::create_dir(&project).unwrap();
1663
1664 let parent_config = project.join(".rumdl.toml");
1666 fs::write(
1667 &parent_config,
1668 r#"
1669[global]
1670
1671[MD013]
1672line_length = 100
1673"#,
1674 )
1675 .unwrap();
1676
1677 let subdir = project.join("subdir");
1679 fs::create_dir(&subdir).unwrap();
1680
1681 let subdir_config = subdir.join(".rumdl.toml");
1682 fs::write(
1683 &subdir_config,
1684 r#"
1685[global]
1686
1687[MD013]
1688line_length = 50
1689"#,
1690 )
1691 .unwrap();
1692
1693 let server = create_test_server();
1694 {
1695 let mut roots = server.workspace_roots.write().await;
1696 roots.push(project.clone());
1697 }
1698
1699 let test_file = subdir.join("test.md");
1701 fs::write(&test_file, "# Test\n").unwrap();
1702
1703 let config = server.resolve_config_for_file(&test_file).await;
1704 let line_length = crate::config::get_rule_config_value::<usize>(&config, "MD013", "line_length");
1705
1706 assert_eq!(
1707 line_length,
1708 Some(50),
1709 "Closer config (subdir) should override parent config"
1710 );
1711 }
1712}