Skip to content

Build your personal knowledge base with Trilium Notes

feat(i18n): give notes a default content language instead of an invisible one

Elian Doranf88ecace39b5
diff --git a/apps/client/src/services/content_language.spec.ts b/apps/client/src/services/content_language.spec.ts
new file mode 100644
index 0000000000..7e22d5cbc9
--- /dev/null
+++ b/apps/client/src/services/content_language.spec.ts
@@ -0,0 +1,62 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { isContentRightToLeft, resolveContentLanguage } from "./content_language.js";
+
+const optionsState = vi.hoisted(() => ({ map: {} as Record<string, string | undefined> }));
+
+vi.mock("./options.js", () => ({
+ default: {
+ get: (name: string) => optionsState.map[name]
+ }
+}));
+
+beforeEach(() => {
+ optionsState.map = {};
+});
+
+describe("resolveContentLanguage", () => {
+ it("prefers the note's own language over the configured default", () => {
+ optionsState.map.defaultContentLanguage = "fr";
+ optionsState.map.locale = "ru";
+
+ expect(resolveContentLanguage("de")).toBe("de");
+ });
+
+ it("falls back to the default content language, then to the application's language", () => {
+ optionsState.map.defaultContentLanguage = "fr";
+ optionsState.map.locale = "ru";
+
+ expect(resolveContentLanguage(null)).toBe("fr");
+ expect(resolveContentLanguage(undefined)).toBe("fr");
+ expect(resolveContentLanguage("")).toBe("fr");
+
+ // An empty default is the "auto" entry, meaning follow the application's language rather
+ // than meaning no language at all.
+ optionsState.map.defaultContentLanguage = "";
+ expect(resolveContentLanguage(null)).toBe("ru");
+ });
+
+ it("returns null only when nothing at all is configured", () => {
+ expect(resolveContentLanguage(null)).toBeNull();
+ });
+});
+
+describe("isContentRightToLeft", () => {
+ it("follows the note's own language", () => {
+ expect(isContentRightToLeft("he")).toBe(true);
+ expect(isContentRightToLeft("de")).toBe(false);
+ });
+
+ it("applies the default to a note that has no language of its own", () => {
+ optionsState.map.defaultContentLanguage = "ar";
+ expect(isContentRightToLeft(null)).toBe(true);
+
+ // ...and a note that does have one is not dragged along by it.
+ expect(isContentRightToLeft("de")).toBe(false);
+ });
+
+ it("treats an unknown or missing language as left-to-right", () => {
+ expect(isContentRightToLeft(null)).toBe(false);
+ expect(isContentRightToLeft("not-a-locale")).toBe(false);
+ });
+});
diff --git a/apps/client/src/services/content_language.ts b/apps/client/src/services/content_language.ts
new file mode 100644
index 0000000000..9277bcf84c
--- /dev/null
+++ b/apps/client/src/services/content_language.ts
@@ -0,0 +1,22 @@
+import { getLocaleById } from "./i18n.js";
+import options from "./options.js";
+
+/**
+ * The language a note is written in.
+ *
+ * A note carries its own language as a `#language` label, set from the Basic Properties ribbon, but
+ * the label is opt-in and the picker that sets it stays empty until content languages are enabled —
+ * so in practice almost no note has one. The `defaultContentLanguage` option answers for all of
+ * them, and an empty value there means "follow the application's language" rather than "none".
+ *
+ * Callers should route the raw label through this rather than reading it directly, so that what the
+ * setting promises to affect — text direction, typographic quotes — actually follows it everywhere.
+ */
+export function resolveContentLanguage(noteLanguage: string | null | undefined): string | null {
+ return noteLanguage || options.get("defaultContentLanguage") || options.get("locale") || null;
+}
+
+/** Whether a note's resolved language is written right-to-left. */
+export function isContentRightToLeft(noteLanguage: string | null | undefined): boolean {
+ return getLocaleById(resolveContentLanguage(noteLanguage))?.rtl ?? false;
+}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index ee59f07eff..c9bf6de3bf 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2048,7 +2048,10 @@
"min-days-in-first-week": "Minimum days in first week",
"first-week-warning": "Changing this may cause duplicates with existing Week Notes.",
"formatting-locale": "Date & number format",
- "formatting-locale-auto": "Based on the application's language"
+ "formatting-locale-auto": "Based on the application's language",
+ "default-content-language": "Default content language",
+ "default-content-language-description": "The language notes are written in unless one is set on the note itself, in the Basic Properties section. It affects features such as right-to-left alignment and which quotation marks typing produces (for example \"quote\" becomes “quote” in English, but „quote“ in German).",
+ "default-content-language-auto": "Based on the application's language"
},
"backup": {
"title": "Backup",
@@ -3108,7 +3111,7 @@
},
"content_language": {
"title": "Content languages",
- "description": "Select one or more languages that should appear in the language selection in the Basic Properties section of a read-only or editable text note. This will allow features such as spell-checking, right-to-left support and text extraction (OCR)."
+ "description": "Select one or more languages that should appear in the language selection in the Basic Properties section of a read-only or editable text note. This will allow features such as spell-checking, right-to-left support, quotation marks and text extraction (OCR)."
},
"switch_layout_button": {
"title_vertical": "Move editing pane to the bottom",
diff --git a/apps/client/src/widgets/note_wrapper.ts b/apps/client/src/widgets/note_wrapper.ts
index 53cce94b55..1ae9679985 100644
--- a/apps/client/src/widgets/note_wrapper.ts
+++ b/apps/client/src/widgets/note_wrapper.ts
@@ -2,7 +2,7 @@ import type { EventData } from "../components/app_context.js";
import type NoteContext from "../components/note_context.js";
import type FNote from "../entities/fnote.js";
import attributeService from "../services/attributes.js";
-import { getLocaleById } from "../services/i18n.js";
+import { isContentRightToLeft } from "../services/content_language.js";
import utils from "../services/utils.js";
import type BasicWidget from "./basic_widget.js";
import FlexContainer from "./containers/flex_container.js";
@@ -67,9 +67,9 @@ export default class NoteWrapperWidget extends FlexContainer<BasicWidget> {
this.$widget.toggleClass("bgfx", hasBackgroundEffects(note));
this.$widget.toggleClass("protected", note.isProtected);
- const noteLanguage = note?.getLabelValue("language");
- const locale = getLocaleById(noteLanguage);
- this.$widget.toggleClass("rtl", !!locale?.rtl);
+ // Resolved rather than read straight off the label: a note with no language of its own
+ // still follows the default content language.
+ this.$widget.toggleClass("rtl", isContentRightToLeft(note?.getLabelValue("language")));
}
async entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {
diff --git a/apps/client/src/widgets/type_widgets/options/i18n.tsx b/apps/client/src/widgets/type_widgets/options/i18n.tsx
index af4133fcd2..b2a01f0fa9 100644
--- a/apps/client/src/widgets/type_widgets/options/i18n.tsx
+++ b/apps/client/src/widgets/type_widgets/options/i18n.tsx
@@ -33,7 +33,7 @@ export default function InternationalizationOptions() {
}
function LocalizationOptions() {
- const { uiLocales, formattingLocales: contentLocales } = useMemo<{ uiLocales: Locale[], formattingLocales: Locale[] }>(() => {
+ const { uiLocales, formattingLocales: contentLocales, writingLocales } = useMemo<{ uiLocales: Locale[], formattingLocales: Locale[], writingLocales: Locale[] }>(() => {
const allLocales = getAvailableLocales();
return {
uiLocales: allLocales.filter(locale => {
@@ -41,6 +41,9 @@ function LocalizationOptions() {
if (locale.devOnly && !glob.isDev) return false;
return true;
}),
+ // Anything a note can be written in, so unlike the formatting list this keeps the
+ // content-only right-to-left locales.
+ writingLocales: allLocales.filter(locale => !locale.devOnly || glob.isDev),
formattingLocales: [
...allLocales.filter(locale => {
if (!locale.electronLocale) return false;
@@ -53,6 +56,7 @@ function LocalizationOptions() {
const [ locale, setLocale ] = useTriliumOption("locale");
const [ formattingLocale, setFormattingLocale ] = useTriliumOption("formattingLocale");
+ const [ defaultContentLanguage, setDefaultContentLanguage ] = useTriliumOption("defaultContentLanguage");
return (
<OptionsSection title={t("i18n.title")}>
@@ -64,6 +68,19 @@ function LocalizationOptions() {
<LocaleSelector locales={contentLocales} currentValue={formattingLocale} onChange={setFormattingLocale} defaultLocale={{ id: "", name: t("i18n.formatting-locale-auto") }} />
</OptionsRow>}
+ <OptionsRow
+ name="default-content-language"
+ label={t("i18n.default-content-language")}
+ description={t("i18n.default-content-language-description")}
+ >
+ <LocaleSelector
+ locales={writingLocales}
+ currentValue={defaultContentLanguage}
+ onChange={setDefaultContentLanguage}
+ defaultLocale={{ id: "", name: t("i18n.default-content-language-auto") }}
+ />
+ </OptionsRow>
+
<DateSettings />
</OptionsSection>
)
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
index 1d7446a012..73292a0452 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
@@ -10,8 +10,8 @@ import { useEffect, useLayoutEffect, useMemo, useRef as usePreactRef } from "pre
import appContext from "../../../components/app_context";
import FNote from "../../../entities/fnote";
+import { isContentRightToLeft } from "../../../services/content_language";
import { applyInlineMermaid, rewriteMermaidDiagramsInContainer } from "../../../services/content_renderer_text";
-import { getLocaleById } from "../../../services/i18n";
import { applyLinkEmbeds } from "../../../services/link_embed";
import { renderMathInElement } from "../../../services/math";
import { trackPendingRender } from "../../../services/pending_renders";
@@ -139,10 +139,9 @@ export function ReadOnlyTextContent({ html, ntxId, dir, className, contentRef: e
function useNoteLanguage(note: FNote) {
const [ language ] = useNoteLabel(note, "language");
- const isRtl = useMemo(() => {
- const correspondingLocale = getLocaleById(language);
- return correspondingLocale?.rtl;
- }, [ language ]);
+ // Resolved rather than read straight off the label, so a note with no language of its own still
+ // lays out the way the default content language says it should.
+ const isRtl = useMemo(() => isContentRightToLeft(language), [ language ]);
return { isRtl };
}
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 f8826f6b57..cefebf8044 100644
--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts
@@ -234,19 +234,32 @@ 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 () => {
+ it("resolves the content language from the note, then the default, then the UI language", async () => {
+ optionsState.map.defaultContentLanguage = "fr";
+ optionsState.map.locale = "ru";
+
+ // The note's own `#language` outranks both options.
+ expect((await buildConfig(baseOpts({ contentLanguage: "de" }))).language).toMatchObject({ content: "de" });
+ // Without one, the default content language answers.
+ expect((await buildConfig(baseOpts({ contentLanguage: null }))).language).toMatchObject({ content: "fr" });
+ // ...and its empty "auto" value follows the application's language instead.
+ optionsState.map.defaultContentLanguage = "";
+ expect((await buildConfig(baseOpts({ contentLanguage: null }))).language).toMatchObject({ content: "ru" });
+ });
+
+ it("derives the quote style from that same resolved language", 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.defaultContentLanguage = "fr";
optionsState.map.locale = "ru";
+
expect(quotesOf(await buildConfig(baseOpts({ contentLanguage: "de" })))).toEqual([
[null, "„", null, "“"],
[null, "‚", null, "‘"]
]);
- // Without one, the formatting locale decides.
+ // With no note language, the default content language 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.
@@ -254,8 +267,8 @@ describe("CK config - language & emoji", () => {
[null, "“", null, "”"]
]);
- // ...and without that, the UI language does.
- optionsState.map.formattingLocale = "";
+ // ...and the "auto" value follows the UI language.
+ optionsState.map.defaultContentLanguage = "";
expect(quotesOf(await buildConfig(baseOpts({ contentLanguage: null })))).toEqual([
[null, "«", null, "»"],
[null, "„", null, "“"]
@@ -263,16 +276,12 @@ describe("CK config - language & emoji", () => {
});
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();
+ // The language itself still applies, so right-to-left text lays out correctly regardless.
+ expect(config.language).toMatchObject({ content: "ku" });
});
it("keeps the non-quote transformation groups when overriding the quotes", async () => {
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index 87213b00dc..465cf76bac 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -4,6 +4,7 @@ import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, formatShortcut, IMAGE_UPLOAD
import i18next from "i18next";
import { copyTextWithToast } from "../../../services/clipboard_ext.js";
+import { resolveContentLanguage } from "../../../services/content_language.js";
import { t } from "../../../services/i18n.js";
import imageService from "../../../services/image.js";
import { getMermaidConfig } from "../../../services/mermaid.js";
@@ -238,23 +239,32 @@ 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 « … ».
+ // The language this note is written in, which governs both its text direction and which
+ // typographic quotes typing produces.
//
- // 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.
+ // The note's own `#language` label wins, being the only per-note signal and the one a
+ // multilingual writer sets deliberately. Almost no note carries one though — the label is
+ // opt-in, and the picker that sets it is empty until content languages are enabled — so the
+ // `defaultContentLanguage` option is what answers in practice. It defaults to English, which is
+ // what every note was implicitly treated as before the option existed; setting it to the empty
+ // "auto" entry follows the application's language instead.
//
- // 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
- );
+ // Deliberately not `formattingLocale`: that one is presented as "Date & number format", so
+ // someone who sets it for unambiguous dates would not expect it to restyle their prose.
+ const contentLanguage = resolveContentLanguage(opts.contentLanguage);
+
+ if (contentLanguage) {
+ config.language = {
+ ui: (typeof config.language === "string" ? config.language : "en"),
+ content: contentLanguage
+ };
+ }
+
+ // CKEditor knows quote conventions for three locales and applies the US pair to everything else,
+ // which is wrong rather than merely unstyled for most of the languages Trilium ships — a German
+ // writer wants „…“, a French one « … ». Resolved here rather than pushed into a live editor
+ // because a language change already rebuilds it (see the effect deps in `CKEditorWithWatchdog`).
+ const quoteStyle = resolveQuoteStyle(contentLanguage);
if (quoteStyle) {
config.typing = {
transformations: {
@@ -267,15 +277,6 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
};
}
- // Set up content language.
- const { contentLanguage } = opts;
- if (contentLanguage) {
- config.language = {
- ui: (typeof config.language === "string" ? config.language : "en"),
- content: contentLanguage
- };
- }
-
// Mention customisation.
if (options.get("textNoteCompletionEnabled") === "true") {
config.mention = {
diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.ts
index b2ee7c0165..38b4965799 100644
--- a/packages/commons/src/lib/options_interface.ts
+++ b/packages/commons/src/lib/options_interface.ts
@@ -83,6 +83,14 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActi
customSearchEngineUrl: string;
locale: string;
formattingLocale: string;
+ /**
+ * The language a note is written in when it carries no `#language` label of its own — which is
+ * almost every note, the label being opt-in. Governs what the content language drives: text
+ * direction and which typographic quotes typing produces.
+ *
+ * An empty value means "follow the application's language" rather than "no language".
+ */
+ defaultContentLanguage: string;
codeBlockTheme: string;
codeBlockThemeMatchesApp: boolean;
codeBlockThemeLight: string;
diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.ts
index f52816d53c..cfca46b3fd 100644
--- a/packages/trilium-core/src/routes/api/options.ts
+++ b/packages/trilium-core/src/routes/api/options.ts
@@ -117,6 +117,7 @@ const ALLOWED_OPTIONS = new Set<OptionNames>([
"editedNotesOpenInRibbon",
"locale",
"formattingLocale",
+ "defaultContentLanguage",
"firstDayOfWeek",
"firstWeekOfYear",
"minDaysInFirstWeek",
diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.ts
index fa92f5c42c..941ed35dd6 100644
--- a/packages/trilium-core/src/services/options_init.ts
+++ b/packages/trilium-core/src/services/options_init.ts
@@ -275,6 +275,10 @@ const defaultOptions: DefaultOption[] = [
// Internationalization
{ name: "locale", value: "en", isSynced: true },
{ name: "formattingLocale", value: "", isSynced: true }, // no value means auto-detect
+ // English rather than "" (which would follow the application's language), so that an install
+ // that never touches this keeps writing the quotes it wrote before the setting existed. An
+ // empty value is still honoured if the user picks the auto entry.
+ { name: "defaultContentLanguage", value: "en", isSynced: true },
{ name: "firstDayOfWeek", value: "1", isSynced: true },
{ name: "firstWeekOfYear", value: "0", isSynced: true },
{ name: "minDaysInFirstWeek", value: "4", isSynced: true },