Skip to content

Build your personal knowledge base with Trilium Notes

feat(editor): fit a custom replacement to the case it was typed in

Elian Doranab211983bb22
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 94a7c76edd..fbe3e513eb 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2050,7 +2050,7 @@
"formatting-locale": "Date & number format",
"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-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.",
"default-content-language-auto": "Based on the application's language"
},
"backup": {
@@ -3157,7 +3157,7 @@
"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 language: \"quote\" becomes “quote” in English, „quote“ in German and « quote » in French.",
+ "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.",
"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/text/replacements.spec.ts b/apps/client/src/widgets/type_widgets/text/replacements.spec.ts
index a01bdbb9aa..501c8c731e 100644
--- a/apps/client/src/widgets/type_widgets/text/replacements.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/replacements.spec.ts
@@ -12,16 +12,19 @@ function transform(replacement: CustomReplacement, text: string) {
if (!transformation) return null;
const { from, to } = transformation;
- if (!(from instanceof RegExp) || !Array.isArray(to)) {
- throw new Error("custom replacements are built as a RegExp plus a replacement array");
+ if (!(from instanceof RegExp) || typeof to !== "function") {
+ throw new Error("custom replacements are built as a RegExp plus a replacement function");
}
const matches = from.exec(text);
if (!matches) return null;
+ // Upstream passes the captured groups, not the whole match, and maps the result back onto them.
+ const replaces = to(matches.slice(1));
+
let result = text.slice(0, matches.index);
for (let i = 1; i < matches.length; i++) {
- result += to[i - 1] ?? matches[i];
+ result += replaces[i - 1] ?? matches[i];
}
return result + text.slice(matches.index + matches[0].length);
}
@@ -75,6 +78,43 @@ describe("buildCustomTransformations", () => {
expect(transform({ from: "(a+)+$", to: "ok" }, "x (a+)+$ ")).toBe("x ok ");
});
+ it("matches whatever case the text was typed in", () => {
+ const replacement = { from: "teh", to: "the" };
+
+ expect(transform(replacement, "teh ")).toBe("the ");
+ expect(transform(replacement, "Teh ")).toBe("The ");
+ expect(transform(replacement, "TEH ")).toBe("THE ");
+ // A shortcut written in capitals is still found when typed in lowercase.
+ expect(transform({ from: "TN", to: "trilium" }, "tn ")).toBe("trilium ");
+ });
+
+ it("leaves a replacement that carries its own capitals exactly as written", () => {
+ // The capitals are the entire point of these, so no amount of shouting rewrites them.
+ expect(transform({ from: "TN", to: "Trilium Notes" }, "TN ")).toBe("Trilium Notes ");
+ expect(transform({ from: "TN", to: "Trilium Notes" }, "tn ")).toBe("Trilium Notes ");
+ expect(transform({ from: "iphone", to: "iPhone" }, "Iphone ")).toBe("iPhone ");
+ });
+
+ it("capitalizes only the first letter, and only for a single typed capital", () => {
+ // "For example", not "For Example" — and not "FOR EXAMPLE" off one capital letter.
+ expect(transform({ from: "eg", to: "for example" }, "Eg ")).toBe("For example ");
+ expect(transform({ from: "eg", to: "for example" }, "EG ")).toBe("FOR EXAMPLE ");
+ // A one-character shortcut typed capitalized is read as the gentler of the two readings.
+ expect(transform({ from: "a", to: "alpha" }, "A ")).toBe("Alpha ");
+ });
+
+ it("does not read an uncased first character as a capital", () => {
+ // `"(" === "(".toUpperCase()`, so looking at the first character rather than the first
+ // letter with a case would capitalize every shortcut that opens with punctuation.
+ expect(transform({ from: "(c)", to: "copyright" }, "(c) ")).toBe("copyright ");
+ expect(transform({ from: "->", to: "leads to" }, "-> ")).toBe("leads to ");
+ });
+
+ it("leaves a caseless script alone", () => {
+ // `toLowerCase` does nothing to these, so neither branch may claim them.
+ expect(transform({ from: "nihao", to: "你好" }, "Nihao ")).toBe("你好 ");
+ });
+
it("ignores a row that is still half-written", () => {
expect(buildCustomTransformations([ { from: "", to: "Trilium Notes" } ])).toEqual([]);
expect(buildCustomTransformations([ { from: "TN", to: "" } ])).toEqual([]);
diff --git a/apps/client/src/widgets/type_widgets/text/replacements.ts b/apps/client/src/widgets/type_widgets/text/replacements.ts
index f992e080c8..d665dd1d5f 100644
--- a/apps/client/src/widgets/type_widgets/text/replacements.ts
+++ b/apps/client/src/widgets/type_widgets/text/replacements.ts
@@ -49,6 +49,9 @@ export function parseCustomReplacements(json: string | null | undefined): Custom
* last letter is what lets `TNT` still be typed. It is the same shape upstream gives its en dash,
* and the behaviour every office suite's autocorrect has taught people to expect.
*
+ * Matching ignores case, and the replacement's own case decides what comes back — see
+ * {@link adaptCase}.
+ *
* A half-written row (either side still blank) compiles to nothing, so a replacement being typed in
* the settings does not act until it is finished.
*/
@@ -56,7 +59,47 @@ export function buildCustomTransformations(replacements: CustomReplacement[]): T
return replacements
.filter(({ from, to }) => from.trim().length > 0 && to.trim().length > 0)
.map(({ from, to }) => ({
- from: new RegExp(`(^|\\s)(${escapeRegExp(from)})(\\s)$`),
- to: [null, to, null]
+ from: new RegExp(`(^|\\s)(${escapeRegExp(from)})(\\s)$`, "i"),
+ // A function rather than a fixed array: what comes back depends on how the text was
+ // actually typed. CKEditor hands it the captured groups, of which the second is the
+ // matched text.
+ to: (matches: string[]) => [null, adaptCase(matches[1], to), null]
}));
}
+
+/**
+ * Fits the replacement to the case of the text that triggered it, the way every office suite's
+ * autocorrect has done for decades:
+ *
+ * - A replacement carrying capitals of its own is left exactly as written, so `TN` → `Trilium Notes`
+ * and `iphone` → `iPhone` keep the capitals that are the whole point of them.
+ * - An all-lowercase replacement follows what was typed: `teh` → `the`, `Teh` → `The`,
+ * `TEH` → `THE`. Typos happen at the start of sentences, which is precisely where a verbatim
+ * lowercase replacement would be wrong.
+ *
+ * Deciding from the replacement rather than from the shortcut is what keeps this to one rule. Apple's
+ * text replacement instead matches case-insensitively and then lets a separate auto-capitaliser run
+ * over the result, which is why the same shortcut can produce different text on macOS and on iOS.
+ */
+function adaptCase(typed: string, replacement: string): string {
+ // Anything with a capital in it was written that way deliberately. Scripts without case are
+ // unchanged by `toLowerCase`, so they take this branch too and are returned untouched.
+ if (replacement !== replacement.toLowerCase()) return replacement;
+
+ // Only letters that actually have a case get a say. Reading the first *character* instead would
+ // take an uncased one for a capital — `"(" === "(".toUpperCase()` is true — so a shortcut like
+ // `(c)` would capitalize its replacement.
+ const cased = typed.match(/\p{Lu}|\p{Ll}/gu);
+ if (!cased) return replacement;
+
+ // A single typed capital is ambiguous between "capitalised" and "all caps"; read it as the
+ // gentler of the two.
+ if (cased.length > 1 && cased.every((letter) => UPPERCASE.test(letter))) return replacement.toUpperCase();
+ if (UPPERCASE.test(cased[0])) return replacement.replace(/\p{L}/u, (letter) => letter.toUpperCase());
+
+ return replacement;
+}
+
+/** Matches a single uppercase letter. Kept unanchored and stateless — no `g`, which would carry a
+ * `lastIndex` between the calls above. */
+const UPPERCASE = /\p{Lu}/u;