Skip to content

Build your personal knowledge base with Trilium Notes

feat(editor): write the typographic quotes the note's language actually uses

Elian Doran815fcf334a68
diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.ts
index 12904e621e..f8826f6b57 100644
--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts
@@ -234,6 +234,53 @@ describe("CK config - language & emoji", () => {
expect(config.language).toBeUndefined();
});
+ it("picks the quote style from the note's language, falling back down the locale chain", async () => {
+ const quotesOf = (config: Awaited<ReturnType<typeof buildConfig>>) =>
+ (config.typing?.transformations.extra ?? []).map((t) => (t as { to: string[] }).to);
+
+ // The note's own `#language` outranks both options.
+ optionsState.map.formattingLocale = "fr";
+ optionsState.map.locale = "ru";
+ expect(quotesOf(await buildConfig(baseOpts({ contentLanguage: "de" })))).toEqual([
+ [null, "„", null, "“"],
+ [null, "‚", null, "‘"]
+ ]);
+
+ // Without one, the formatting locale decides.
+ expect(quotesOf(await buildConfig(baseOpts({ contentLanguage: null })))).toEqual([
+ // The gap inside the guillemets is U+202F, the narrow no-break space French sets
+ // there — it looks like a plain space but is not one.
+ [null, "« ", null, " »"],
+ [null, "“", null, "”"]
+ ]);
+
+ // ...and without that, the UI language does.
+ optionsState.map.formattingLocale = "";
+ expect(quotesOf(await buildConfig(baseOpts({ contentLanguage: null })))).toEqual([
+ [null, "«", null, "»"],
+ [null, "„", null, "“"]
+ ]);
+ });
+
+ it("leaves CKEditor's own transformations alone for a locale with no mapping", async () => {
+ optionsState.map.formattingLocale = "ar";
+ optionsState.map.locale = "he";
+ // Last link in the chain, and unmapped too — otherwise the environment's own locale answers.
+ const language = vi.spyOn(navigator, "language", "get").mockReturnValue("fa");
+
+ const config = await buildConfig(baseOpts({ contentLanguage: "ku" }));
+
+ // No `typing` override at all, so the default `quotes` group stays in force.
+ expect(config.typing).toBeUndefined();
+ language.mockRestore();
+ });
+
+ it("keeps the non-quote transformation groups when overriding the quotes", async () => {
+ const config = await buildConfig(baseOpts({ contentLanguage: "de" }));
+
+ expect(config.typing?.transformations.include).toEqual(["symbols", "mathematical", "typography"]);
+ });
+
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.ts
index b9e620385e..87213b00dc 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -11,9 +11,10 @@ import { default as mimeTypesService, getHighlightJsNameForMime } from "../../..
import noteAutocompleteService, { type Suggestion } from "../../../services/note_autocomplete.js";
import options from "../../../services/options.js";
import { ensureMimeTypesForHighlighting, isSyntaxHighlightEnabled } from "../../../services/syntax_highlight.js";
-import { isMac } from "../../../services/utils.js";
import { getTaskStateDefinitions, openCustomTaskStateConfig } from "../../../services/task_states.js";
+import { isMac } from "../../../services/utils.js";
import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams.js";
+import { buildQuoteTransformations, resolveQuoteStyle } from "./quotes.js";
import { buildToolbarConfig } from "./toolbar.js";
/**
@@ -237,6 +238,35 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
embedImage: (src: string) => imageService.embedReferenceImageAsDataUrl(src)
};
+ // Which typographic quotes `"…"` and `'…'` turn into. CKEditor applies the US pair to every
+ // locale it has no entry for, which is wrong rather than merely unstyled for most of the
+ // languages Trilium ships — a German writer wants „…“, a French one « … ».
+ //
+ // Preference order: the note's own `#language` first, since it is the only per-note signal and
+ // the one a multilingual writer sets deliberately, then the same locale chain the date and
+ // number formatters resolve through. That way a German-speaking user gets German quotes without
+ // having labelled anything.
+ //
+ // Resolved here rather than pushed into a live editor because a note's language change already
+ // rebuilds the editor (see the effect deps in `CKEditorWithWatchdog`).
+ const quoteStyle = resolveQuoteStyle(
+ opts.contentLanguage,
+ options.get("formattingLocale"),
+ options.get("locale"),
+ navigator.language
+ );
+ if (quoteStyle) {
+ config.typing = {
+ transformations: {
+ // Upstream's default groups minus `quotes`, whose two transformations are replaced
+ // by the locale-specific pair below. Restated rather than filtered with `remove`
+ // because the config type requires `include`.
+ include: ["symbols", "mathematical", "typography"],
+ extra: buildQuoteTransformations(quoteStyle)
+ }
+ };
+ }
+
// Set up content language.
const { contentLanguage } = opts;
if (contentLanguage) {
diff --git a/apps/client/src/widgets/type_widgets/text/quotes.spec.ts b/apps/client/src/widgets/type_widgets/text/quotes.spec.ts
new file mode 100644
index 0000000000..5ee5b5768a
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/text/quotes.spec.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it } from "vitest";
+
+import { buildQuoteTransformations, type QuoteStyle, resolveQuoteStyle } from "./quotes.js";
+
+/**
+ * Applies a transformation the way CKEditor's `TextTransformation` does: match the text before the
+ * caret, then swap in every group the `to` array names, leaving the `null` ones alone. Lets the
+ * regex and the replacement array be asserted together, which is where a quote pair actually breaks.
+ */
+function transform(transformation: ReturnType<typeof buildQuoteTransformations>[number], text: string) {
+ const from = transformation.from;
+ if (!(from instanceof RegExp) || !Array.isArray(transformation.to)) {
+ throw new Error("the quote transformations are built as a RegExp plus a replacement array");
+ }
+
+ const matches = from.exec(text);
+ if (!matches) return null;
+
+ let result = text.slice(0, matches.index);
+ for (let i = 1; i < matches.length; i++) {
+ result += transformation.to[i - 1] ?? matches[i];
+ }
+ return result + text.slice(matches.index + matches[0].length);
+}
+
+/** The primary (double-quote) and secondary (single-quote) transformation for a locale. */
+function transformationsFor(locale: string) {
+ const style = resolveQuoteStyle(locale);
+ if (!style) throw new Error(`expected ${locale} to resolve to a quote style`);
+ const [primary, secondary] = buildQuoteTransformations(style);
+ return { primary, secondary };
+}
+
+describe("resolveQuoteStyle", () => {
+ it("takes the first candidate that maps, skipping empty ones", () => {
+ const de: QuoteStyle = { primary: ["„", "“"], secondary: ["‚", "‘"] };
+
+ expect(resolveQuoteStyle("de", "fr", "en")).toEqual(de);
+ // The note has no `#language`, so the formatting locale decides.
+ expect(resolveQuoteStyle(null, "de", "en")).toEqual(de);
+ expect(resolveQuoteStyle(undefined, "", "de")).toEqual(de);
+ // An unmapped candidate does not stop the search.
+ expect(resolveQuoteStyle("ar", "de")).toEqual(de);
+ });
+
+ it("returns null when nothing maps, leaving CKEditor's defaults in place", () => {
+ expect(resolveQuoteStyle()).toBeNull();
+ expect(resolveQuoteStyle(null, undefined, "")).toBeNull();
+ // The right-to-left content locales are deliberately unmapped.
+ for (const locale of ["ar", "he", "ku", "fa", "ug"]) {
+ expect(resolveQuoteStyle(locale)).toBeNull();
+ }
+ });
+
+ it("falls back from a region to its base language, but not past a mapped region", () => {
+ expect(resolveQuoteStyle("de-DE")).toEqual(resolveQuoteStyle("de"));
+ expect(resolveQuoteStyle("de-AT")).toEqual(resolveQuoteStyle("de"));
+ expect(resolveQuoteStyle("fr-CA")).toEqual(resolveQuoteStyle("fr"));
+
+ // en-GB inverts the levels, so it must not collapse into `en`.
+ expect(resolveQuoteStyle("en-GB")).toEqual({ primary: ["‘", "’"], secondary: ["“", "”"] });
+ expect(resolveQuoteStyle("en-US")).toEqual({ primary: ["“", "”"], secondary: ["‘", "’"] });
+ expect(resolveQuoteStyle("en-GB")).not.toEqual(resolveQuoteStyle("en"));
+ });
+
+ it("normalizes the locale ids Trilium stores, matching the date and number formatters", () => {
+ // Underscored and case-varied forms reach the same entry.
+ expect(resolveQuoteStyle("pt_br")).toEqual(resolveQuoteStyle("pt-BR"));
+ // Brazilian usage differs from European Portuguese, so it must not collapse into `pt`.
+ expect(resolveQuoteStyle("pt_br")).not.toEqual(resolveQuoteStyle("pt"));
+ expect(resolveQuoteStyle("pt")).toEqual({ primary: ["«", "»"], secondary: ["“", "”"] });
+
+ // `cn`/`tw` are Trilium ids that normalize to zh-CN/zh-TW; only traditional uses brackets.
+ expect(resolveQuoteStyle("cn")).toEqual({ primary: ["“", "”"], secondary: ["‘", "’"] });
+ expect(resolveQuoteStyle("tw")).toEqual({ primary: ["「", "」"], secondary: ["『", "』"] });
+ });
+});
+
+/** U+202F, the narrow no-break space French sets inside its guillemets. Named so the assertions
+ * below do not carry an invisible character that reads as stray whitespace. */
+const NNBSP = "\u202F";
+
+describe("buildQuoteTransformations", () => {
+ it("replaces both marks of a quoted run, leaving the text between them alone", () => {
+ const { primary, secondary } = transformationsFor("en");
+
+ expect(transform(primary, `he said "hello there"`)).toBe(`he said “hello there”`);
+ expect(transform(secondary, `he said 'hello there'`)).toBe(`he said ‘hello there’`);
+ // Opening at the very start of the line is matched too.
+ expect(transform(primary, `"hello"`)).toBe(`“hello”`);
+ });
+
+ it("only fires once the run is closed, and not on a quote mid-word", () => {
+ const { primary, secondary } = transformationsFor("en");
+
+ // Still typing inside the quotes.
+ expect(transform(primary, `he said "hello`)).toBeNull();
+ // The opening mark has to start the line or follow a space, so an apostrophe is safe.
+ expect(transform(secondary, `it's fine`)).toBeNull();
+ expect(transform(secondary, `don't say it's fine`)).toBeNull();
+ });
+
+ it("uses the asymmetric marks of locales that do not mirror them", () => {
+ // German closes with the raised mark rather than a mirror of the opening one.
+ expect(transform(transformationsFor("de").primary, `er sagte "hallo"`)).toBe(`er sagte „hallo“`);
+ expect(transform(transformationsFor("de").secondary, `er sagte 'hallo'`)).toBe(`er sagte ‚hallo‘`);
+ // Polish opens low and closes high.
+ expect(transform(transformationsFor("pl").primary, `on rzekł "cześć"`)).toBe(`on rzekł „cześć”`);
+ // Russian sets guillemets outermost.
+ expect(transform(transformationsFor("ru").primary, `он сказал "привет"`)).toBe(`он сказал «привет»`);
+ });
+
+ it("keeps the narrow no-break spaces French sets inside its guillemets", () => {
+ expect(transform(transformationsFor("fr").primary, `il a dit "bonjour"`)).toBe(`il a dit «${NNBSP}bonjour${NNBSP}»`);
+ // The nested level takes plain double quotes, without the spacing.
+ expect(transform(transformationsFor("fr").secondary, `il a dit 'bonjour'`)).toBe(`il a dit “bonjour”`);
+ });
+
+ it("uses corner brackets for Japanese", () => {
+ expect(transform(transformationsFor("ja").primary, `彼は "こんにちは"`)).toBe(`彼は 「こんにちは」`);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/text/quotes.ts b/apps/client/src/widgets/type_widgets/text/quotes.ts
new file mode 100644
index 0000000000..822ce2a804
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/text/quotes.ts
@@ -0,0 +1,106 @@
+import type { TextTypingTransformationDescription } from "@triliumnext/ckeditor5";
+
+import { normalizeLocale } from "../../../utils/formatters.js";
+
+/** The opening and closing marks of one quotation level. */
+export interface QuoteStyle {
+ /** The marks a quotation is normally set in. */
+ primary: readonly [open: string, close: string];
+ /** The marks a quotation nested inside another one is set in. */
+ secondary: readonly [open: string, close: string];
+}
+
+/**
+ * Which typographic quotes each locale writes, keyed by a lowercased BCP-47 tag. Looked up most
+ * specific first, so `en-gb` wins over `en` and `pt-br` over `pt`.
+ *
+ * CKEditor only ships three of these — US, en-GB and Polish — and applies the US pair to every
+ * locale it has no entry for. That is wrong rather than merely unstyled for a German or French
+ * writer, which is what this table exists to fix.
+ *
+ * A locale is deliberately absent where the convention is one we are not confident about; it then
+ * falls through to CKEditor's default, which is a better outcome than a confident guess. That
+ * currently means the right-to-left content locales (`ar`, `he`, `ku`, `fa`, `ug`), where usage
+ * varies by register and interacts with bidirectional text.
+ */
+const QUOTE_STYLES: Record<string, QuoteStyle> = {
+ // “…” / ‘…’ — the same pair CKEditor defaults to, restated so these locales resolve explicitly
+ // rather than by omission.
+ en: { primary: ["“", "”"], secondary: ["‘", "’"] },
+ ga: { primary: ["“", "”"], secondary: ["‘", "’"] },
+ hi: { primary: ["“", "”"], secondary: ["‘", "’"] },
+ id: { primary: ["“", "”"], secondary: ["‘", "’"] },
+ ko: { primary: ["“", "”"], secondary: ["‘", "’"] },
+ zh: { primary: ["“", "”"], secondary: ["‘", "’"] },
+ "pt-br": { primary: ["“", "”"], secondary: ["‘", "’"] },
+
+ // British usage inverts the two levels.
+ "en-gb": { primary: ["‘", "’"], secondary: ["“", "”"] },
+
+ // „…“ — the closing mark is the raised one, not a mirror of the opening.
+ de: { primary: ["„", "“"], secondary: ["‚", "‘"] },
+ cs: { primary: ["„", "“"], secondary: ["‚", "‘"] },
+
+ // „…” with guillemets for the nested level.
+ pl: { primary: ["„", "”"], secondary: ["«", "»"] },
+ ro: { primary: ["„", "”"], secondary: ["«", "»"] },
+
+ // Guillemets outermost, low-high pair nested.
+ ru: { primary: ["«", "»"], secondary: ["„", "“"] },
+ uk: { primary: ["«", "»"], secondary: ["„", "“"] },
+
+ // French sets a narrow no-break space inside the guillemets. Replacements are not
+ // length-constrained, so the space rides along with the mark it belongs to.
+ fr: { primary: ["« ", " »"], secondary: ["“", "”"] },
+
+ es: { primary: ["«", "»"], secondary: ["“", "”"] },
+ it: { primary: ["«", "»"], secondary: ["“", "”"] },
+ pt: { primary: ["«", "»"], secondary: ["“", "”"] },
+
+ // Corner brackets, used by Japanese and by traditional (but not simplified) Chinese.
+ ja: { primary: ["「", "」"], secondary: ["『", "』"] },
+ "zh-tw": { primary: ["「", "」"], secondary: ["『", "』"] }
+};
+
+/**
+ * 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.
+ * Returns `null` when nothing matches, meaning CKEditor's own defaults should be left in place.
+ */
+export function resolveQuoteStyle(...candidates: (string | null | undefined)[]): QuoteStyle | null {
+ for (const candidate of candidates) {
+ if (!candidate) continue;
+
+ // `normalizeLocale` is what the date and number formatters resolve through, so the ids
+ // Trilium stores (`pt_br`, `cn`, `tw`) map the same way in both places.
+ const locale = normalizeLocale(candidate).toLowerCase();
+ // A region-qualified tag falls back to its base language, so `de-DE` and `de-AT` both find
+ // `de` while `en-GB` still keeps its own entry.
+ const style = QUOTE_STYLES[locale] ?? QUOTE_STYLES[locale.split("-")[0]];
+ if (style) return style;
+ }
+
+ return null;
+}
+
+/**
+ * The transformations that replace a typed `"…"` and `'…'` with the style's marks, in the shape
+ * CKEditor's `typing.transformations.extra` takes.
+ */
+export function buildQuoteTransformations(style: QuoteStyle): TextTypingTransformationDescription[] {
+ return [
+ { from: buildQuotesRegExp("\""), to: [null, style.primary[0], null, style.primary[1]] },
+ { from: buildQuotesRegExp("'"), to: [null, style.secondary[0], null, style.secondary[1]] }
+ ];
+}
+
+/**
+ * Matches a quoted run that ends at the caret: the mark opens at the start of the line or after a
+ * space, and nothing between the two marks is another one of them. Groups 2 and 4 are the marks the
+ * transformation swaps out.
+ *
+ * Replicates the regex CKEditor builds for its own quote transformations, which it does not export.
+ */
+function buildQuotesRegExp(quoteCharacter: string) {
+ return new RegExp(`(^|\\s)(${quoteCharacter})([^${quoteCharacter}]*)(${quoteCharacter})$`);
+}
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 1e11d752a6..6d318c0e12 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -10,7 +10,7 @@ import { COMMON_PLUGINS, CORE_PLUGINS, POPUP_EDITOR_PLUGINS } from "./plugins.js
import { BalloonEditor, DecoupledEditor, FindAndReplaceEditing, FindCommand } from "ckeditor5";
export { default as EditorWatchdog } from "./custom_watchdog";
export { CHAT_INPUT_PLUGINS, MEMO_PLUGINS } from "./plugins.js";
-export type { EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, WatchdogConfig, WatchdogState } from "ckeditor5";
+export type { EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, TextTypingTransformationDescription, WatchdogConfig, WatchdogState } from "ckeditor5";
export type { ClipboardImageEmbedConfig } from "./plugins/clipboard_image_embed.js";
export type { SlashCommandConfig, SlashCommandDefinition } from "./plugins/mention/slash_commands.js";
export type { TriliumMentionFeed } from "./plugins/mention/types.js";