Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(editor): let the quotation marks be chosen instead of inferred
Elian Doran44024619fdd6
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex fbe3e513eb..36af71295c 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3157,7 +3157,9 @@"title": "Automatic replacements","description": "As you type, some sequences of characters are replaced with the typographic symbol they stand for. This never happens inside a code block or inline code, and pasted text is left alone.","quotes": "Quotation marks",- "quotes_description": "Turns straight quotes into the curved ones of the note's content language: \"quote\" becomes “quote” in English, „quote“ in German and « quote » in French.",+ "quotes_description": "Which marks a straight quote turns into as you type it. Following the note's content language gives “quote” in English, „quote“ in German and « quote » in French; picking a pair instead uses it everywhere, whatever a note is written in.",+ "quotes_auto": "Follow the note's content language",+ "quotes_off": "Leave straight quotes alone","punctuation": "Punctuation","punctuation_description": "Turns ... into an ellipsis (…), and -- and --- surrounded by spaces into an en dash (–) and an em dash (—).","math": "Mathematical symbols",diff --git a/apps/client/src/widgets/type_widgets/options/text_notes.tsx b/apps/client/src/widgets/type_widgets/options/text_notes.tsxindex b4c4bf5493..c2c8944893 100644--- a/apps/client/src/widgets/type_widgets/options/text_notes.tsx+++ b/apps/client/src/widgets/type_widgets/options/text_notes.tsx@@ -19,6 +19,7 @@ import FormText from "../../react/FormText";import FormTextBox, { FormTextBoxWithUnit } from "../../react/FormTextBox";import { useColorScheme, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";import { getHtml } from "../../react/RawHtml";+import { QUOTE_STYLE_PRESETS } from "../text/quotes";import { type CustomReplacement, parseCustomReplacements } from "../text/replacements";import OptionsPageHeader from "./components/OptionsPageHeader";import OptionsRow, { OptionsRowWithToggle } from "./components/OptionsRow";@@ -187,20 +188,34 @@ function EditorFeatures() {* behaviour being undocumented as about it being unwanted, so the examples are the point.*/function AutomaticReplacements() {- const [quotesEnabled, setQuotesEnabled] = useTriliumOptionBool("textNoteQuoteReplacementsEnabled");+ const [quoteStyle, setQuoteStyle] = useTriliumOption("textNoteQuoteStyle");const [punctuationEnabled, setPunctuationEnabled] = useTriliumOptionBool("textNotePunctuationReplacementsEnabled");const [mathEnabled, setMathEnabled] = useTriliumOptionBool("textNoteMathReplacementsEnabled");const [symbolsEnabled, setSymbolsEnabled] = useTriliumOptionBool("textNoteSymbolReplacementsEnabled");return (<OptionsSection title={t("automatic_replacements.title")} description={t("automatic_replacements.description")}>- <OptionsRowWithToggle- name="quote-replacements-enabled"+ <OptionsRow+ name="quote-style"label={t("automatic_replacements.quotes")}description={t("automatic_replacements.quotes_description")}- currentValue={quotesEnabled}- onChange={setQuotesEnabled}- />+ >+ <FormSelect+ currentValue={quoteStyle || "auto"}+ onChange={setQuoteStyle}+ keyProperty="value" titleProperty="label"+ values={[+ { value: "auto", label: t("automatic_replacements.quotes_auto") },+ { value: "off", label: t("automatic_replacements.quotes_off") },+ // The marks are their own label — no wording to translate, and nothing+ // between the choice and what it produces.+ ...QUOTE_STYLE_PRESETS.map(({ id, style }) => ({+ value: id,+ label: `${style.primary[0]}…${style.primary[1]} ${style.secondary[0]}…${style.secondary[1]}`+ }))+ ]}+ />+ </OptionsRow><OptionsRowWithTogglename="punctuation-replacements-enabled"diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsxindex 7887b84062..8bb31099af 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx@@ -58,7 +58,7 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe// the transformation list at plugin init — `normalizeTransformations` runs once inside// `_enableTransformationWatchers` — so unlike the settings read through a getter (link previews,// clipboard image embedding) a live editor has nothing left to re-read.- const [ quoteReplacements ] = useTriliumOptionBool("textNoteQuoteReplacementsEnabled");+ const [ quoteStyle ] = useTriliumOption("textNoteQuoteStyle");const [ punctuationReplacements ] = useTriliumOptionBool("textNotePunctuationReplacementsEnabled");const [ mathReplacements ] = useTriliumOptionBool("textNoteMathReplacementsEnabled");const [ symbolReplacements ] = useTriliumOptionBool("textNoteSymbolReplacementsEnabled");@@ -295,7 +295,7 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe// which is acceptable for a change made deliberately over in the settings.}, [contentLanguage, uiLanguage, isClassicEditor, multilineToolbar,- quoteReplacements, punctuationReplacements, mathReplacements, symbolReplacements,+ quoteStyle, punctuationReplacements, mathReplacements, symbolReplacements,customReplacements, defaultContentLanguage]);diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.tsindex dd3f2707a7..bbd174af6d 100644--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts@@ -324,8 +324,8 @@ describe("CK config - language & emoji", () => {expect(config.typing?.transformations.extra).toHaveLength(2);});- it("drops the quote replacements entirely when their toggle is off", async () => {- optionsState.map.textNoteQuoteReplacementsEnabled = "false";+ it("drops the quote replacements entirely when the style is off", async () => {+ optionsState.map.textNoteQuoteStyle = "off";const config = await buildConfig(baseOpts({ contentLanguage: "de" }));@@ -334,6 +334,27 @@ describe("CK config - language & emoji", () => {expect(config.typing?.transformations.extra).toEqual([]);});+ it("lets a chosen style outrank the note's language", async () => {+ const quotesOf = (config: Awaited<ReturnType<typeof buildConfig>>) =>+ (config.typing?.transformations.extra ?? []).map((t) => (t as { to: string[] }).to);++ // The whole point of picking one: a note written in German still gets the chosen marks. This+ // is what serves someone writing several languages in a single note, whom no per-note+ // language setting can help.+ optionsState.map.textNoteQuoteStyle = "corner";+ expect(quotesOf(await buildConfig(baseOpts({ contentLanguage: "de" })))).toEqual([+ [null, "「", null, "」"],+ [null, "『", null, "』"]+ ]);++ // An id we do not know falls back to following the language rather than to no quotes.+ optionsState.map.textNoteQuoteStyle = "no-such-style";+ expect(quotesOf(await buildConfig(baseOpts({ contentLanguage: "de" })))).toEqual([+ [null, "„", null, "“"],+ [null, "‚", null, "‘"]+ ]);+ });+it("prefixes the emoji definitions URL with the page origin in dev mode", async () => {const prod = await buildConfig(baseOpts());window.glob.isDev = true;diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex b815029471..77b7921c56 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -15,7 +15,7 @@ import { getTaskStateDefinitions, openCustomTaskStateConfig } from "../../../serimport { isMac } from "../../../services/utils.js";import { resolveContentLanguage } from "../../../utils/formatters.js";import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams.js";-import { buildQuoteTransformations, resolveQuoteStyle } from "./quotes.js";+import { buildQuoteTransformations, getQuoteStylePreset, resolveQuoteStyle } from "./quotes.js";import { buildCustomTransformations, parseCustomReplacements } from "./replacements.js";import { buildToolbarConfig } from "./toolbar.js";@@ -327,9 +327,13 @@ function buildTransformationsConfig(contentLanguage: string | null): TextTransfoif (options.get("textNoteMathReplacementsEnabled") !== "true") remove.push("mathematical");if (options.get("textNoteSymbolReplacementsEnabled") !== "true") remove.push("symbols");- const quotesEnabled = options.get("textNoteQuoteReplacementsEnabled") === "true";- const quoteStyle = quotesEnabled ? resolveQuoteStyle(contentLanguage) : null;- if (!quotesEnabled || quoteStyle) {+ const quoteSetting = options.get("textNoteQuoteStyle") || "auto";+ // An unknown id — the option hand-edited, or written by a version offering a preset this one has+ // dropped — falls back to following the language rather than to no quotes at all.+ const quoteStyle = quoteSetting === "off"+ ? null+ : getQuoteStylePreset(quoteSetting) ?? resolveQuoteStyle(contentLanguage);+ if (quoteSetting === "off" || quoteStyle) {remove.push("quotes");}diff --git a/apps/client/src/widgets/type_widgets/text/quotes.spec.ts b/apps/client/src/widgets/type_widgets/text/quotes.spec.tsindex ee89780144..6018a03380 100644--- a/apps/client/src/widgets/type_widgets/text/quotes.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/quotes.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { buildQuoteTransformations, type QuoteStyle, resolveQuoteStyle } from "./quotes.js";+import { buildQuoteTransformations, getQuoteStylePreset, QUOTE_STYLE_PRESETS, type QuoteStyle, resolveQuoteStyle } from "./quotes.js";/*** Applies a transformation the way CKEditor's `TextTransformation` does: match the text before the@@ -93,6 +93,41 @@ describe("resolveQuoteStyle", () => {* below do not carry an invisible character that reads as stray whitespace. */const NNBSP = "\u202F";+describe("QUOTE_STYLE_PRESETS", () => {+ it("offers each pair once, under an id naming the marks rather than a language", () => {+ const ids = QUOTE_STYLE_PRESETS.map((preset) => preset.id);++ expect(new Set(ids).size).toBe(ids.length);+ // Named for their shape: the same pair serves several languages, and a writer picking one is+ // choosing marks, not declaring what they write in.+ expect(ids).toContain("guillemets-spaced");+ expect(ids).not.toContain("fr");+ });++ it("takes its marks from the locale table, so a pair is written in one place", () => {+ // French above all: its narrow no-break spaces are invisible in a diff and have been+ // mistyped before.+ expect(getQuoteStylePreset("guillemets-spaced")).toEqual(resolveQuoteStyle("fr"));+ expect(getQuoteStylePreset("low-high")).toEqual(resolveQuoteStyle("de"));+ expect(getQuoteStylePreset("corner")).toEqual(resolveQuoteStyle("ja"));+ });++ it("inverts the levels for the single-curly pair rather than restating them", () => {+ const english = resolveQuoteStyle("en");++ expect(getQuoteStylePreset("single-curly")).toEqual({+ primary: english?.secondary,+ secondary: english?.primary+ });+ });++ it("returns null for an id it does not know", () => {+ expect(getQuoteStylePreset("no-such-style")).toBeNull();+ expect(getQuoteStylePreset("")).toBeNull();+ expect(getQuoteStylePreset(null)).toBeNull();+ });+});+describe("buildQuoteTransformations", () => {it("replaces both marks of a quoted run, leaving the text between them alone", () => {const { primary, secondary } = transformationsFor("en");diff --git a/apps/client/src/widgets/type_widgets/text/quotes.ts b/apps/client/src/widgets/type_widgets/text/quotes.tsindex 588a81e054..36f2bd79d3 100644--- a/apps/client/src/widgets/type_widgets/text/quotes.ts+++ b/apps/client/src/widgets/type_widgets/text/quotes.ts@@ -71,6 +71,33 @@ const QUOTE_STYLES: Record<string, QuoteStyle> = {"zh-tw": { primary: ["「", "」"], secondary: ["『", "』"] }};+/**+ * The styles offered as an explicit choice, for writers who would rather name their marks than have+ * a language name them — someone writing three languages in one note, or who simply prefers one+ * pair and does not want the note's metadata deciding. macOS offers exactly this and nothing else;+ * LibreOffice offers it alongside the locale defaults, which is the shape taken here.+ *+ * Each entry points at a row of the table above rather than restating its marks, so a pair is+ * written in one place only — the French narrow no-break spaces above all, which are invisible in a+ * diff and have already been mistyped twice.+ */+export const QUOTE_STYLE_PRESETS = [+ { id: "double-curly", style: QUOTE_STYLES.en },+ // The levels the other way up, which is how British typography traditionally set them.+ { id: "single-curly", style: { primary: QUOTE_STYLES.en.secondary, secondary: QUOTE_STYLES.en.primary } },+ { id: "low-high", style: QUOTE_STYLES.de },+ { id: "low-right", style: QUOTE_STYLES.pl },+ { id: "guillemets", style: QUOTE_STYLES.ru },+ { id: "guillemets-spaced", style: QUOTE_STYLES.fr },+ { id: "corner", style: QUOTE_STYLES.ja }+] as const satisfies readonly { id: string; style: QuoteStyle }[];++/** The style a preset id names, or `null` for an id we do not know — a hand-edited option, or one+ * written by a version that offered a preset this one has dropped. */+export function getQuoteStylePreset(id: string | null | undefined): QuoteStyle | null {+ return QUOTE_STYLE_PRESETS.find((preset) => preset.id === id)?.style ?? null;+}+/*** Picks the quote style for the first of `candidates` that maps to one, so callers can express a* preference order — the note's own `#language`, then the formatting locale, then the UI language.diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex 50344d84d1..09e76baec5 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -242,10 +242,11 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActicodeNoteIndentWithTabs: boolean;textNoteEditorMultilineToolbar: boolean;/**- * Whether a typed `"…"` becomes the typographic quotes of the note's language (`“…”`, `„…“`,- * `« … »`). Which marks are produced is decided by the content language, not by this flag.+ * Which typographic quotes a typed `"…"` becomes: `auto` to follow the note's content language,+ * `off` to leave straight quotes alone, or the id of one of `QUOTE_STYLE_PRESETS` to always use+ * that pair whatever the note is written in.*/- textNoteQuoteReplacementsEnabled: boolean;+ textNoteQuoteStyle: string;/** Whether `...` becomes `…`, and ` -- ` / ` --- ` become an en/em dash, as they are typed. */textNotePunctuationReplacementsEnabled: boolean;/** Whether `1/2`, `!=`, `->` and their kin become `½`, `≠`, `→` as they are typed. */diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.tsindex 4b26179338..bc7006934b 100644--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@ -124,7 +124,7 @@ const ALLOWED_OPTIONS = new Set<OptionNames>(["languages","textNoteEditorType","textNoteEditorMultilineToolbar",- "textNoteQuoteReplacementsEnabled",+ "textNoteQuoteStyle","textNotePunctuationReplacementsEnabled","textNoteMathReplacementsEnabled","textNoteSymbolReplacementsEnabled",diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex 565cedd104..500508f5de 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -308,7 +308,9 @@ const defaultOptions: DefaultOption[] = [// The four groups of as-you-type replacements. All on, which is how the editor behaved before// they could be turned off; the point of the setting is that the behaviour is now visible and// refusable, not that it changes for anyone who leaves it alone.- { name: "textNoteQuoteReplacementsEnabled", value: "true", isSynced: true },+ // "auto" keeps the marks following the note's language, which is what the editor did before the+ // setting existed. An explicit preset overrides the language entirely — the point of offering it.+ { name: "textNoteQuoteStyle", value: "auto", isSynced: true },{ name: "textNotePunctuationReplacementsEnabled", value: "true", isSynced: true },{ name: "textNoteMathReplacementsEnabled", value: "true", isSynced: true },{ name: "textNoteSymbolReplacementsEnabled", value: "true", isSynced: true },