From bd0f28cd3bb0cee7e8cd9686fa68fd34f22b399b Mon Sep 17 00:00:00 2001 From: Muu Date: Tue, 24 Nov 2026 06:01:01 +0800 Subject: [PATCH] feat(spelling): save typos to custom dictionaries with a default dictionary setting (#5466) Co-authored-by: muutot <92625353+muutot@users.noreply.github.com> --- crates/ide-core/src/inspection_settings.rs | 5 + crates/ide-host/src/ops/spell.rs | 115 +++++++++++++++++- crates/ide-host/tests/spell_dictionary.rs | 107 ++++++++++++++++ crates/ide-spell/src/lib.rs | 11 +- docs/en/guide/inspections.mdx | 5 +- docs/zh/guide/inspections.mdx | 5 +- e2e/spellingSettingsLayout.spec.ts | 11 ++ src-tauri/tests/commands.snap | 1 + src/bindings.ts | 14 +++ src/editor/lsp/spelling.test.ts | 74 ++++++++++- src/editor/lsp/spelling.ts | 68 ++++++++++- src/features/settings/model/schema.ts | 5 +- .../settings/pages/editor/spelling.tsx | 24 +++- src/platform/locales/text/en.json | 7 ++ src/platform/locales/text/zh-TW.json | 4 + src/platform/locales/text/zh.json | 7 ++ 16 files changed, 441 insertions(+), 22 deletions(-) create mode 100644 crates/ide-host/tests/spell_dictionary.rs diff --git a/crates/ide-core/src/inspection_settings.rs b/crates/ide-core/src/inspection_settings.rs index 41dfb8f25..7081cd535 100644 --- a/crates/ide-core/src/inspection_settings.rs +++ b/crates/ide-core/src/inspection_settings.rs @@ -71,6 +71,11 @@ pub struct SpellingSettings { pub project_words: Vec, /// Custom dictionaries: plain word lists or Hunspell `.dic` files. pub custom_dictionaries: Vec, + /// Where "Save '…' to dictionary" writes: `project`, `application`, or a + /// `spelling.customDictionaries` entry verbatim; empty (the default) is + /// project when one is open, application otherwise. + #[specta(optional)] + pub default_dictionary: Option, } /// Changes to one inspection; absent fields keep the inspection's defaults. diff --git a/crates/ide-host/src/ops/spell.rs b/crates/ide-host/src/ops/spell.rs index bb1605e55..0491d8082 100644 --- a/crates/ide-host/src/ops/spell.rs +++ b/crates/ide-host/src/ops/spell.rs @@ -20,13 +20,18 @@ fn dictionary_paths(settings: &SpellingSettings, root: &Path) -> Vec { .iter() .map(|p| p.trim()) .filter(|p| !p.is_empty()) - .map(|p| match p.strip_prefix("~/") { - Some(rest) => dirs::home_dir().unwrap_or_default().join(rest), - None => root.join(p), - }) + .map(|p| resolve_dictionary(p, root)) .collect() } +/// One `spelling.customDictionaries` entry resolved: `~/…` from home, relative from the project root. +fn resolve_dictionary(text: &str, root: &Path) -> PathBuf { + match text.strip_prefix("~/") { + Some(rest) => dirs::home_dir().unwrap_or_default().join(rest), + None => root.join(text), + } +} + fn speller(project: &Project) -> Speller { let s = project.settings.effective().spelling; let words = s.ide_words.iter().chain(&s.project_words); @@ -116,4 +121,104 @@ pub async fn spell_suggest(host: &Host, window: &str, word: String) -> IdeResult .await } -ide_command::domain!(spell: spell_check, spell_suggest); +/// Appends `word` to the custom dictionary `dictionary` (a +/// `spelling.customDictionaries` entry: `~/…` from home, relative from the +/// project root) and reports which file was written, creating it when missing. +/// A Hunspell `.dic` with a `.aff` beside it keeps its word count line current; +/// the speller picks the change up through its own mtime cache. +#[command(trust = always)] +pub async fn spell_save_to_dictionary( + host: &Host, + window: &str, + dictionary: String, + word: String, +) -> IdeResult { + let project = host.project(window)?; + blocking(move || { + let entry = dictionary.trim(); + if entry.is_empty() + || !project.settings.read_effective(|s| s.spelling.custom_dictionaries.iter().any(|p| p.trim() == entry)) + { + return Err(IdeError::invalid("Select a configured custom dictionary")); + } + let w = word.trim(); + // One word per line: no whitespace, no line breaks; digits and hyphens + // may appear, but at least one letter (a number list checks nothing). + if w.starts_with('#') + || w.contains('/') + || w.chars().any(|c| c.is_whitespace() || c.is_control()) + || !w.chars().any(|c| c.is_alphabetic()) + { + return Err(IdeError::invalid(format!("'{word}' is not a word a dictionary can list"))); + } + let path = resolve_dictionary(entry, &project.root); + // Serialize the read/modify/write across projects that share a dictionary. + static SAVES: parking_lot::Mutex<()> = parking_lot::Mutex::new(()); + let _save = SAVES.lock(); + let mut text = match std::fs::metadata(&path) { + Ok(m) if !m.is_file() || m.permissions().readonly() => { + return Err(IdeError::invalid(format!("{} is not a writable dictionary file", path.display()))); + } + Ok(_) => std::fs::read_to_string(&path)?, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(), + Err(e) => return Err(e.into()), + }; + let hunspell = ide_spell::affix_file(&path).is_some(); + let already_listed = if hunspell { + text.lines().any(|line| line.trim() == w) + } else { + ide_spell::parse_word_list(&text).contains(&w.to_lowercase()) + }; + if already_listed { + return Ok(String::new()); + } + let newline = if text.contains("\r\n") { "\r\n" } else { "\n" }; + if hunspell { + let body = text.strip_prefix('\u{feff}').unwrap_or(&text); + let start = text.len() - body.len() + + body + .split_inclusive('\n') + .take_while(|line| line.trim_start().starts_with('#')) + .map(str::len) + .sum::(); + let header = text[start..].lines().next().unwrap_or_default(); + if let Some(count) = header.trim().parse::().ok().and_then(|n| n.checked_add(1)) { + text.replace_range(start..start + header.len(), &count.to_string()); + } else if text.is_empty() { + text.push_str("1\n"); + } + } + if !text.is_empty() && !text.ends_with('\n') { + text.push_str(newline); + } + text.push_str(w); + text.push_str(newline); + // A dictionary file may name folders that do not exist yet (a fresh + // project layout): create them, then write. + if let Some(dir) = path.parent() + && !dir.is_dir() + { + std::fs::create_dir_all(dir)?; + } + ide_vfs::write_atomic_strict(&path, text.as_bytes())?; + Ok(path.to_string_lossy().into_owned()) + }) + .await +} + +ide_command::domain!(spell: spell_check, spell_suggest, spell_save_to_dictionary); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn resolves_home_dictionaries() { + if let Some(home) = dirs::home_dir() { + assert_eq!( + resolve_dictionary("~/words/personal.txt", Path::new("project")), + home.join("words/personal.txt") + ); + } + } +} diff --git a/crates/ide-host/tests/spell_dictionary.rs b/crates/ide-host/tests/spell_dictionary.rs new file mode 100644 index 000000000..5ec58972c --- /dev/null +++ b/crates/ide-host/tests/spell_dictionary.rs @@ -0,0 +1,107 @@ +//! Appending a word to a custom dictionary file (Typo › Save to '…'). +use ide_core::NullSink; +use ide_host::ops; +use ide_host::{Host, HostConfig}; +use ide_workspace::SettingsScope; +use std::path::Path; +use std::sync::Arc; + +fn host(base: &Path) -> Arc { + Arc::new(Host::new(HostConfig { + config_dir: base.join("config"), + data_dir: base.join("data"), + local_data_dir: base.join("data"), + languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: Arc::default(), + sink_for: Box::new(|_| Arc::new(NullSink)), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + })) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn saves_words_to_configured_project_dictionaries() { + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap().join("project"); + std::fs::create_dir_all(&root).unwrap(); + let host = host(&tmp.path().join("app")); + host.trust.decide(&root, true, false).unwrap(); + host.open_project("main", &root).unwrap(); + host.project("main") + .unwrap() + .settings + .set(SettingsScope::Global, "spelling.customDictionaries", serde_json::json!([" docs/team.dic "])) + .unwrap(); + + // A missing file is created as a plain word list. + let file = + ops::spell::spell_save_to_dictionary(&host, "main", "docs/team.dic".into(), "Pyorm".into()).await.unwrap(); + assert_eq!(file, root.join("docs/team.dic").to_string_lossy()); + assert_eq!(std::fs::read_to_string(root.join("docs/team.dic")).unwrap(), "Pyorm\n"); + + // A second word is appended; the first stays. + ops::spell::spell_save_to_dictionary(&host, "main", "docs/team.dic".into(), "mesage".into()).await.unwrap(); + assert_eq!(std::fs::read_to_string(root.join("docs/team.dic")).unwrap(), "Pyorm\nmesage\n"); + + // The same word again changes nothing and reports no file. + let file = + ops::spell::spell_save_to_dictionary(&host, "main", "docs/team.dic".into(), "MESAGE".into()).await.unwrap(); + assert_eq!(file, ""); + assert_eq!(std::fs::read_to_string(root.join("docs/team.dic")).unwrap(), "Pyorm\nmesage\n"); + + // A file without a final newline is joined with one. + std::fs::write(root.join("docs/team.dic"), "Pyorm\nmesage").unwrap(); + ops::spell::spell_save_to_dictionary(&host, "main", "docs/team.dic".into(), "wrng".into()).await.unwrap(); + assert_eq!(std::fs::read_to_string(root.join("docs/team.dic")).unwrap(), "Pyorm\nmesage\nwrng\n"); + + assert!(ops::spell::spell_save_to_dictionary(&host, "main", "arbitrary.txt".into(), "kurz".into()).await.is_err()); + assert!(!root.join("arbitrary.txt").exists()); + + // Not a word: no file is written. + assert!( + ops::spell::spell_save_to_dictionary(&host, "main", "docs/team.dic".into(), "two words".into()).await.is_err() + ); + assert!(ops::spell::spell_save_to_dictionary(&host, "main", "docs/team.dic".into(), "123".into()).await.is_err()); + let dictionary = root.join("docs/team.dic"); + std::fs::write(&dictionary, [0xff, b'\n']).unwrap(); + assert!(ops::spell::spell_save_to_dictionary(&host, "main", "docs/team.dic".into(), "kurz".into()).await.is_err()); + assert_eq!(std::fs::read(&dictionary).unwrap(), [0xff, b'\n']); + host.shutdown().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_hunspell_dictionary_keeps_its_word_count_line() { + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap().join("project"); + std::fs::create_dir_all(&root).unwrap(); + let host = host(&tmp.path().join("app")); + host.trust.decide(&root, true, false).unwrap(); + host.open_project("main", &root).unwrap(); + host.project("main") + .unwrap() + .settings + .set(SettingsScope::Global, "spelling.customDictionaries", serde_json::json!(["de_TEST.dic"])) + .unwrap(); + + std::fs::write(root.join("de_TEST.dic"), "\u{feff}# Test\r\n2\r\npyorm\r\nmesage").unwrap(); + std::fs::write(root.join("de_TEST.aff"), "SET UTF-8\n").unwrap(); + ops::spell::spell_save_to_dictionary(&host, "main", "de_TEST.dic".into(), "kurz".into()).await.unwrap(); + // The count line tracks the words, the entries keep their order. + assert_eq!( + std::fs::read_to_string(root.join("de_TEST.dic")).unwrap(), + "\u{feff}# Test\r\n3\r\npyorm\r\nmesage\r\nkurz\r\n" + ); + + let dictionary = root.join("de_TEST.dic"); + let speller = ide_spell::Speller::new(std::iter::empty::<&str>(), std::slice::from_ref(&dictionary)); + assert!(speller.is_correct("mesage")); + assert!(speller.is_correct("kurz")); + + // Without an .aff beside it, the same file is a word list: no count line. + std::fs::remove_file(root.join("de_TEST.aff")).unwrap(); + std::fs::write(&dictionary, "3\npyorm\nmesage\nkurz\n").unwrap(); + ops::spell::spell_save_to_dictionary(&host, "main", "de_TEST.dic".into(), "wrng".into()).await.unwrap(); + assert_eq!(std::fs::read_to_string(root.join("de_TEST.dic")).unwrap(), "3\npyorm\nmesage\nkurz\nwrng\n"); + host.shutdown().await; +} diff --git a/crates/ide-spell/src/lib.rs b/crates/ide-spell/src/lib.rs index 742998b87..aadce86fe 100644 --- a/crates/ide-spell/src/lib.rs +++ b/crates/ide-spell/src/lib.rs @@ -216,7 +216,7 @@ impl CustomDictionary { } /// The `.aff` next to a Hunspell `.dic` (`de_DE.dic` → `de_DE.aff`), if there is one. -fn affix_file(path: &Path) -> Option { +pub fn affix_file(path: &Path) -> Option { if !path.extension().is_some_and(|e| e.eq_ignore_ascii_case("dic")) { return None; } @@ -289,10 +289,10 @@ impl Speller { /// (`checkpointer`, `serializers`) and `-ed` / `-ing` / `-able` forms of /// programming terms (`stringified`) pass too. pub fn is_correct(&self, word: &str) -> bool { - if let Some(base) = word.strip_suffix("'s") { - return self.is_correct(base); - } let lower = word.to_lowercase(); + if let Some(base) = word.strip_suffix("'s") { + return self.user_word(&lower) || self.is_correct(base); + } self.listed(word, &lower) || self.agent_noun(&lower) || self.term_form(&lower) } @@ -792,11 +792,12 @@ mod tests { let dir = std::env::temp_dir().join(format!("ide-spell-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let dic = dir.join("team.dic"); - std::fs::write(&dic, "2\nfrobnicate/S\nQuuxify\n").unwrap(); + std::fs::write(&dic, "3\nfrobnicate/S\nQuuxify\nZorblax's\n").unwrap(); let s = Speller::new(["Openidea"], std::slice::from_ref(&dic)); assert!(s.is_correct("openidea")); assert!(s.is_correct("frobnicate")); assert!(s.is_correct("quuxify")); + assert!(s.is_correct("Zorblax's")); assert!(!s.is_correct("zorblax")); let _ = std::fs::remove_dir_all(dir); } diff --git a/docs/en/guide/inspections.mdx b/docs/en/guide/inspections.mdx index 9a71e45a6..df183f3e1 100644 --- a/docs/en/guide/inspections.mdx +++ b/docs/en/guide/inspections.mdx @@ -72,9 +72,10 @@ The **Proofreading › Typo** inspection checks words in comments, string litera On a typo, `⌥↵` / `Alt+Enter` offers: - **Typo: Change to…** (comments, strings, text) or **Typo: Rename to…** (a declared name, done through Rename so references follow); -- saving the word to the project-level or application-level dictionary. +- saving the word to the project-level or application-level dictionary, or to one of your custom dictionaries (listed by their configured paths; the word is appended to the file, created when missing — a Hunspell `.dic` keeps its word count line); +- when no custom dictionary is configured, opening the Spelling settings to add one. -Manage the project and application dictionaries, and add your own dictionary files, in **Settings › Editor › Natural Languages › Spelling**. Typo's severity and options are in **Settings › Editor › Inspections** like any other inspection. +Manage the project and application dictionaries, and add your own dictionary files, in **Settings › Editor › Natural Languages › Spelling**. The page's **Default dictionary** selects where the plain "Save '…' to dictionary" row writes (project dictionary by default); the → submenu always offers every dictionary. Typo's severity and options are in **Settings › Editor › Inspections** like any other inspection. ## Before committing diff --git a/docs/zh/guide/inspections.mdx b/docs/zh/guide/inspections.mdx index 4f77f68be..94f56e190 100644 --- a/docs/zh/guide/inspections.mdx +++ b/docs/zh/guide/inspections.mdx @@ -72,9 +72,10 @@ description: "编辑器和问题工具窗口中的问题、快速修复与意图 在拼写错误上按 `⌥↵` / `Alt+Enter` 可以: - **拼写错误:更改为…**(注释、字符串和文本)或 **拼写错误:重命名为…**(声明的名称,通过重命名完成,引用会一并更新); -- 把这个词保存到项目级或应用程序级词典。 +- 把这个词保存到项目级或应用程序级词典,或保存到某个自定义词典(按配置的路径列出;单词会追加到文件里,文件不存在时会创建——Hunspell `.dic` 的词数行会同步更新); +- 尚未配置自定义词典时,打开拼写设置页添加一个。 -项目词典、应用程序词典和自定义词典文件在 **设置 › 编辑器 › 自然语言 › 拼写** 中管理。拼写错误检查的严重性和选项与其他检查一样,在 **设置 › 编辑器 › 检查** 中设置。 +项目词典、应用程序词典和自定义词典文件在 **设置 › 编辑器 › 自然语言 › 拼写** 中管理。页顶的 **默认词典** 决定「将 '…' 保存到词典」行的写入目标(默认项目词典);→ 子菜单始终列出全部词典。拼写错误检查的严重性和选项与其他检查一样,在 **设置 › 编辑器 › 检查** 中设置。 ## 提交之前 diff --git a/e2e/spellingSettingsLayout.spec.ts b/e2e/spellingSettingsLayout.spec.ts index 49b0a3f72..8f84ddb89 100644 --- a/e2e/spellingSettingsLayout.spec.ts +++ b/e2e/spellingSettingsLayout.spec.ts @@ -41,6 +41,16 @@ test("Spelling puts dictionary files first and keeps accepted words in separate await expect(filesList.getByRole("option", { name: "dictionaries/team.dic" })).toBeVisible(); await expect(project).toHaveAttribute("aria-selected", "true"); + // The default dictionary the editor's Save '…' fix writes to (PyCharm's + // "Default dictionary"): the project dictionary by default, custom files join the list. + const defaultBox = settings.getByRole("button", { name: "Default dictionary" }); + await expect(defaultBox).toHaveText("Project dictionary"); + await defaultBox.click(); + const defaultList = page.getByRole("listbox", { name: "Default dictionary" }); + await expect(defaultList.getByRole("option", { name: "dictionaries/team.dic" })).toBeVisible(); + await defaultList.getByRole("option", { name: "Application dictionary" }).click(); + await expect(defaultBox).toHaveText("Application dictionary"); + await words.getByRole("button", { name: "Add", exact: true }).click(); await words.getByRole("textbox", { name: "Word", exact: true }).fill("checkoutable"); await words.getByRole("textbox", { name: "Word", exact: true }).press("Enter"); @@ -60,6 +70,7 @@ test("Spelling puts dictionary files first and keeps accepted words in separate .poll(async () => (await ipcCalls(page, "settings_set")).sort((a, b) => String(a.key).localeCompare(String(b.key)))) .toEqual([ { scope: "global", key: "spelling.customDictionaries", value: JSON.stringify(["dictionaries/team.dic"]) }, + { scope: "global", key: "spelling.defaultDictionary", value: JSON.stringify("application") }, { scope: "global", key: "spelling.ideWords", value: JSON.stringify(["worktree"]) }, { scope: "project", key: "spelling.projectWords", value: JSON.stringify(["checkoutable"]) }, ]); diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index ecb0f8712..07707b57f 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -619,6 +619,7 @@ settings_removed_theme always project_host bin settings_set always project_host bindings sync show_system_notification trusted desktop bindings sync spell_check always project_host bindings async +spell_save_to_dictionary always project_host bindings async spell_suggest always project_host bindings async spring_route_sources trusted desktop bindings async ssh_askpass_answer always desktop bindings sync diff --git a/src/bindings.ts b/src/bindings.ts index 9ce00f855..586144f9c 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1745,6 +1745,14 @@ export const commands = { * `cancel_request(request)`. */ spellCheck: (doc: DocId, scope: SpellScope, request: RequestId) => typedError(__TAURI_INVOKE("spell_check", { doc, scope, request })), + /** + * Appends `word` to the custom dictionary `dictionary` (a + * `spelling.customDictionaries` entry: `~/…` from home, relative from the + * project root) and reports which file was written, creating it when missing. + * A Hunspell `.dic` with a `.aff` beside it keeps its word count line current; + * the speller picks the change up through its own mtime cache. + */ + spellSaveToDictionary: (dictionary: string, word: string) => typedError(__TAURI_INVOKE("spell_save_to_dictionary", { dictionary, word })), /** Replacements for a misspelt `word`, best first (Typo › Change to…). */ spellSuggest: (word: string) => typedError(__TAURI_INVOKE("spell_suggest", { word })), /** Spring Web mapping sources for the request-path index of Search Everywhere. */ @@ -12753,6 +12761,12 @@ export type SpellingSettings = { projectWords?: string[], /** Custom dictionaries: plain word lists or Hunspell `.dic` files. */ customDictionaries?: string[], + /** + * Where "Save '…' to dictionary" writes: `project`, `application`, or a + * `spelling.customDictionaries` entry verbatim; empty (the default) is + * project when one is open, application otherwise. + */ + defaultDictionary?: string | null, }; /** One row of SQL Resolution Scopes. */ diff --git a/src/editor/lsp/spelling.test.ts b/src/editor/lsp/spelling.test.ts index 9017b82ad..07fe63171 100644 --- a/src/editor/lsp/spelling.test.ts +++ b/src/editor/lsp/spelling.test.ts @@ -14,12 +14,19 @@ const settingsSet = vi.fn(async (_scope: string, _key: string, value: string) => status: "ok" as const, data: { spelling: { ideWords: [], projectWords: JSON.parse(value), customDictionaries: [] } } as unknown as Settings, })); +const spellSaveToDictionary = vi.fn(async () => ({ status: "ok" as const, data: "team.dic" })); vi.mock("@/platform/ipc", async (orig) => { const actual = await orig(); return { ...actual, isTauri: () => true, - commands: { ...actual.commands, spellCheck, settingsSet, cancelRequest: vi.fn(async () => {}) }, + commands: { + ...actual.commands, + spellCheck, + settingsSet, + spellSaveToDictionary, + cancelRequest: vi.fn(async () => {}), + }, }; }); @@ -78,10 +85,12 @@ describe("Typo inspection", () => { view.dispatch({ selection: { anchor: 5 } }); expect(spellingIntentions(view).map((i) => i.label)).toEqual(["Typo: Change to…", "Save 'mesage' to dictionary"]); - // IDEA's → menu: each dictionary level and the inspection's controls. + // IDEA's → menu: each dictionary level, each configured custom dictionary + // (the settings page when there is none) and the inspection's controls. expect(spellingIntentions(view)[0]!.submenu?.map((i) => ("label" in i ? i.label : "-"))).toEqual([ "Save to project-level dictionary", "Save to application-level dictionary", + "Add custom dictionary…", "-", "Edit inspection profile setting", "Disable inspection", @@ -97,6 +106,67 @@ describe("Typo inspection", () => { expect(spellCheck).toHaveBeenCalledTimes(2); }); + it("offers each configured custom dictionary and saves through the backend", async () => { + vi.useFakeTimers(); + useProject.setState({ + project: { root: "/p" } as never, + settings: { spelling: { customDictionaries: ["~/words/team.dic", " docs/local.txt "] } } as never, + }); + const view = editor("// mesage"); + await settle(); + view.dispatch({ selection: { anchor: 5 } }); + expect(spellingIntentions(view)[0]!.submenu?.map((i) => ("label" in i ? i.label : "-"))).toEqual([ + "Save to project-level dictionary", + "Save to application-level dictionary", + "Save to '~/words/team.dic'", + "Save to 'docs/local.txt'", + "-", + "Edit inspection profile setting", + "Disable inspection", + ]); + const save = spellingIntentions(view)[0]!.submenu!.find( + (i) => "id" in i && i.id === "spelling.saveCustom.docs/local.txt", + ); + if (!save || !("run" in save) || typeof save.run !== "function") throw new Error("no save row"); + await save.run(); + expect(spellSaveToDictionary).toHaveBeenCalledWith("docs/local.txt", "mesage"); + // The dictionary file changed: the file is re-checked. + await settle(); + expect(spellCheck).toHaveBeenCalledTimes(2); + }); + + it("saves to the default dictionary the settings chose", async () => { + vi.useFakeTimers(); + // A custom dictionary as the default: the row writes the file, not settings. + useProject.setState({ + project: { root: "/p" } as never, + settings: { + spelling: { customDictionaries: ["docs/local.txt"], defaultDictionary: "docs/local.txt" }, + } as never, + }); + const view = editor("// mesage"); + await settle(); + view.dispatch({ selection: { anchor: 5 } }); + await spellingIntentions(view)[1]!.run(); + expect(spellSaveToDictionary).toHaveBeenCalledWith("docs/local.txt", "mesage"); + expect(settingsSet).not.toHaveBeenCalled(); + + // The application dictionary as the default, and a removed custom + // dictionary falls back to the project one. + const application = { spelling: { customDictionaries: ["docs/local.txt"], defaultDictionary: "application" } }; + useProject.setState({ settings: application as never }); + await spellingIntentions(view)[1]!.run(); + expect(settingsSet).toHaveBeenCalledWith("global", "spelling.ideWords", JSON.stringify(["mesage"])); + vi.clearAllMocks(); + useProject.setState({ + settings: { + spelling: { customDictionaries: ["docs/local.txt"], defaultDictionary: "~/words/gone.dic" }, + } as never, + }); + await spellingIntentions(view)[1]!.run(); + expect(settingsSet).toHaveBeenCalledWith("project", "spelling.projectWords", JSON.stringify(["mesage"])); + }); + it("does not run while the inspection is disabled", async () => { vi.useFakeTimers(); useProject.setState({ diff --git a/src/editor/lsp/spelling.ts b/src/editor/lsp/spelling.ts index 6220ee49b..0283b28de 100644 --- a/src/editor/lsp/spelling.ts +++ b/src/editor/lsp/spelling.ts @@ -10,6 +10,7 @@ import { StateEffect, StateField, type EditorState, type Extension } from "@code import { EditorView, ViewPlugin } from "@codemirror/view"; import { whenSynced } from "@/editor/api"; import { call, commands, isCancelled, isTauri, nextRequestId, type RequestId } from "@/platform/ipc"; +import { executeAction } from "@/platform/actions"; import { useProject } from "@/platform/project"; import { inspectionOption, @@ -40,6 +41,9 @@ interface PlacedTypo { const setTypos = StateEffect.define(); +/** A custom dictionary file changed on disk; the file is checked again. */ +const dictionariesChanged = StateEffect.define(); + /** The last check's typos, mapped through later edits (for the quick fixes). */ const typosField = StateField.define({ create: () => [], @@ -83,6 +87,48 @@ export async function saveToDictionary(word: string, level: "project" | "ide") { useProject.setState({ settings }); } +/** Configured custom dictionaries (`spelling.customDictionaries`), trimmed and in order. */ +function customDictionaries(): string[] { + return (spellingOf(useProject.getState().settings)?.customDictionaries ?? []).map((d) => d.trim()).filter(Boolean); +} + +/** + * Appends the word to a custom dictionary file (the backend resolves `~/…` + * against the home folder, relative paths against the project root, and + * creates the file when missing). The dictionary change re-checks the file + * like the other saves; an error is reported at the caret. + */ +async function saveToCustomDictionary(view: EditorView, dictionary: string, word: string) { + try { + await call(commands.spellSaveToDictionary(dictionary, word)); + view.dispatch({ effects: dictionariesChanged.of(null) }); + } catch (e) { + if (!isCancelled(e)) showHint(view, e instanceof Error ? e.message : String(e), { tone: "error" }); + } +} + +/** + * The dictionary "Save '…' to dictionary" writes to: the Default dictionary + * setting (`project`, `application`, or a custom dictionary's configured + * path); without one, project when a project is open, application otherwise. + * A default naming a removed dictionary, or a project's file with no project + * open, falls back — the row always works. + */ +function defaultSaveTarget(view: EditorView, word: string): () => void { + const hasProject = !!useProject.getState().project; + const setting = spellingOf(useProject.getState().settings)?.defaultDictionary; + if ( + hasProject && + setting && + setting !== "project" && + setting !== "application" && + customDictionaries().includes(setting) + ) { + return () => saveToCustomDictionary(view, setting, word); + } + return () => saveToDictionary(word, hasProject && setting !== "application" ? "project" : "ide"); +} + function typoAt(state: EditorState, pos: number): PlacedTypo | undefined { return state .field(typosField, false) @@ -146,8 +192,8 @@ export function spellingIntentions(view: EditorView): ListPopupItem[] { const typo = typoAt(view.state, sel.head); if (!typo) return []; const hasProject = !!useProject.getState().project; - // One row saves to the project dictionary (application-level without a project); - // its submenu still offers each level, then the inspection controls. + const dictionaries = hasProject ? customDictionaries() : []; + // The submenu offers each available dictionary and the inspection controls. const saveSubmenu: MenuItem[] = [ ...(hasProject ? [ @@ -163,6 +209,20 @@ export function spellingIntentions(view: EditorView): ListPopupItem[] { label: "Save to application-level dictionary", run: () => void saveToDictionary(typo.word, "ide"), }, + ...dictionaries.map((d) => ({ + id: `spelling.saveCustom.${d}`, + label: tx`Save to '${d}'`, + run: () => void saveToCustomDictionary(view, d, typo.word), + })), + ...(dictionaries.length + ? [] + : [ + { + id: "spelling.addCustom", + label: "Add custom dictionary…", + run: () => void executeAction("file.settings", "editor.naturalLanguages.spelling"), + }, + ]), { kind: "separator" }, ...intentionControls({ id: SPELLING_INSPECTION, name: "Typo" }), ]; @@ -184,7 +244,7 @@ export function spellingIntentions(view: EditorView): ListPopupItem[] { id: "spelling.save", label: tx`Save '${typo.word}' to dictionary`, icon: "bulb-fix", - run: () => saveToDictionary(typo.word, hasProject ? "project" : "ide"), + run: defaultSaveTarget(view, typo.word), submenu: saveSubmenu, }, ]; @@ -256,7 +316,7 @@ export function spellingExtension(): Extension { }); return { update: (u) => { - if (u.docChanged) schedule(); + if (u.docChanged || u.transactions.some((tr) => tr.effects.some((e) => e.is(dictionariesChanged)))) schedule(); }, destroy: () => { clearTimeout(timer); diff --git a/src/features/settings/model/schema.ts b/src/features/settings/model/schema.ts index b9f34ef99..66541c359 100644 --- a/src/features/settings/model/schema.ts +++ b/src/features/settings/model/schema.ts @@ -160,6 +160,8 @@ export interface SpellingValid { ideWords: string[]; projectWords: string[]; customDictionaries: string[]; + /** Where "Save '…' to dictionary" writes; empty means project (application without a project). */ + defaultDictionary: string; } const stringList = (v: unknown): string[] => @@ -171,6 +173,7 @@ function validateSpelling(raw: unknown): SpellingValid { ideWords: stringList(r.ideWords), projectWords: stringList(r.projectWords), customDictionaries: stringList(r.customDictionaries), + defaultDictionary: typeof r.defaultDictionary === "string" ? r.defaultDictionary : "", }; } @@ -226,7 +229,7 @@ export const DEFAULT_SETTINGS: ValidSettings = { cmake: {}, projectStructure: DEFAULT_PROJECT_STRUCTURE, inspections: DEFAULT_INSPECTIONS, - spelling: { ideWords: [], projectWords: [], customDictionaries: [] }, + spelling: { ideWords: [], projectWords: [], customDictionaries: [], defaultDictionary: "" }, tools: {}, languageServers: {}, agents: { diff --git a/src/features/settings/pages/editor/spelling.tsx b/src/features/settings/pages/editor/spelling.tsx index 46c670c20..7ad40deb5 100644 --- a/src/features/settings/pages/editor/spelling.tsx +++ b/src/features/settings/pages/editor/spelling.tsx @@ -9,7 +9,8 @@ import { useSettingsDialog } from "../../model/staging"; import { useSetting } from "../../components/context"; import { GlobListEditor, Row, SearchLabel, Section } from "../../components/Form"; import { useProject } from "@/platform/project"; -import { T, Tabs } from "@/ui"; +import { Select, T, Tabs } from "@/ui"; +import type { SelectOption } from "@/ui"; import type { PageSpec } from "../spec"; import formStyles from "../../components/Form.module.css"; import styles from "./Spelling.module.css"; @@ -101,8 +102,29 @@ function AcceptedWords() { function SpellingPage() { const [dictionaries, setDictionaries] = useSetting("spelling.customDictionaries", "global"); + const [defaultDictionary, setDefaultDictionary] = useSetting("spelling.defaultDictionary", "global"); + const newProjects = useSettingsDialog((s) => s.newProjects); + const hasProject = useProject((s) => !!s.project) && !newProjects; + const fallback = hasProject ? "project" : "application"; + const options: SelectOption[] = [ + ...(hasProject ? [{ value: "project", label: "Project dictionary" }] : []), + { value: "application", label: "Application dictionary" }, + ...words(dictionaries ?? []) + .filter((d) => d !== "project" && d !== "application") + .map((d) => ({ value: d, label: d, verbatim: true })), + ]; return (
+
+ +