feat(spelling): save typos to custom dictionaries with a default dictionary setting (#5466)

Co-authored-by: muutot <92625353+muutot@users.noreply.github.com>
This commit is contained in:
Muu
2026-11-24 06:01:01 +08:00
committed by GitHub
co-authored by muutot
parent ea7ec41064
commit bd0f28cd3b
16 changed files with 441 additions and 22 deletions
@@ -71,6 +71,11 @@ pub struct SpellingSettings {
pub project_words: Vec<String>,
/// Custom dictionaries: plain word lists or Hunspell `.dic` files.
pub custom_dictionaries: Vec<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.
#[specta(optional)]
pub default_dictionary: Option<String>,
}
/// Changes to one inspection; absent fields keep the inspection's defaults.
+110 -5
View File
@@ -20,13 +20,18 @@ fn dictionary_paths(settings: &SpellingSettings, root: &Path) -> Vec<PathBuf> {
.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<String> {
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::<usize>();
let header = text[start..].lines().next().unwrap_or_default();
if let Some(count) = header.trim().parse::<usize>().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")
);
}
}
}
+107
View File
@@ -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<Host> {
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;
}
+6 -5
View File
@@ -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<PathBuf> {
pub fn affix_file(path: &Path) -> Option<PathBuf> {
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);
}
+3 -2
View File
@@ -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
+3 -2
View File
@@ -72,9 +72,10 @@ description: "编辑器和问题工具窗口中的问题、快速修复与意图
在拼写错误上按 `⌥↵` / `Alt+Enter` 可以:
- **拼写错误:更改为…**(注释、字符串和文本)或 **拼写错误:重命名为…**(声明的名称,通过重命名完成,引用会一并更新);
- 把这个词保存到项目级或应用程序级词典。
- 把这个词保存到项目级或应用程序级词典,或保存到某个自定义词典(按配置的路径列出;单词会追加到文件里,文件不存在时会创建——Hunspell `.dic` 的词数行会同步更新);
- 尚未配置自定义词典时,打开拼写设置页添加一个。
项目词典、应用程序词典和自定义词典文件在 **设置 › 编辑器 › 自然语言 › 拼写** 中管理。拼写错误检查的严重性和选项与其他检查一样,在 **设置 › 编辑器 › 检查** 中设置。
项目词典、应用程序词典和自定义词典文件在 **设置 › 编辑器 › 自然语言 › 拼写** 中管理。页顶的 **默认词典** 决定「将 '…' 保存到词典」行的写入目标(默认项目词典);→ 子菜单始终列出全部词典。拼写错误检查的严重性和选项与其他检查一样,在 **设置 › 编辑器 › 检查** 中设置。
## 提交之前
+11
View File
@@ -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"]) },
]);
+1
View File
@@ -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
+14
View File
@@ -1745,6 +1745,14 @@ export const commands = {
* `cancel_request(request)`.
*/
spellCheck: (doc: DocId, scope: SpellScope, request: RequestId) => typedError<Typo[], IdeError>(__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<string, IdeError>(__TAURI_INVOKE("spell_save_to_dictionary", { dictionary, word })),
/** Replacements for a misspelt `word`, best first (Typo › Change to…). */
spellSuggest: (word: string) => typedError<string[], IdeError>(__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. */
+72 -2
View File
@@ -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<typeof import("@/platform/ipc")>();
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({
+64 -4
View File
@@ -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<readonly PlacedTypo[]>();
/** A custom dictionary file changed on disk; the file is checked again. */
const dictionariesChanged = StateEffect.define<null>();
/** The last check's typos, mapped through later edits (for the quick fixes). */
const typosField = StateField.define<readonly PlacedTypo[]>({
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);
+4 -1
View File
@@ -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: {
@@ -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<string[]>("spelling.customDictionaries", "global");
const [defaultDictionary, setDefaultDictionary] = useSetting<string>("spelling.defaultDictionary", "global");
const newProjects = useSettingsDialog((s) => s.newProjects);
const hasProject = useProject((s) => !!s.project) && !newProjects;
const fallback = hasProject ? "project" : "application";
const options: SelectOption<string>[] = [
...(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 (
<div className={styles.spelling}>
<Section stackFields>
<Row label="Default dictionary" hint="The dictionary the editor's Save '…' to dictionary quick fix writes to.">
<Select
value={options.some((option) => option.value === defaultDictionary) ? defaultDictionary : fallback}
options={options}
onChange={(v) => setDefaultDictionary(v)}
aria-label="Default dictionary"
/>
</Row>
</Section>
<Section title="Custom dictionaries">
<Row
label="Dictionary files"
+7
View File
@@ -1,4 +1,11 @@
{
"Default dictionary": "Default dictionary",
"The dictionary the editor's Save '…' to dictionary quick fix writes to.": "The dictionary the editor's Save '…' to dictionary quick fix writes to.",
"Save to '{dictionary}'": "Save to '{dictionary}'",
"Add custom dictionary…": "Add custom dictionary…",
"Select a configured custom dictionary": "Select a configured custom dictionary",
"'{word}' is not a word a dictionary can list": "'{word}' is not a word a dictionary can list",
"{path} is not a writable dictionary file": "{path} is not a writable dictionary file",
"Task Actions": "Task Actions",
"Search commits": "Search commits",
"Amend commit failed": "Amend commit failed",
+4
View File
@@ -4126,6 +4126,8 @@
"Dictionary files": "詞典檔案",
"No custom dictionaries": "沒有自訂詞典",
"Dictionary path": "詞典路徑",
"Default dictionary": "預設詞典",
"The dictionary the editor's Save '…' to dictionary quick fix writes to.": "編輯器中「將 '…' 儲存到詞典」快速修復寫入的詞典。",
"Natural Languages": "自然語言",
"Java Class › JUnit 5 Test": "Java 類別 › JUnit 5 測試",
"Kotlin Class/File › JUnit 5 Test": "Kotlin 類別/檔案 › JUnit 5 測試",
@@ -4857,6 +4859,8 @@
"Save '{word}' to dictionary": "將 '{word}' 儲存到詞典",
"Save to project-level dictionary": "儲存到專案級詞典",
"Save to application-level dictionary": "儲存到應用程式級詞典",
"Save to '{dictionary}'": "儲存到 '{dictionary}'",
"Add custom dictionary…": "新增自訂詞典…",
"Typo: In word '{word}'": "拼寫錯誤:單字 '{word}'",
"Choose Super Class or Interface ({count} found)": "選擇超類別或介面(找到 {count} 個)",
"Choose Super Method of {name} ({count} found)": "選擇 {name} 的超方法(找到 {count} 個)",
+7
View File
@@ -4578,6 +4578,8 @@
"Dictionary files": "词典文件",
"No custom dictionaries": "没有自定义词典",
"Dictionary path": "词典路径",
"Default dictionary": "默认词典",
"The dictionary the editor's Save '…' to dictionary quick fix writes to.": "编辑器中「将 '…' 保存到词典」快速修复写入的词典。",
"Natural Languages": "自然语言",
"Java Class › JUnit 5 Test": "Java 类 › JUnit 5 测试",
"Kotlin Class/File › JUnit 5 Test": "Kotlin 类/文件 › JUnit 5 测试",
@@ -5309,6 +5311,11 @@
"Save '{word}' to dictionary": "将 '{word}' 保存到词典",
"Save to project-level dictionary": "保存到项目级词典",
"Save to application-level dictionary": "保存到应用程序级词典",
"Save to '{dictionary}'": "保存到 '{dictionary}'",
"Add custom dictionary…": "添加自定义词典…",
"Select a configured custom dictionary": "请选择已配置的自定义词典",
"'{word}' is not a word a dictionary can list": "词典无法收录“{word}”",
"{path} is not a writable dictionary file": "{path} 不是可写的词典文件",
"Typo: In word '{word}'": "拼写错误:单词 '{word}'",
"Choose Super Class or Interface ({count} found)": "选择超类或接口(找到 {count} 个)",
"Choose Super Method of {name} ({count} found)": "选择 {name} 的超方法(找到 {count} 个)",