Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
harper-ls: debounce diagnostics after edits (#3282)
Dronakurlddb00e0f7775
diff --git a/harper-ls/Cargo.toml b/harper-ls/Cargo.tomlindex c5153682e..e1431b261 100644--- a/harper-ls/Cargo.toml+++ b/harper-ls/Cargo.toml@@ -21,7 +21,7 @@ harper-html = { path = "../harper-html", version = "2.0.0" }harper-python = { path = "../harper-python", version = "2.0.0" }harper-asciidoc = { path = "../harper-asciidoc", version = "2.0.0" }tower-lsp-server = "0.22.1"-tokio = { version = "1.52.1", default-features = false, features = ["fs", "io-std", "io-util", "macros", "net", "rt-multi-thread", "sync"] }+tokio = { version = "1.52.1", default-features = false, features = ["fs", "io-std", "io-util", "macros", "net", "rt-multi-thread", "sync", "test-util", "time"] }clap = { version = "4.6.1", default-features = false, features = ["derive", "std"] }dirs = "6.0.0"anyhow = "1.0.102"diff --git a/harper-ls/src/backend.rs b/harper-ls/src/backend.rsindex e797544e8..3327b0b7e 100644--- a/harper-ls/src/backend.rs+++ b/harper-ls/src/backend.rs@@ -3,6 +3,7 @@ use std::fs::OpenOptions;use std::io::{BufWriter, Write};use std::path::PathBuf;use std::sync::Arc;+use std::time::Duration;use crate::config::Config;use crate::document_state::DocumentState;@@ -50,22 +51,25 @@ pub fn ls_version() -> &'static str {env!("CARGO_PKG_VERSION")}+#[derive(Clone)]pub struct Backend {client: Client,- root: RwLock<PathBuf>,- config: RwLock<Config>,- stats: RwLock<Stats>,- doc_state: Mutex<HashMap<Uri, DocumentState>>,+ root: Arc<RwLock<PathBuf>>,+ config: Arc<RwLock<Config>>,+ stats: Arc<RwLock<Stats>>,+ doc_state: Arc<Mutex<HashMap<Uri, DocumentState>>>,+ pending_diagnostic_tasks: Arc<Mutex<HashMap<Uri, tokio::task::JoinHandle<()>>>>,}impl Backend {pub fn new(client: Client, config: Config) -> Self {Self {client,- root: RwLock::new(".".into()),- stats: RwLock::new(Stats::new()),- config: RwLock::new(config),- doc_state: Mutex::new(HashMap::new()),+ root: Arc::new(RwLock::new(".".into())),+ stats: Arc::new(RwLock::new(Stats::new())),+ config: Arc::new(RwLock::new(config)),+ doc_state: Arc::new(Mutex::new(HashMap::new())),+ pending_diagnostic_tasks: Arc::new(Mutex::new(HashMap::new())),}}@@ -468,6 +472,13 @@ impl Backend {.await;}+ /// The async pending diagnostics are discarded and diagnostics are created+ /// and published immediately.+ async fn publish_diagnostics_immediately(&self, uri: &Uri) {+ self.abort_pending_diagnostics(uri).await;+ self.publish_diagnostics(uri).await;+ }+/// Update the configuration of the server and publish document updates that/// match it.async fn update_config_from_obj(&self, json_obj: Value) {@@ -493,6 +504,32 @@ impl Backend {self.update_config_from_obj(first).await;}}++ /// Aborts a pending diagnostic run, e.g. because the document was changed.+ async fn abort_pending_diagnostics(&self, uri: &Uri) {+ let mut tasks = self.pending_diagnostic_tasks.lock().await;+ if let Some(task) = tasks.remove(uri) {+ task.abort();+ }+ }++ /// Schedule diagnostics in `delay_ms` milliseconds+ /// Configure this with the `diagnosticDelayMs` option.+ /// ```toml+ /// [language-server.harper-ls.config.harper-ls]+ /// diagnosticDelayMs = 1000+ /// ```+ pub async fn schedule_diagnostics(&self, uri: &Uri, delay_ms: u64) {+ let task_uri = uri.clone();+ let backend = self.clone();+ let handle = tokio::spawn(async move {+ tokio::time::sleep(Duration::from_millis(delay_ms)).await;+ backend.publish_diagnostics(&task_uri).await;+ });++ let mut tasks = self.pending_diagnostic_tasks.lock().await;+ tasks.insert(uri.clone(), handle);+ }}impl LanguageServer for Backend {@@ -590,7 +627,8 @@ impl LanguageServer for Backend {.map_err(|err| error!("{err}")).err();- self.publish_diagnostics(¶ms.text_document.uri).await;+ self.publish_diagnostics_immediately(¶ms.text_document.uri)+ .await;}async fn did_change(&self, params: DidChangeTextDocumentParams) {@@ -605,14 +643,24 @@ impl LanguageServer for Backend {error!("{err}")}- self.publish_diagnostics(¶ms.text_document.uri).await;+ let delay_ms = self.config.read().await.diagnostic_delay_ms;+ if delay_ms > 0 {+ // Diagnostics delay is configured, abort pending diagnostic task+ // and schedule a new diagnostic run in delay_ms milliseconds.+ self.abort_pending_diagnostics(¶ms.text_document.uri)+ .await;+ self.schedule_diagnostics(¶ms.text_document.uri, delay_ms)+ .await;+ } else {+ self.publish_diagnostics(¶ms.text_document.uri).await;+ }}async fn did_close(&self, _params: DidCloseTextDocumentParams) {let uri = _params.text_document.uri;let mut doc_lock = self.doc_state.lock().await;doc_lock.remove(&uri);-+ self.abort_pending_diagnostics(&uri).await;self.client.send_notification::<PublishDiagnostics>(PublishDiagnosticsParams {uri: uri.clone(),@@ -644,6 +692,7 @@ impl LanguageServer for Backend {}for uri in &uris_to_clear {+ self.abort_pending_diagnostics(uri).await;self.client.send_notification::<PublishDiagnostics>(PublishDiagnosticsParams {uri: uri.clone(),@@ -697,7 +746,7 @@ impl LanguageServer for Backend {.await.map_err(|err| error!("{err}")).err();- self.publish_diagnostics(&file_uri).await;+ self.publish_diagnostics_immediately(&file_uri).await;}"HarperAddToWSDict" => {let word = &first.chars().collect::<Vec<_>>();@@ -718,7 +767,7 @@ impl LanguageServer for Backend {.await.map_err(|err| error!("{err}")).err();- self.publish_diagnostics(&file_uri).await;+ self.publish_diagnostics_immediately(&file_uri).await;}"HarperAddToFileDict" => {let word = &first.chars().collect::<Vec<_>>();@@ -749,7 +798,7 @@ impl LanguageServer for Backend {.await.map_err(|err| error!("{err}")).err();- self.publish_diagnostics(&file_uri).await;+ self.publish_diagnostics_immediately(&file_uri).await;}"HarperOpen" => match open::that(&first) {Ok(()) => {@@ -799,7 +848,7 @@ impl LanguageServer for Backend {drop(doc_lock);- self.publish_diagnostics(&uri).await;+ self.publish_diagnostics_immediately(&uri).await;}_ => (),}@@ -828,7 +877,7 @@ impl LanguageServer for Backend {.await.map_err(|err| error!("{err}")).err();- self.publish_diagnostics(&uri).await;+ self.publish_diagnostics_immediately(&uri).await;}}@@ -848,6 +897,7 @@ impl LanguageServer for Backend {// Clears the diagnostics for open buffers.for uri in doc_states.keys() {+ self.abort_pending_diagnostics(uri).await;let result = PublishDiagnosticsParams {uri: uri.clone(),diagnostics: vec![],diff --git a/harper-ls/src/config.rs b/harper-ls/src/config.rsindex a55f849ad..2f4389908 100644--- a/harper-ls/src/config.rs+++ b/harper-ls/src/config.rs@@ -79,6 +79,9 @@ pub struct Config {/// Above this limit, the file will not be linted.pub max_file_length: usize,pub exclude_patterns: GlobSet,+ /// Delay in milliseconds after typing stops before diagnostics are published.+ /// Set to 0 to publish diagnostics immediately.+ pub diagnostic_delay_ms: u64,}impl Config {@@ -147,9 +150,9 @@ impl Config {if let Some(v) = value.get("statsPath") {if let Value::String(path) = v {- base.file_dict_path = path.try_resolve_in(workspace_root)?.to_path_buf();+ base.stats_path = path.try_resolve_in(workspace_root)?.to_path_buf();} else {- bail!("fileDict path must be a string.");+ bail!("statsPath must be a string.");}}@@ -204,6 +207,10 @@ impl Config {}}+ if let Some(v) = value.get("diagnosticDelayMs") {+ base.diagnostic_delay_ms = serde_json::from_value(v.clone())?;+ }+Ok(base)}}@@ -226,6 +233,57 @@ impl Default for Config {dialect: Dialect::American,max_file_length: 120_000,exclude_patterns: GlobSet::empty(),+ diagnostic_delay_ms: 0,}}}++#[cfg(test)]+mod tests {+ use serde_json::json;++ use super::Config;++ #[test]+ fn parses_diagnostic_delay() {+ let config = Config::from_lsp_config(+ std::path::Path::new("."),+ json!({+ "harper-ls": {+ "diagnosticDelayMs": 750+ }+ }),+ )+ .unwrap();++ assert_eq!(config.diagnostic_delay_ms, 750);+ }++ #[test]+ fn defaults_diagnostic_delay_to_zero() {+ let config = Config::default();++ assert_eq!(config.diagnostic_delay_ms, 0);+ }++ #[test]+ fn parses_stats_path_without_touching_file_dict_path() {+ let config = Config::from_lsp_config(+ std::path::Path::new("."),+ json!({+ "harper-ls": {+ "statsPath": ".harper-stats.txt"+ }+ }),+ )+ .unwrap();++ assert!(config.stats_path.ends_with(".harper-stats.txt"));+ assert!(+ config+ .file_dict_path+ .ends_with("harper-ls/file_dictionaries/"),+ "file dictionary path should keep its default value"+ );+ }+}