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
Add code-fence language autocompletion to Markdown editor
Elian Doranf4e97e4c51a1
diff --git a/apps/client/src/widgets/type_widgets/code/Markdown.spec.ts b/apps/client/src/widgets/type_widgets/code/Markdown.spec.tsindex 696e00d18c..67ab7b3f2d 100644--- a/apps/client/src/widgets/type_widgets/code/Markdown.spec.ts+++ b/apps/client/src/widgets/type_widgets/code/Markdown.spec.ts@@ -2,9 +2,12 @@// DOMPurify relies on browser-faithful DOM traversal (NodeIterator); happy-dom// mishandles it and strips valid markup (surfaced by dompurify 3.4.8). Run the// sanitization-dependent specs under jsdom, which matches real-browser behavior.+import { markdown } from "@codemirror/lang-markdown";+import { ensureSyntaxTree } from "@codemirror/language";+import { EditorState } from "@codemirror/state";import { describe, expect, it } from "vitest";-import { buildTaskItemInsert, renderWithSourceLines } from "./Markdown.js";+import { buildTaskItemInsert, isClosingFence, parseCodeFencePrefix, renderWithSourceLines } from "./Markdown.js";describe("renderWithSourceLines", () => {function extractLines(src: string): number[] {@@ -238,3 +241,61 @@ describe("buildTaskItemInsert", () => {expect(buildTaskItemInsert("/", true)).toBe("[/] ");});});++describe("parseCodeFencePrefix", () => {+ it("matches a bare fence opener", () => {+ expect(parseCodeFencePrefix("```")).toEqual({ langStart: 3, typed: "" });+ });++ it("captures the partial language token after the backticks", () => {+ expect(parseCodeFencePrefix("```js")).toEqual({ langStart: 3, typed: "js" });+ expect(parseCodeFencePrefix("```c++")).toEqual({ langStart: 3, typed: "c++" });+ });++ it("accounts for leading indentation in langStart", () => {+ expect(parseCodeFencePrefix(" ```py")).toEqual({ langStart: 7, typed: "py" });+ });++ it("handles fences longer than three backticks", () => {+ expect(parseCodeFencePrefix("`````")).toEqual({ langStart: 5, typed: "" });+ });++ it("rejects non-fence text", () => {+ expect(parseCodeFencePrefix("``")).toBeNull(); // too few backticks+ expect(parseCodeFencePrefix("text ```js")).toBeNull(); // not at line start+ expect(parseCodeFencePrefix("```js ")).toBeNull(); // language already finished (trailing space)+ });+});++describe("isClosingFence", () => {+ function lineStart(doc: string, lineNumber: number): number {+ const state = EditorState.create({ doc, extensions: [ markdown() ] });+ ensureSyntaxTree(state, doc.length);+ return state.doc.line(lineNumber).from;+ }++ function check(doc: string, lineNumber: number): boolean {+ const state = EditorState.create({ doc, extensions: [ markdown() ] });+ ensureSyntaxTree(state, doc.length);+ return isClosingFence(state, state.doc.line(lineNumber).from);+ }++ it("treats the first fence line of a block as an opener", () => {+ expect(check("```js\ncode\n```", 1)).toBe(false);+ });++ it("treats the terminating fence line as a closer", () => {+ expect(check("```js\ncode\n```", 3)).toBe(true);+ });++ it("treats a new fence after a closed block as an opener", () => {+ // The second block's opener must still offer completions.+ expect(check("```js\ncode\n```\n\n```py\nmore\n```", 5)).toBe(false);+ });++ it("does not flag a plain line as a closing fence", () => {+ expect(check("just a paragraph", 1)).toBe(false);+ // Referencing lineStart keeps the helper used and documents the offset math.+ expect(lineStart("```js\ncode\n```", 3)).toBe(11);+ });+});diff --git a/apps/client/src/widgets/type_widgets/code/Markdown.tsx b/apps/client/src/widgets/type_widgets/code/Markdown.tsxindex 4e43adc009..f221ec3589 100644--- a/apps/client/src/widgets/type_widgets/code/Markdown.tsx+++ b/apps/client/src/widgets/type_widgets/code/Markdown.tsx@@ -1,8 +1,9 @@import "./Markdown.css";import "./MarkdownCommons.css";-import { autocompletion } from "@codemirror/autocomplete";+import { autocompletion, type Completion, type CompletionContext, type CompletionResult } from "@codemirror/autocomplete";import { syntaxTree } from "@codemirror/language";+import type { EditorState } from "@codemirror/state";import type { SyntaxNode } from "@lezer/common";import VanillaCodeMirror from "@triliumnext/codemirror";import { isAnchorState, type TaskStateDef } from "@triliumnext/commons";@@ -18,6 +19,7 @@ import FNote from "../../../entities/fnote";import froca from "../../../services/froca";import { t } from "../../../services/i18n";import keyboard_actions from "../../../services/keyboard_actions";+import mime_types from "../../../services/mime_types";import note_create from "../../../services/note_create";import options from "../../../services/options";import server from "../../../services/server";@@ -722,13 +724,63 @@ function useSlashCommands(parentComponent: TypeWidgetProps["parentComponent"], e...buildSnippetCompletions(snippetsRef.current.filter((snippet) => snippet.noteId !== noteRef.current.noteId))]};- }],+ }, codeFenceCompletionSource],activateOnTyping: true});editorView.setNamedExtension("slashCommands", ext);}, [editorView]);}++/**+ * Parses the text of a line up to the cursor to detect a fenced code block opener being typed+ * (e.g. "```", "```py", or an indented " ```js"). Returns the offset within the line where the+ * language token starts (right after the run of backticks) and the partial language already typed,+ * or `null` when the text isn't a fence opener. Pure helper, unit-tested.+ */+export function parseCodeFencePrefix(lineBeforeCursor: string): { langStart: number; typed: string } | null {+ const match = /^(\s*)(`{3,})([A-Za-z0-9+#._-]*)$/.exec(lineBeforeCursor);+ if (!match) return null;+ return { langStart: match[1].length + match[2].length, typed: match[3] };+}++/**+ * Whether the fence on the line starting at `lineFrom` closes an already-open code block rather than+ * opening a new one. A bare ``` is both opener and closer in Markdown, so language completions are+ * only offered on openers: inside a `FencedCode` node that began on an earlier line, the ``` closes it.+ */+export function isClosingFence(state: EditorState, lineFrom: number): boolean {+ for (let node: SyntaxNode | null = syntaxTree(state).resolveInner(lineFrom, 1); node; node = node.parent) {+ if (node.name === "FencedCode") return node.from < lineFrom;+ }+ return false;+}++/** Builds the fence-language completions from the user's enabled code-note languages. */+function buildCodeFenceOptions(): Completion[] {+ const seen = new Set<string>();+ const options: Completion[] = [];+ for (const mimeType of mime_types.getMimeTypes()) {+ const code = mimeType.mdLanguageCode;+ if (!mimeType.enabled || !code || seen.has(code)) continue;+ seen.add(code);+ options.push({ label: code, detail: mimeType.title });+ }+ return options;+}++/**+ * Completion source for code-fence languages: triggers only right after a ``` fence opener and lists+ * the user's enabled languages. Returns `null` everywhere else, so it never pollutes the slash menu.+ */+function codeFenceCompletionSource(context: CompletionContext): CompletionResult | null {+ const line = context.state.doc.lineAt(context.pos);+ const parsed = parseCodeFencePrefix(line.text.slice(0, context.pos - line.from));+ if (!parsed || isClosingFence(context.state, line.from)) return null;++ const options = buildCodeFenceOptions();+ return options.length ? { from: line.from + parsed.langStart, options } : null;+}//#endregion//#region Image upload