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
+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} 个)",