1use std::collections::HashMap;
7use std::path::PathBuf;
8use std::sync::Arc;
9
10use futures::future::join_all;
11use tokio::sync::{RwLock, mpsc};
12use tower_lsp::jsonrpc::Result as JsonRpcResult;
13use tower_lsp::lsp_types::*;
14use tower_lsp::{Client, LanguageServer};
15
16use crate::config::{Config, is_valid_rule_name};
17use crate::lsp::index_worker::IndexWorker;
18use crate::lsp::types::{IndexState, IndexUpdate, LspRuleSettings, RumdlLspConfig};
19use crate::rule::FixCapability;
20use crate::rules;
21use crate::workspace_index::WorkspaceIndex;
22
23const MARKDOWN_EXTENSIONS: &[&str] = &["md", "markdown", "mdx", "mkd", "mkdn", "mdown", "mdwn", "qmd", "rmd"];
25
26const MAX_RULE_LIST_SIZE: usize = 100;
28
29const MAX_LINE_LENGTH: usize = 10_000;
31
32#[inline]
34fn is_markdown_extension(ext: &str) -> bool {
35 MARKDOWN_EXTENSIONS.contains(&ext.to_lowercase().as_str())
36}
37
38#[derive(Clone, Debug, PartialEq)]
40pub(crate) struct DocumentEntry {
41 pub(crate) content: String,
43 pub(crate) version: Option<i32>,
45 pub(crate) from_disk: bool,
47}
48
49#[derive(Clone, Debug)]
51pub(crate) struct ConfigCacheEntry {
52 pub(crate) config: Config,
54 pub(crate) config_file: Option<PathBuf>,
56 pub(crate) from_global_fallback: bool,
58}
59
60#[derive(Clone)]
70pub struct RumdlLanguageServer {
71 pub(crate) client: Client,
72 pub(crate) config: Arc<RwLock<RumdlLspConfig>>,
74 pub(crate) rumdl_config: Arc<RwLock<Config>>,
76 pub(crate) documents: Arc<RwLock<HashMap<Url, DocumentEntry>>>,
78 pub(crate) workspace_roots: Arc<RwLock<Vec<PathBuf>>>,
80 pub(crate) config_cache: Arc<RwLock<HashMap<PathBuf, ConfigCacheEntry>>>,
83 pub(crate) workspace_index: Arc<RwLock<WorkspaceIndex>>,
85 pub(crate) index_state: Arc<RwLock<IndexState>>,
87 pub(crate) update_tx: mpsc::Sender<IndexUpdate>,
89 pub(crate) client_supports_pull_diagnostics: Arc<RwLock<bool>>,
92}
93
94impl RumdlLanguageServer {
95 pub fn new(client: Client, cli_config_path: Option<&str>) -> Self {
96 let mut initial_config = RumdlLspConfig::default();
98 if let Some(path) = cli_config_path {
99 initial_config.config_path = Some(path.to_string());
100 }
101
102 let workspace_index = Arc::new(RwLock::new(WorkspaceIndex::new()));
104 let index_state = Arc::new(RwLock::new(IndexState::default()));
105 let workspace_roots = Arc::new(RwLock::new(Vec::new()));
106
107 let (update_tx, update_rx) = mpsc::channel::<IndexUpdate>(100);
109 let (relint_tx, _relint_rx) = mpsc::channel::<PathBuf>(100);
110
111 let worker = IndexWorker::new(
113 update_rx,
114 workspace_index.clone(),
115 index_state.clone(),
116 client.clone(),
117 workspace_roots.clone(),
118 relint_tx,
119 );
120 tokio::spawn(worker.run());
121
122 Self {
123 client,
124 config: Arc::new(RwLock::new(initial_config)),
125 rumdl_config: Arc::new(RwLock::new(Config::default())),
126 documents: Arc::new(RwLock::new(HashMap::new())),
127 workspace_roots,
128 config_cache: Arc::new(RwLock::new(HashMap::new())),
129 workspace_index,
130 index_state,
131 update_tx,
132 client_supports_pull_diagnostics: Arc::new(RwLock::new(false)),
133 }
134 }
135
136 pub(super) async fn get_document_content(&self, uri: &Url) -> Option<String> {
142 {
144 let docs = self.documents.read().await;
145 if let Some(entry) = docs.get(uri) {
146 return Some(entry.content.clone());
147 }
148 }
149
150 if let Ok(path) = uri.to_file_path() {
152 if let Ok(content) = tokio::fs::read_to_string(&path).await {
153 let entry = DocumentEntry {
155 content: content.clone(),
156 version: None,
157 from_disk: true,
158 };
159
160 let mut docs = self.documents.write().await;
161 docs.insert(uri.clone(), entry);
162
163 log::debug!("Loaded document from disk and cached: {uri}");
164 return Some(content);
165 } else {
166 log::debug!("Failed to read file from disk: {uri}");
167 }
168 }
169
170 None
171 }
172
173 async fn get_open_document_content(&self, uri: &Url) -> Option<String> {
179 let docs = self.documents.read().await;
180 docs.get(uri)
181 .and_then(|entry| (!entry.from_disk).then(|| entry.content.clone()))
182 }
183}
184
185#[tower_lsp::async_trait]
186impl LanguageServer for RumdlLanguageServer {
187 async fn initialize(&self, params: InitializeParams) -> JsonRpcResult<InitializeResult> {
188 log::info!("Initializing rumdl Language Server");
189
190 if let Some(options) = params.initialization_options
192 && let Ok(config) = serde_json::from_value::<RumdlLspConfig>(options)
193 {
194 *self.config.write().await = config;
195 }
196
197 let supports_pull = params
200 .capabilities
201 .text_document
202 .as_ref()
203 .and_then(|td| td.diagnostic.as_ref())
204 .is_some();
205
206 if supports_pull {
207 log::info!("Client supports pull diagnostics - disabling push to avoid duplicates");
208 *self.client_supports_pull_diagnostics.write().await = true;
209 } else {
210 log::info!("Client does not support pull diagnostics - using push model");
211 }
212
213 let mut roots = Vec::new();
215 if let Some(workspace_folders) = params.workspace_folders {
216 for folder in workspace_folders {
217 if let Ok(path) = folder.uri.to_file_path() {
218 let path = path.canonicalize().unwrap_or(path);
219 log::info!("Workspace root: {}", path.display());
220 roots.push(path);
221 }
222 }
223 } else if let Some(root_uri) = params.root_uri
224 && let Ok(path) = root_uri.to_file_path()
225 {
226 let path = path.canonicalize().unwrap_or(path);
227 log::info!("Workspace root: {}", path.display());
228 roots.push(path);
229 }
230 *self.workspace_roots.write().await = roots;
231
232 self.load_configuration(false).await;
234
235 Ok(InitializeResult {
236 capabilities: ServerCapabilities {
237 text_document_sync: Some(TextDocumentSyncCapability::Options(TextDocumentSyncOptions {
238 open_close: Some(true),
239 change: Some(TextDocumentSyncKind::FULL),
240 will_save: Some(false),
241 will_save_wait_until: Some(true),
242 save: Some(TextDocumentSyncSaveOptions::SaveOptions(SaveOptions {
243 include_text: Some(false),
244 })),
245 })),
246 code_action_provider: Some(CodeActionProviderCapability::Options(CodeActionOptions {
247 code_action_kinds: Some(vec![
248 CodeActionKind::QUICKFIX,
249 CodeActionKind::SOURCE_FIX_ALL,
250 CodeActionKind::new("source.fixAll.rumdl"),
251 ]),
252 work_done_progress_options: WorkDoneProgressOptions::default(),
253 resolve_provider: None,
254 })),
255 document_formatting_provider: Some(OneOf::Left(true)),
256 document_range_formatting_provider: Some(OneOf::Left(true)),
257 diagnostic_provider: Some(DiagnosticServerCapabilities::Options(DiagnosticOptions {
258 identifier: Some("rumdl".to_string()),
259 inter_file_dependencies: true,
260 workspace_diagnostics: false,
261 work_done_progress_options: WorkDoneProgressOptions::default(),
262 })),
263 completion_provider: Some(CompletionOptions {
264 trigger_characters: Some(vec![
265 "`".to_string(),
266 "(".to_string(),
267 "#".to_string(),
268 "/".to_string(),
269 ".".to_string(),
270 "-".to_string(),
271 ]),
272 resolve_provider: Some(false),
273 work_done_progress_options: WorkDoneProgressOptions::default(),
274 all_commit_characters: None,
275 completion_item: None,
276 }),
277 definition_provider: Some(OneOf::Left(true)),
278 references_provider: Some(OneOf::Left(true)),
279 hover_provider: Some(HoverProviderCapability::Simple(true)),
280 rename_provider: Some(OneOf::Right(RenameOptions {
281 prepare_provider: Some(true),
282 work_done_progress_options: WorkDoneProgressOptions::default(),
283 })),
284 workspace: Some(WorkspaceServerCapabilities {
285 workspace_folders: Some(WorkspaceFoldersServerCapabilities {
286 supported: Some(true),
287 change_notifications: Some(OneOf::Left(true)),
288 }),
289 file_operations: None,
290 }),
291 ..Default::default()
292 },
293 server_info: Some(ServerInfo {
294 name: "rumdl".to_string(),
295 version: Some(env!("CARGO_PKG_VERSION").to_string()),
296 }),
297 })
298 }
299
300 async fn initialized(&self, _: InitializedParams) {
301 let version = env!("CARGO_PKG_VERSION");
302
303 let (binary_path, build_time) = std::env::current_exe()
305 .ok()
306 .map(|path| {
307 let path_str = path.to_str().unwrap_or("unknown").to_string();
308 let build_time = std::fs::metadata(&path)
309 .ok()
310 .and_then(|metadata| metadata.modified().ok())
311 .and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok())
312 .and_then(|duration| {
313 let secs = duration.as_secs();
314 chrono::DateTime::from_timestamp(secs as i64, 0)
315 .map(|dt| dt.format("%Y-%m-%d %H:%M:%S UTC").to_string())
316 })
317 .unwrap_or_else(|| "unknown".to_string());
318 (path_str, build_time)
319 })
320 .unwrap_or_else(|| ("unknown".to_string(), "unknown".to_string()));
321
322 let working_dir = std::env::current_dir()
323 .ok()
324 .and_then(|p| p.to_str().map(|s| s.to_string()))
325 .unwrap_or_else(|| "unknown".to_string());
326
327 log::info!("rumdl Language Server v{version} initialized (built: {build_time}, binary: {binary_path})");
328 log::info!("Working directory: {working_dir}");
329
330 self.client
331 .log_message(MessageType::INFO, format!("rumdl v{version} Language Server started"))
332 .await;
333
334 if self.update_tx.send(IndexUpdate::FullRescan).await.is_err() {
336 log::warn!("Failed to trigger initial workspace indexing");
337 } else {
338 log::info!("Triggered initial workspace indexing for cross-file analysis");
339 }
340
341 let markdown_patterns = [
343 "**/*.md",
344 "**/*.markdown",
345 "**/*.mdx",
346 "**/*.mkd",
347 "**/*.mkdn",
348 "**/*.mdown",
349 "**/*.mdwn",
350 "**/*.qmd",
351 "**/*.rmd",
352 ];
353 let config_patterns = [
354 "**/.rumdl.toml",
355 "**/rumdl.toml",
356 "**/pyproject.toml",
357 "**/.markdownlint.json",
358 ];
359 let watchers: Vec<_> = markdown_patterns
360 .iter()
361 .chain(config_patterns.iter())
362 .map(|pattern| FileSystemWatcher {
363 glob_pattern: GlobPattern::String((*pattern).to_string()),
364 kind: Some(WatchKind::all()),
365 })
366 .collect();
367
368 let registration = Registration {
369 id: "markdown-watcher".to_string(),
370 method: "workspace/didChangeWatchedFiles".to_string(),
371 register_options: Some(
372 serde_json::to_value(DidChangeWatchedFilesRegistrationOptions { watchers }).unwrap(),
373 ),
374 };
375
376 if self.client.register_capability(vec![registration]).await.is_err() {
377 log::debug!("Client does not support file watching capability");
378 }
379 }
380
381 async fn completion(&self, params: CompletionParams) -> JsonRpcResult<Option<CompletionResponse>> {
382 let uri = params.text_document_position.text_document.uri;
383 let position = params.text_document_position.position;
384
385 let Some(text) = self.get_document_content(&uri).await else {
387 return Ok(None);
388 };
389
390 if let Some((start_col, current_text)) = Self::detect_code_fence_language_position(&text, position) {
392 log::debug!(
393 "Code fence completion triggered at {}:{}, current text: '{}'",
394 position.line,
395 position.character,
396 current_text
397 );
398 let items = self
399 .get_language_completions(&uri, ¤t_text, start_col, position)
400 .await;
401 if !items.is_empty() {
402 return Ok(Some(CompletionResponse::Array(items)));
403 }
404 }
405
406 if self.config.read().await.enable_link_completions {
408 let trigger = params.context.as_ref().and_then(|c| c.trigger_character.as_deref());
412 let skip_link_check = matches!(trigger, Some("." | "-")) && {
413 let line_num = position.line as usize;
414 !text
417 .lines()
418 .nth(line_num)
419 .map(|line| line.contains("]("))
420 .unwrap_or(false)
421 };
422
423 if !skip_link_check && let Some(link_info) = Self::detect_link_target_position(&text, position) {
424 let items = if let Some((partial_anchor, anchor_start_col)) = link_info.anchor {
425 log::debug!(
426 "Anchor completion triggered at {}:{}, file: '{}', partial: '{}'",
427 position.line,
428 position.character,
429 link_info.file_path,
430 partial_anchor
431 );
432 self.get_anchor_completions(&uri, &link_info.file_path, &partial_anchor, anchor_start_col, position)
433 .await
434 } else {
435 log::debug!(
436 "File path completion triggered at {}:{}, partial: '{}'",
437 position.line,
438 position.character,
439 link_info.file_path
440 );
441 self.get_file_completions(&uri, &link_info.file_path, link_info.path_start_col, position)
442 .await
443 };
444 if !items.is_empty() {
445 return Ok(Some(CompletionResponse::Array(items)));
446 }
447 }
448 }
449
450 Ok(None)
451 }
452
453 async fn did_change_workspace_folders(&self, params: DidChangeWorkspaceFoldersParams) {
454 let mut roots = self.workspace_roots.write().await;
456
457 for removed in ¶ms.event.removed {
459 if let Ok(path) = removed.uri.to_file_path() {
460 roots.retain(|r| r != &path);
461 log::info!("Removed workspace root: {}", path.display());
462 }
463 }
464
465 for added in ¶ms.event.added {
467 if let Ok(path) = added.uri.to_file_path()
468 && !roots.contains(&path)
469 {
470 log::info!("Added workspace root: {}", path.display());
471 roots.push(path);
472 }
473 }
474 drop(roots);
475
476 self.config_cache.write().await.clear();
478
479 self.reload_configuration().await;
481
482 if self.update_tx.send(IndexUpdate::FullRescan).await.is_err() {
484 log::warn!("Failed to trigger workspace rescan after folder change");
485 }
486 }
487
488 async fn did_change_configuration(&self, params: DidChangeConfigurationParams) {
489 log::debug!("Configuration changed: {:?}", params.settings);
490
491 let settings_value = params.settings;
495
496 let rumdl_settings = if let serde_json::Value::Object(ref obj) = settings_value {
498 obj.get("rumdl").cloned().unwrap_or(settings_value.clone())
499 } else {
500 settings_value
501 };
502
503 let mut config_applied = false;
505 let mut warnings: Vec<String> = Vec::new();
506
507 if let Ok(rule_settings) = serde_json::from_value::<LspRuleSettings>(rumdl_settings.clone())
511 && (rule_settings.disable.is_some()
512 || rule_settings.enable.is_some()
513 || rule_settings.line_length.is_some()
514 || !rule_settings.rules.is_empty())
515 {
516 if let Some(ref disable) = rule_settings.disable {
518 for rule in disable {
519 if !is_valid_rule_name(rule) {
520 warnings.push(format!("Unknown rule in disable list: {rule}"));
521 }
522 }
523 }
524 if let Some(ref enable) = rule_settings.enable {
525 for rule in enable {
526 if !is_valid_rule_name(rule) {
527 warnings.push(format!("Unknown rule in enable list: {rule}"));
528 }
529 }
530 }
531 for rule_name in rule_settings.rules.keys() {
533 if !is_valid_rule_name(rule_name) {
534 warnings.push(format!("Unknown rule in settings: {rule_name}"));
535 }
536 }
537
538 log::info!("Applied rule settings from configuration (Neovim style)");
539 let mut config = self.config.write().await;
540 config.settings = Some(rule_settings);
541 drop(config);
542 config_applied = true;
543 } else if let Ok(full_config) = serde_json::from_value::<RumdlLspConfig>(rumdl_settings.clone())
544 && (full_config.config_path.is_some()
545 || full_config.enable_rules.is_some()
546 || full_config.disable_rules.is_some()
547 || full_config.settings.is_some()
548 || !full_config.enable_linting
549 || full_config.enable_auto_fix)
550 {
551 if let Some(ref rules) = full_config.enable_rules {
553 for rule in rules {
554 if !is_valid_rule_name(rule) {
555 warnings.push(format!("Unknown rule in enableRules: {rule}"));
556 }
557 }
558 }
559 if let Some(ref rules) = full_config.disable_rules {
560 for rule in rules {
561 if !is_valid_rule_name(rule) {
562 warnings.push(format!("Unknown rule in disableRules: {rule}"));
563 }
564 }
565 }
566
567 log::info!("Applied full LSP configuration from settings");
568 *self.config.write().await = full_config;
569 config_applied = true;
570 } else if let serde_json::Value::Object(obj) = rumdl_settings {
571 let mut config = self.config.write().await;
574
575 let mut rules = std::collections::HashMap::new();
577 let mut disable = Vec::new();
578 let mut enable = Vec::new();
579 let mut line_length = None;
580
581 for (key, value) in obj {
582 match key.as_str() {
583 "disable" => match serde_json::from_value::<Vec<String>>(value.clone()) {
584 Ok(d) => {
585 if d.len() > MAX_RULE_LIST_SIZE {
586 warnings.push(format!(
587 "Too many rules in 'disable' ({} > {}), truncating",
588 d.len(),
589 MAX_RULE_LIST_SIZE
590 ));
591 }
592 for rule in d.iter().take(MAX_RULE_LIST_SIZE) {
593 if !is_valid_rule_name(rule) {
594 warnings.push(format!("Unknown rule in disable: {rule}"));
595 }
596 }
597 disable = d.into_iter().take(MAX_RULE_LIST_SIZE).collect();
598 }
599 Err(_) => {
600 warnings.push(format!(
601 "Invalid 'disable' value: expected array of strings, got {value}"
602 ));
603 }
604 },
605 "enable" => match serde_json::from_value::<Vec<String>>(value.clone()) {
606 Ok(e) => {
607 if e.len() > MAX_RULE_LIST_SIZE {
608 warnings.push(format!(
609 "Too many rules in 'enable' ({} > {}), truncating",
610 e.len(),
611 MAX_RULE_LIST_SIZE
612 ));
613 }
614 for rule in e.iter().take(MAX_RULE_LIST_SIZE) {
615 if !is_valid_rule_name(rule) {
616 warnings.push(format!("Unknown rule in enable: {rule}"));
617 }
618 }
619 enable = e.into_iter().take(MAX_RULE_LIST_SIZE).collect();
620 }
621 Err(_) => {
622 warnings.push(format!(
623 "Invalid 'enable' value: expected array of strings, got {value}"
624 ));
625 }
626 },
627 "lineLength" | "line_length" | "line-length" => {
628 if let Some(l) = value.as_u64() {
629 match usize::try_from(l) {
630 Ok(len) if len <= MAX_LINE_LENGTH => line_length = Some(len),
631 Ok(len) => warnings.push(format!(
632 "Invalid 'lineLength' value: {len} exceeds maximum ({MAX_LINE_LENGTH})"
633 )),
634 Err(_) => warnings.push(format!("Invalid 'lineLength' value: {l} is too large")),
635 }
636 } else {
637 warnings.push(format!("Invalid 'lineLength' value: expected number, got {value}"));
638 }
639 }
640 _ if key.starts_with("MD") || key.starts_with("md") => {
642 let normalized = key.to_uppercase();
643 if !is_valid_rule_name(&normalized) {
644 warnings.push(format!("Unknown rule: {key}"));
645 }
646 rules.insert(normalized, value);
647 }
648 _ => {
649 warnings.push(format!("Unknown configuration key: {key}"));
651 }
652 }
653 }
654
655 let settings = LspRuleSettings {
656 line_length,
657 disable: if disable.is_empty() { None } else { Some(disable) },
658 enable: if enable.is_empty() { None } else { Some(enable) },
659 rules,
660 };
661
662 log::info!("Applied Neovim-style rule settings (manual parse)");
663 config.settings = Some(settings);
664 drop(config);
665 config_applied = true;
666 } else {
667 log::warn!("Could not parse configuration settings: {rumdl_settings:?}");
668 }
669
670 for warning in &warnings {
672 log::warn!("{warning}");
673 }
674
675 if !warnings.is_empty() {
677 let message = if warnings.len() == 1 {
678 format!("rumdl: {}", warnings[0])
679 } else {
680 format!("rumdl configuration warnings:\n{}", warnings.join("\n"))
681 };
682 self.client.log_message(MessageType::WARNING, message).await;
683 }
684
685 if !config_applied {
686 log::debug!("No configuration changes applied");
687 }
688
689 self.config_cache.write().await.clear();
691
692 let doc_list: Vec<_> = {
694 let documents = self.documents.read().await;
695 documents
696 .iter()
697 .map(|(uri, entry)| (uri.clone(), entry.content.clone()))
698 .collect()
699 };
700
701 let tasks = doc_list.into_iter().map(|(uri, text)| {
703 let server = self.clone();
704 tokio::spawn(async move {
705 server.update_diagnostics(uri, text, true).await;
706 })
707 });
708
709 let _ = join_all(tasks).await;
711 }
712
713 async fn shutdown(&self) -> JsonRpcResult<()> {
714 log::info!("Shutting down rumdl Language Server");
715
716 let _ = self.update_tx.send(IndexUpdate::Shutdown).await;
718
719 Ok(())
720 }
721
722 async fn did_open(&self, params: DidOpenTextDocumentParams) {
723 let uri = params.text_document.uri;
724 let text = params.text_document.text;
725 let version = params.text_document.version;
726
727 let entry = DocumentEntry {
728 content: text.clone(),
729 version: Some(version),
730 from_disk: false,
731 };
732 self.documents.write().await.insert(uri.clone(), entry);
733
734 if let Ok(path) = uri.to_file_path() {
736 let _ = self
737 .update_tx
738 .send(IndexUpdate::FileChanged {
739 path,
740 content: text.clone(),
741 })
742 .await;
743 }
744
745 self.update_diagnostics(uri, text, true).await;
746 }
747
748 async fn did_change(&self, params: DidChangeTextDocumentParams) {
749 let uri = params.text_document.uri;
750 let version = params.text_document.version;
751
752 if let Some(change) = params.content_changes.into_iter().next() {
753 let text = change.text;
754
755 let entry = DocumentEntry {
756 content: text.clone(),
757 version: Some(version),
758 from_disk: false,
759 };
760 self.documents.write().await.insert(uri.clone(), entry);
761
762 if let Ok(path) = uri.to_file_path() {
764 let _ = self
765 .update_tx
766 .send(IndexUpdate::FileChanged {
767 path,
768 content: text.clone(),
769 })
770 .await;
771 }
772
773 self.update_diagnostics(uri, text, false).await;
774 }
775 }
776
777 async fn will_save_wait_until(&self, params: WillSaveTextDocumentParams) -> JsonRpcResult<Option<Vec<TextEdit>>> {
778 if params.reason != TextDocumentSaveReason::MANUAL {
781 return Ok(None);
782 }
783
784 let config_guard = self.config.read().await;
785 let enable_auto_fix = config_guard.enable_auto_fix;
786 drop(config_guard);
787
788 if !enable_auto_fix {
789 return Ok(None);
790 }
791
792 let Some(text) = self.get_document_content(¶ms.text_document.uri).await else {
794 return Ok(None);
795 };
796
797 match self.apply_all_fixes(¶ms.text_document.uri, &text).await {
799 Ok(Some(fixed_text)) => {
800 Ok(Some(vec![TextEdit {
802 range: Range {
803 start: Position { line: 0, character: 0 },
804 end: self.get_end_position(&text),
805 },
806 new_text: fixed_text,
807 }]))
808 }
809 Ok(None) => Ok(None),
810 Err(e) => {
811 log::error!("Failed to generate fixes in will_save_wait_until: {e}");
812 Ok(None)
813 }
814 }
815 }
816
817 async fn did_save(&self, params: DidSaveTextDocumentParams) {
818 if let Some(entry) = self.documents.read().await.get(¶ms.text_document.uri) {
821 self.update_diagnostics(params.text_document.uri, entry.content.clone(), true)
822 .await;
823 }
824 }
825
826 async fn did_close(&self, params: DidCloseTextDocumentParams) {
827 self.documents.write().await.remove(¶ms.text_document.uri);
829
830 self.client
833 .publish_diagnostics(params.text_document.uri, Vec::new(), None)
834 .await;
835 }
836
837 async fn did_change_watched_files(&self, params: DidChangeWatchedFilesParams) {
838 const CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", "pyproject.toml", ".markdownlint.json"];
840
841 let mut config_changed = false;
842
843 for change in ¶ms.changes {
844 if let Ok(path) = change.uri.to_file_path() {
845 let file_name = path.file_name().and_then(|f| f.to_str());
846 let extension = path.extension().and_then(|e| e.to_str());
847
848 if let Some(name) = file_name
850 && CONFIG_FILES.contains(&name)
851 && !config_changed
852 {
853 log::info!("Config file changed: {}, invalidating config cache", path.display());
854
855 let mut cache = self.config_cache.write().await;
859 cache.clear();
860
861 drop(cache);
863 self.reload_configuration().await;
864 config_changed = true;
865 }
866
867 if let Some(ext) = extension
869 && is_markdown_extension(ext)
870 {
871 match change.typ {
872 FileChangeType::CREATED | FileChangeType::CHANGED => {
873 if let Ok(content) = tokio::fs::read_to_string(&path).await {
875 let _ = self
876 .update_tx
877 .send(IndexUpdate::FileChanged {
878 path: path.clone(),
879 content,
880 })
881 .await;
882 }
883 }
884 FileChangeType::DELETED => {
885 let _ = self
886 .update_tx
887 .send(IndexUpdate::FileDeleted { path: path.clone() })
888 .await;
889 }
890 _ => {}
891 }
892 }
893 }
894 }
895
896 if config_changed {
898 let docs_to_update: Vec<(Url, String)> = {
899 let docs = self.documents.read().await;
900 docs.iter()
901 .filter(|(_, entry)| !entry.from_disk)
902 .map(|(uri, entry)| (uri.clone(), entry.content.clone()))
903 .collect()
904 };
905
906 for (uri, text) in docs_to_update {
907 self.update_diagnostics(uri, text, true).await;
908 }
909 }
910 }
911
912 async fn code_action(&self, params: CodeActionParams) -> JsonRpcResult<Option<CodeActionResponse>> {
913 let uri = params.text_document.uri;
914 let range = params.range;
915 let requested_kinds = params.context.only;
916
917 if let Some(text) = self.get_document_content(&uri).await {
918 match self.get_code_actions(&uri, &text, range).await {
919 Ok(actions) => {
920 let filtered_actions = if let Some(ref kinds) = requested_kinds
924 && !kinds.is_empty()
925 {
926 actions
927 .into_iter()
928 .filter(|action| {
929 action.kind.as_ref().is_some_and(|action_kind| {
930 let action_kind_str = action_kind.as_str();
931 kinds.iter().any(|requested| {
932 let requested_str = requested.as_str();
933 action_kind_str.starts_with(requested_str)
936 })
937 })
938 })
939 .collect()
940 } else {
941 actions
942 };
943
944 let response: Vec<CodeActionOrCommand> = filtered_actions
945 .into_iter()
946 .map(CodeActionOrCommand::CodeAction)
947 .collect();
948 Ok(Some(response))
949 }
950 Err(e) => {
951 log::error!("Failed to get code actions: {e}");
952 Ok(None)
953 }
954 }
955 } else {
956 Ok(None)
957 }
958 }
959
960 async fn range_formatting(&self, params: DocumentRangeFormattingParams) -> JsonRpcResult<Option<Vec<TextEdit>>> {
961 log::debug!(
966 "Range formatting requested for {:?}, formatting entire document due to rule interdependencies",
967 params.range
968 );
969
970 let formatting_params = DocumentFormattingParams {
971 text_document: params.text_document,
972 options: params.options,
973 work_done_progress_params: params.work_done_progress_params,
974 };
975
976 self.formatting(formatting_params).await
977 }
978
979 async fn formatting(&self, params: DocumentFormattingParams) -> JsonRpcResult<Option<Vec<TextEdit>>> {
980 let uri = params.text_document.uri;
981 let options = params.options;
982
983 log::debug!("Formatting request for: {uri}");
984 log::debug!(
985 "FormattingOptions: insert_final_newline={:?}, trim_final_newlines={:?}, trim_trailing_whitespace={:?}",
986 options.insert_final_newline,
987 options.trim_final_newlines,
988 options.trim_trailing_whitespace
989 );
990
991 if let Some(text) = self.get_document_content(&uri).await {
992 let config_guard = self.config.read().await;
994 let lsp_config = config_guard.clone();
995 drop(config_guard);
996
997 let file_path = uri.to_file_path().ok();
999 let file_config = if let Some(ref path) = file_path {
1000 self.resolve_config_for_file(path).await
1001 } else {
1002 self.rumdl_config.read().await.clone()
1004 };
1005
1006 let rumdl_config = self.merge_lsp_settings(file_config, &lsp_config);
1008
1009 let all_rules = rules::all_rules(&rumdl_config);
1010 let flavor = if let Some(ref path) = file_path {
1011 rumdl_config.get_flavor_for_file(path)
1012 } else {
1013 rumdl_config.markdown_flavor()
1014 };
1015
1016 let mut filtered_rules = rules::filter_rules(&all_rules, &rumdl_config.global);
1018
1019 filtered_rules = self.apply_lsp_config_overrides(filtered_rules, &lsp_config);
1021
1022 let mut result = text.clone();
1024 match crate::lint(
1025 &text,
1026 &filtered_rules,
1027 false,
1028 flavor,
1029 file_path.clone(),
1030 Some(&rumdl_config),
1031 ) {
1032 Ok(warnings) => {
1033 log::debug!(
1034 "Found {} warnings, {} with fixes",
1035 warnings.len(),
1036 warnings.iter().filter(|w| w.fix.is_some()).count()
1037 );
1038
1039 let has_fixes = warnings.iter().any(|w| w.fix.is_some());
1040 if has_fixes {
1041 let fixable_warnings: Vec<_> = warnings
1043 .iter()
1044 .filter(|w| {
1045 if let Some(rule_name) = &w.rule_name {
1046 filtered_rules
1047 .iter()
1048 .find(|r| r.name() == rule_name)
1049 .map(|r| r.fix_capability() != FixCapability::Unfixable)
1050 .unwrap_or(false)
1051 } else {
1052 false
1053 }
1054 })
1055 .cloned()
1056 .collect();
1057
1058 match crate::utils::fix_utils::apply_warning_fixes(&text, &fixable_warnings) {
1059 Ok(fixed_content) => {
1060 result = fixed_content;
1061 }
1062 Err(e) => {
1063 log::error!("Failed to apply fixes: {e}");
1064 }
1065 }
1066 }
1067 }
1068 Err(e) => {
1069 log::error!("Failed to lint document: {e}");
1070 }
1071 }
1072
1073 result = Self::apply_formatting_options(result, &options);
1076
1077 if result != text {
1079 log::debug!("Returning formatting edits");
1080 let end_position = self.get_end_position(&text);
1081 let edit = TextEdit {
1082 range: Range {
1083 start: Position { line: 0, character: 0 },
1084 end: end_position,
1085 },
1086 new_text: result,
1087 };
1088 return Ok(Some(vec![edit]));
1089 }
1090
1091 Ok(Some(Vec::new()))
1092 } else {
1093 log::warn!("Document not found: {uri}");
1094 Ok(None)
1095 }
1096 }
1097
1098 async fn goto_definition(&self, params: GotoDefinitionParams) -> JsonRpcResult<Option<GotoDefinitionResponse>> {
1099 let uri = params.text_document_position_params.text_document.uri;
1100 let position = params.text_document_position_params.position;
1101
1102 log::debug!("Go-to-definition at {uri} {}:{}", position.line, position.character);
1103
1104 Ok(self.handle_goto_definition(&uri, position).await)
1105 }
1106
1107 async fn references(&self, params: ReferenceParams) -> JsonRpcResult<Option<Vec<Location>>> {
1108 let uri = params.text_document_position.text_document.uri;
1109 let position = params.text_document_position.position;
1110
1111 log::debug!("Find references at {uri} {}:{}", position.line, position.character);
1112
1113 Ok(self.handle_references(&uri, position).await)
1114 }
1115
1116 async fn hover(&self, params: HoverParams) -> JsonRpcResult<Option<Hover>> {
1117 let uri = params.text_document_position_params.text_document.uri;
1118 let position = params.text_document_position_params.position;
1119
1120 log::debug!("Hover at {uri} {}:{}", position.line, position.character);
1121
1122 Ok(self.handle_hover(&uri, position).await)
1123 }
1124
1125 async fn prepare_rename(&self, params: TextDocumentPositionParams) -> JsonRpcResult<Option<PrepareRenameResponse>> {
1126 let uri = params.text_document.uri;
1127 let position = params.position;
1128
1129 log::debug!("Prepare rename at {uri} {}:{}", position.line, position.character);
1130
1131 Ok(self.handle_prepare_rename(&uri, position).await)
1132 }
1133
1134 async fn rename(&self, params: RenameParams) -> JsonRpcResult<Option<WorkspaceEdit>> {
1135 let uri = params.text_document_position.text_document.uri;
1136 let position = params.text_document_position.position;
1137 let new_name = params.new_name;
1138
1139 log::debug!("Rename at {uri} {}:{} → {new_name}", position.line, position.character);
1140
1141 Ok(self.handle_rename(&uri, position, &new_name).await)
1142 }
1143
1144 async fn diagnostic(&self, params: DocumentDiagnosticParams) -> JsonRpcResult<DocumentDiagnosticReportResult> {
1145 let uri = params.text_document.uri;
1146
1147 if let Some(text) = self.get_open_document_content(&uri).await {
1148 match self.lint_document(&uri, &text, true).await {
1149 Ok(diagnostics) => Ok(DocumentDiagnosticReportResult::Report(DocumentDiagnosticReport::Full(
1150 RelatedFullDocumentDiagnosticReport {
1151 related_documents: None,
1152 full_document_diagnostic_report: FullDocumentDiagnosticReport {
1153 result_id: None,
1154 items: diagnostics,
1155 },
1156 },
1157 ))),
1158 Err(e) => {
1159 log::error!("Failed to get diagnostics: {e}");
1160 Ok(DocumentDiagnosticReportResult::Report(DocumentDiagnosticReport::Full(
1161 RelatedFullDocumentDiagnosticReport {
1162 related_documents: None,
1163 full_document_diagnostic_report: FullDocumentDiagnosticReport {
1164 result_id: None,
1165 items: Vec::new(),
1166 },
1167 },
1168 )))
1169 }
1170 }
1171 } else {
1172 Ok(DocumentDiagnosticReportResult::Report(DocumentDiagnosticReport::Full(
1173 RelatedFullDocumentDiagnosticReport {
1174 related_documents: None,
1175 full_document_diagnostic_report: FullDocumentDiagnosticReport {
1176 result_id: None,
1177 items: Vec::new(),
1178 },
1179 },
1180 )))
1181 }
1182 }
1183}
1184
1185#[cfg(test)]
1186#[path = "tests.rs"]
1187mod tests;