Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
(feat) Add concept of workspace dictionary to harper-ls (#1669)
Daniel Silverstone4ba92b4e8c7d
diff --git a/harper-ls/src/backend.rs b/harper-ls/src/backend.rsindex da6355fad..1ee25a093 100644--- a/harper-ls/src/backend.rs+++ b/harper-ls/src/backend.rs@@ -47,6 +47,7 @@ pub fn ls_version() -> &'static str {pub struct Backend {client: Client,+ root: RwLock<PathBuf>,config: RwLock<Config>,stats: RwLock<Stats>,doc_state: Mutex<HashMap<Uri, DocumentState>>,@@ -56,6 +57,7 @@ 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()),@@ -155,6 +157,21 @@ impl Backend {.map_err(|err| anyhow!("Unable to save the dictionary to file: {err}"))}+ async fn load_workspace_dictionary(&self) -> MutableDictionary {+ let config = self.config.read().await;+ load_dict(&config.workspace_dict_path)+ .await+ .map_err(|err| info!("{err}"))+ .unwrap_or(MutableDictionary::new())+ }++ async fn save_workspace_dictionary(&self, dict: impl Dictionary) -> Result<()> {+ let config = self.config.read().await;+ save_dict(&config.workspace_dict_path, dict)+ .await+ .map_err(|err| anyhow!("Unable to save the dictionary to file: {err}"))+ }+async fn save_stats(&self) -> Result<()> {let (config, stats) = join(self.config.read(), self.stats.read()).await;@@ -180,6 +197,8 @@ impl Backend {dict.add_dictionary(FstDictionary::curated());let user_dict = self.load_user_dictionary().await;dict.add_dictionary(Arc::new(user_dict));+ let ws_dict = self.load_workspace_dictionary().await;+ dict.add_dictionary(Arc::new(ws_dict));Ok(dict)}@@ -417,7 +436,9 @@ impl Backend {/// Update the configuration of the server and publish document updates that/// match it.async fn update_config_from_obj(&self, json_obj: Value) {- if let Ok(new_config) = Config::from_lsp_config(json_obj).map_err(|err| error!("{err}")) {+ if let Ok(new_config) = Config::from_lsp_config(&self.root.read().await, json_obj)+ .map_err(|err| error!("{err}"))+ {let mut config = self.config.write().await;*config = new_config;}@@ -440,7 +461,29 @@ impl Backend {}impl LanguageServer for Backend {- async fn initialize(&self, _: InitializeParams) -> JsonResult<InitializeResult> {+ async fn initialize(&self, params: InitializeParams) -> JsonResult<InitializeResult> {+ if let Some(root) = params+ .workspace_folders+ .as_ref()+ // We take the first workspace folder+ .and_then(|v| v.first())+ .map(|f| &f.uri)+ // Or failing that, the root_uri (which is deprecated in favour of workspace_folders)+ .or(+ #[allow(deprecated)]+ params.root_uri.as_ref(),+ )+ .and_then(|u| u.to_file_path().map(PathBuf::from))+ // Or failing that, the root_path (which is deprecated in favour of root_uri)+ .or(+ #[allow(deprecated)]+ params.root_path.as_deref().map(PathBuf::from),+ )+ {+ // Save the workspace root away for use during the configuration step+ *self.root.write().await = root;+ }+Ok(InitializeResult {server_info: Some(ServerInfo {name: "harper-ls".to_owned(),@@ -452,6 +495,7 @@ impl LanguageServer for Backend {commands: vec!["HarperRecordLint".to_owned(),"HarperAddToUserDict".to_owned(),+ "HarperAddToWSDict".to_owned(),"HarperAddToFileDict".to_owned(),"HarperOpen".to_owned(),"HarperIgnoreLint".to_owned(),@@ -620,6 +664,27 @@ impl LanguageServer for Backend {.err();self.publish_diagnostics(&file_uri).await;}+ "HarperAddToWSDict" => {+ let word = &first.chars().collect::<Vec<_>>();++ let Some(second) = string_args.next() else {+ return Ok(None);+ };++ let file_uri = second.parse().unwrap();++ let mut dict = self.load_workspace_dictionary().await;+ dict.append_word(word, WordMetadata::default());+ self.save_workspace_dictionary(dict)+ .await+ .map_err(|err| error!("{err}"))+ .err();+ self.update_document_from_file(&file_uri, None)+ .await+ .map_err(|err| error!("{err}"))+ .err();+ self.publish_diagnostics(&file_uri).await;+ }"HarperAddToFileDict" => {let word = &first.chars().collect::<Vec<_>>();diff --git a/harper-ls/src/config.rs b/harper-ls/src/config.rsindex 1c0b717d0..dcb80c131 100644--- a/harper-ls/src/config.rs+++ b/harper-ls/src/config.rs@@ -1,4 +1,4 @@-use std::path::PathBuf;+use std::path::{Path, PathBuf};use anyhow::{Result, bail};use dirs::{config_dir, data_local_dir};@@ -65,6 +65,7 @@ impl CodeActionConfig {pub struct Config {pub user_dict_path: PathBuf,pub file_dict_path: PathBuf,+ pub workspace_dict_path: PathBuf,pub ignored_lints_path: PathBuf,pub stats_path: PathBuf,pub lint_config: LintGroupConfig,@@ -79,7 +80,7 @@ pub struct Config {}impl Config {- pub fn from_lsp_config(value: Value) -> Result<Self> {+ pub fn from_lsp_config(workspace_root: &Path, value: Value) -> Result<Self> {let mut base = Config::default();let Value::Object(value) = value else {@@ -97,7 +98,7 @@ impl Config {let path = v.as_str().unwrap();if !path.is_empty() {- base.user_dict_path = path.try_resolve()?.to_path_buf();+ base.user_dict_path = path.try_resolve_in(workspace_root)?.to_path_buf();}}@@ -108,8 +109,24 @@ impl Config {let path = v.as_str().unwrap();if !path.is_empty() {- base.file_dict_path = path.try_resolve()?.to_path_buf();+ base.file_dict_path = path.try_resolve_in(workspace_root)?.to_path_buf();+ }+ }++ if let Some(v) = value.get("workspaceDictPath") {+ if !v.is_string() {+ bail!("workspaceDict path must be a string.");+ }+ let path = v.as_str().unwrap();+ if !path.is_empty() {+ base.workspace_dict_path = path.try_resolve_in(workspace_root)?.to_path_buf();}+ } else {+ // Resolve the default path in the project root+ base.workspace_dict_path = base+ .workspace_dict_path+ .try_resolve_in(workspace_root)?+ .to_path_buf();}if let Some(v) = value.get("ignoredLintsPath") {@@ -119,13 +136,13 @@ impl Config {let path = v.as_str().unwrap();if !path.is_empty() {- base.ignored_lints_path = path.try_resolve()?.to_path_buf();+ base.ignored_lints_path = path.try_resolve_in(workspace_root)?.to_path_buf();}}if let Some(v) = value.get("statsPath") {if let Value::String(path) = v {- base.file_dict_path = path.try_resolve()?.to_path_buf();+ base.file_dict_path = path.try_resolve_in(workspace_root)?.to_path_buf();} else {bail!("fileDict path must be a string.");}@@ -176,6 +193,7 @@ impl Default for Config {file_dict_path: data_local_dir().unwrap().join("harper-ls/file_dictionaries/"),+ workspace_dict_path: ".harper-dictionary.txt".into(),ignored_lints_path: data_local_dir().unwrap().join("harper-ls/ignored_lints/"),stats_path: data_local_dir().unwrap().join("harper-ls/stats.txt"),lint_config: LintGroupConfig::default(),diff --git a/harper-ls/src/diagnostics.rs b/harper-ls/src/diagnostics.rsindex 1aa0cff8a..3cafaa80f 100644--- a/harper-ls/src/diagnostics.rs+++ b/harper-ls/src/diagnostics.rs@@ -96,6 +96,12 @@ pub fn lint_to_code_actions<'a>(Some(vec![orig.clone().into(), uri.to_string().into()]),)));+ results.push(CodeActionOrCommand::Command(Command::new(+ format!("Add \"{orig}\" to the workspace dictionary."),+ "HarperAddToWSDict".to_string(),+ Some(vec![orig.clone().into(), uri.to_string().into()]),+ )));+results.push(CodeActionOrCommand::Command(Command::new(format!("Add \"{orig}\" to the file dictionary."),"HarperAddToFileDict".to_string(),diff --git a/packages/vscode-plugin/package.json b/packages/vscode-plugin/package.jsonindex 41e1f03b6..8ab906db3 100644--- a/packages/vscode-plugin/package.json+++ b/packages/vscode-plugin/package.json@@ -147,6 +147,11 @@"type": "string","description": "Optional path to a global dictionary file to use."},+ "harper.workspaceDictPath": {+ "scope": "resource",+ "type": "string",+ "description": "Optional path to a workspace-local dictionary file to use."+ },"harper.linters.ACoupleMore": {"scope": "resource","type": "boolean",diff --git a/packages/vscode-plugin/src/extension.ts b/packages/vscode-plugin/src/extension.tsindex d81ea4cc5..43a666763 100644--- a/packages/vscode-plugin/src/extension.ts+++ b/packages/vscode-plugin/src/extension.ts@@ -28,7 +28,12 @@ const clientOptions: LanguageClientOptions = {},executeCommand(command, args, next) {if (- ['HarperAddToUserDict', 'HarperAddToFileDict', 'HarperIgnoreLint'].includes(command) &&+ [+ 'HarperAddToUserDict',+ 'HarperAddToWSDict',+ 'HarperAddToFileDict',+ 'HarperIgnoreLint',+ ].includes(command) &&args.find((a) => typeof a === 'string' && a.startsWith('untitled:'))) {windowdiff --git a/packages/web/src/routes/docs/integrations/emacs/+page.md b/packages/web/src/routes/docs/integrations/emacs/+page.mdindex b93007494..621d6bea3 100644--- a/packages/web/src/routes/docs/integrations/emacs/+page.md+++ b/packages/web/src/routes/docs/integrations/emacs/+page.md@@ -43,6 +43,7 @@ Additionally, you can also configure things like which linters to use or how you```elisp title=init.el(setq-default eglot-workspace-configuration'(:harper-ls (:userDictPath ""+ :workspaceDictPath "":fileDictPath "":linters (:SpellCheck t:SpelledNumbers :json-falsediff --git a/packages/web/src/routes/docs/integrations/helix/+page.md b/packages/web/src/routes/docs/integrations/helix/+page.mdindex 7de7bfdd0..18e32ab0d 100644--- a/packages/web/src/routes/docs/integrations/helix/+page.md+++ b/packages/web/src/routes/docs/integrations/helix/+page.md@@ -41,6 +41,7 @@ Additionally, you can also configure things like which linters to use or how you```toml title=languages.toml[language-server.harper-ls.config.harper-ls]userDictPath = ""+workspaceDictPath = ""fileDictPath = ""diagnosticSeverity = "hint"isolateEnglish = falsediff --git a/packages/web/src/routes/docs/integrations/language-server/+page.md b/packages/web/src/routes/docs/integrations/language-server/+page.mdindex d429db031..44cd1dadc 100644--- a/packages/web/src/routes/docs/integrations/language-server/+page.md+++ b/packages/web/src/routes/docs/integrations/language-server/+page.md@@ -76,7 +76,7 @@ If none of the previous installation methods are available to you, we also provi## Dictionaries-`harper-ls` has three kinds of dictionaries: user, file-local, and static dictionaries. All three dictionaries are combined and used together when spell checking files.+`harper-ls` has four kinds of dictionaries: user, workspace, file-local, and static dictionaries. All four dictionaries are combined and used together when spell checking files.### User Dictionary@@ -90,6 +90,12 @@ Each user of `harper-ls` has their own dictionary, which by default, is locatedThis dictionary is a simple line-separated word list in plaintext. You can add and remove words at will. Code actions on misspelled words allow you to add elements to this list. Additionally, [its location is configurable](#Dictionaries_).+### Workspace Dictionary++Each workspace in which you use `harper-ls` has its own dictionary, which by default is located at `.harper-dictionary.txt` in the root of the workspace.++This dictionary is a simple line-separated word list in plaintext. You can add and remove words at will. Code actions on misspelled words allow you to add elements to this list. Additionally, [its location is configurable](#Dictionaries_).+### File-Local DictionarySometimes, you'll encounter a word (or name) that is only valid within the context of a specific file. In this case, you can add this file-specific word to a file-local dictionary using code actions. Any words added to this dictionary will only be included in the combined dictionary when spell checking a file at that specific path.@@ -114,12 +120,13 @@ We _do_ take pull requests or issues for adding words to the static dictionary.`harper-ls` has code actions that help in quickly dealing with spelling or grammar errors you encounter. The examples below assume that you have misspelled "contained" as "containes" and have selected it to apply a code action to it.-| Code Action or Command | Description | Example |-| ---------------------- | ---------------------------------------------------------- | ------------------------------------------- |-| Quick Fixes | Suggests fixes for the selected error | `Replace with: "contained"` |-| `HarperIgnoreLint` | Ignores the selected error for the duration of the session | `Ignore Harper error.` |-| `HarperAddToUserDict` | Adds the selected word to the user dictionary | `Add "containes" to the global dictionary.` |-| `HarperAddToFileDict` | Adds the selected word to a file-local dictionary | `Add "containes" to the file dictionary.` |+| Code Action or Command | Description | Example |+| ---------------------- | ---------------------------------------------------------- | ---------------------------------------------- |+| Quick Fixes | Suggests fixes for the selected error | `Replace with: "contained"` |+| `HarperIgnoreLint` | Ignores the selected error for the duration of the session | `Ignore Harper error.` |+| `HarperAddToUserDict` | Adds the selected word to the user dictionary | `Add "containes" to the global dictionary.` |+| `HarperAddToWSDict` | Adds the selected word to the workspace dictionary | `Add "containes" to the workspace dictionary.` |+| `HarperAddToFileDict` | Adds the selected word to a file-local dictionary | `Add "containes" to the file dictionary.` |## Ignore Comments@@ -163,13 +170,16 @@ In the above example, "spellcheckd", "this this", and other spelling or grammar}```-### Directories+### Directories++| Config | Type | Default Value | Description |+| ------------------- | -------- | ------------- | --------------------------------------------------------------- |+| `userDictPath` | `string` | `""` | Set the file path where the user dictionary is located |+| `workspaceDictPath` | `string` | `""` | Set the file path where the workspace dictionary is located |+| `fileDictPath` | `string` | `""` | Set the directory where the file-local dictionaries are located |+| `ignoredLintsPath` | `string` | `""` | Set the directory where the ignored lint lists are located |-| Config | Type | Default Value | Description |-| -------------- | -------- | ------------- | --------------------------------------------------------------- |-| `userDictPath` | `string` | `""` | Set the file path where the user dictionary is located |-| `fileDictPath` | `string` | `""` | Set the directory where the file-local dictionaries are located |-| `ignoredLintsPath` | `string` | `""` | Set the directory where the ignored lint lists are located |+These paths are always resolved relative to the root of the workspace in which `harper-ls` was invoked.### Lintersdiff --git a/packages/web/src/routes/docs/integrations/neovim/+page.md b/packages/web/src/routes/docs/integrations/neovim/+page.mdindex 14a0ea23b..0b18c49d3 100644--- a/packages/web/src/routes/docs/integrations/neovim/+page.md+++ b/packages/web/src/routes/docs/integrations/neovim/+page.md@@ -25,6 +25,7 @@ require('lspconfig').harper_ls.setup {settings = {["harper-ls"] = {userDictPath = "",+ workspaceDictPath = "",fileDictPath = "",linters = {SpellCheck = true,diff --git a/packages/web/src/routes/docs/integrations/sublime-text/+page.md b/packages/web/src/routes/docs/integrations/sublime-text/+page.mdindex 27e377109..e9f144e50 100644--- a/packages/web/src/routes/docs/integrations/sublime-text/+page.md+++ b/packages/web/src/routes/docs/integrations/sublime-text/+page.md@@ -27,6 +27,7 @@ Open `Preferences > Package Settings > LSP > Settings` and add the `harper-ls` c"settings": {"harper-ls": {"userDictPath": "",+ "workspaceDictPath": "","fileDictPath": "","linters": {"SpellCheck": true,@@ -54,7 +55,7 @@ Open `Preferences > Package Settings > LSP > Settings` and add the `harper-ls` c}}}-}+}```For more information on what each of these configs do, you can head over to the [configuration section](./language-server#Configuration) of our `harper-ls` documentation.