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(text): paste code copied from VS Code as code
Elian Doran584ba406f3ab
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Developer-specific formatting.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Developer-specific formatting.htmlindex 677f0fafc1..edcbb2a56a 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Developer-specific formatting.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Developer-specific formatting.html@@ -12,6 +12,8 @@look for the <span class="tn-icon cke cke-code"></span> button.</li><li>Type `code` where <code>code</code> is the desired text to be automaticallyformatted as inline code.</li>+ <li>Paste a single line copied from Visual Studio Code. See <a href="#root/_help_QxEyIjRBizuC">Code blocks</a> for+ pasting several lines.</li></ul><h3>Code blocks</h3><p>Code blocks display a snippet of code as a dedicated block:</p>diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.htmlindex 2641c027bd..4ae97532f1 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.html@@ -23,6 +23,16 @@to the last selected language.</li></ul></li>+ <li>Paste several lines of code copied from Visual Studio Code.+ <ul>+ <li>The code block uses the language of the file in Visual Studio Code.</li>+ <li>If that language is not in the list of languages, the code block uses <em>Auto-detected</em>.</li>+ <li>The colors of the Visual Studio Code theme are removed.</li>+ <li>A single line becomes inline code instead of a code block.</li>+ <li>This works in the desktop application and in Chromium-based browsers (Chrome,+ Edge), but not in Firefox.</li>+ </ul>+ </li></ul><h2>Exiting out of the code block</h2><ul>diff --git a/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting.md b/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting.mdindex 928a8a1733..7f8671416b 100644--- a/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting.md+++ b/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting.md@@ -11,6 +11,7 @@ To insert an inline code:* Via the [Formatting toolbar](Formatting%20toolbar.md), look for the <span class="tn-icon cke cke-code"></span> button.* Type \`code\` where `code` is the desired text to be automatically formatted as inline code.+* Paste a single line copied from Visual Studio Code. See [Code blocks](Developer-specific%20formatting/Code%20blocks.md) for pasting several lines.### Code blocksdiff --git a/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.md b/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.mdindex e15459fa88..5894abf547 100644--- a/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.md+++ b/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.md@@ -12,6 +12,12 @@ Note that this feature is meant for generally small snippets of code. For larger* Pressing the arrow next to the icon, which will show a popup with the available languages.* Type ` ``` ` (as in Markdown).* Note that it's not possible to specify the language, as it will default to the last selected language.+* Paste several lines of code copied from Visual Studio Code.+ * The code block uses the language of the file in Visual Studio Code.+ * If that language is not in the list of languages, the code block uses _Auto-detected_.+ * The colors of the Visual Studio Code theme are removed.+ * A single line becomes inline code instead of a code block.+ * This works in the desktop application and in Chromium-based browsers (Chrome, Edge), but not in Firefox.## Exiting out of the code blockdiff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.tsindex 76616959e5..7b9f7ba621 100644--- a/packages/ckeditor5/src/plugins.ts+++ b/packages/ckeditor5/src/plugins.ts@@ -39,6 +39,7 @@ import ImageActions from "./plugins/image_actions.js";import ClipboardBareImage from "./plugins/clipboard_bare_image.js";import ClipboardImageEmbed from "./plugins/clipboard_image_embed.js";import ClipboardPageStyles from "./plugins/clipboard_page_styles.js";+import PasteFromVsCode from "./plugins/paste_from_vscode.js";import TriliumSnippets from "./plugins/snippets/snippets.js";import TriliumAiAssistant from "./plugins/ai_assistant/ai_assistant.js";@@ -115,6 +116,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [ClipboardImageEmbed,ClipboardBareImage,ClipboardPageStyles,+ PasteFromVsCode,AdaptiveColors,TriliumSnippets,TriliumAiAssistant,diff --git a/packages/ckeditor5/src/plugins/paste_from_vscode.spec.ts b/packages/ckeditor5/src/plugins/paste_from_vscode.spec.tsnew file mode 100644index 0000000000..384f97e5bf--- /dev/null+++ b/packages/ckeditor5/src/plugins/paste_from_vscode.spec.ts@@ -0,0 +1,141 @@+import { ClassicEditor, Code, CodeBlock, Essentials, Paragraph, _getModelData, _setModelData } from "ckeditor5";+import { beforeEach, describe, expect, it } from "vitest";++import { createTestEditor } from "../../test/editor-kit.js";+import PasteFromVsCode, { codeBlockLanguage, VSCODE_EDITOR_DATA, vsCodePasteHtml } from "./paste_from_vscode.js";++/** A CSS rule copied out of VS Code under a dark theme: the clipboard's HTML, verbatim. */+const VSCODE_HTML = `<meta charset='utf-8'><div style="color: #bbbebf;background-color: #121314;font-family: Menlo, Monaco, 'Courier New', monospace;font-weight: normal;font-size: 12px;line-height: 18px;white-space: pre;"><div><span style="color: #d7ba7d;">#trilium-error-overlay</span><span style="color: #bbbebf;"> </span><span style="color: #d7ba7d;">.tn-eo-title</span><span style="color: #bbbebf;"> {</span></div><div><span style="color: #bbbebf;"> </span><span style="color: #9cdcfe;">margin</span><span style="color: #bbbebf;">: </span><span style="color: #b5cea8;">0</span><span style="color: #bbbebf;">;</span></div><div><span style="color: #bbbebf;"> </span><span style="color: #9cdcfe;">font-size</span><span style="color: #bbbebf;">: </span><span style="color: #b5cea8;">1.4em</span><span style="color: #bbbebf;">;</span></div><div><span style="color: #bbbebf;"> </span><span style="color: #9cdcfe;">font-weight</span><span style="color: #bbbebf;">: </span><span style="color: #b5cea8;">600</span><span style="color: #bbbebf;">;</span></div><div><span style="color: #bbbebf;">}</span></div></div>`;++/** The same copy as plain text. */+const VSCODE_TEXT = "#trilium-error-overlay .tn-eo-title {\n margin: 0;\n font-size: 1.4em;\n font-weight: 600;\n}";++/** The `vscode-editor-data` entry of the same copy, verbatim. */+const VSCODE_CSS_DATA = `{"version":1,"id":"a35fc511-64ce-42fa-ad40-145ae9353182","isFromEmptySelection":false,"multicursorText":null,"mode":"css"}`;++function clipboard(text: string, editorData?: string, html = "") {+ const types: Record<string, string> = { "text/plain": text, "text/html": html };+ if (editorData !== undefined) {+ types[VSCODE_EDITOR_DATA] = editorData;+ }++ return { getData: (type: string) => types[type] ?? "" };+}++describe("PasteFromVsCode", () => {+ describe("codeBlockLanguage", () => {+ it("maps VS Code language IDs to code block languages", () => {+ expect(codeBlockLanguage("css")).toBe("text-css");+ expect(codeBlockLanguage("typescript")).toBe("application-typescript");+ expect(codeBlockLanguage("python")).toBe("text-x-python");+ });++ it("maps the IDs that differ from the Markdown names, or resolve to a variant there", () => {+ expect(codeBlockLanguage("shellscript")).toBe("text-x-sh");+ expect(codeBlockLanguage("typescriptreact")).toBe("text-typescript-jsx");+ expect(codeBlockLanguage("jsonc")).toBe("application-json");+ expect(codeBlockLanguage("json")).toBe("application-json");+ expect(codeBlockLanguage("java")).toBe("text-x-java");+ expect(codeBlockLanguage("sql")).toBe("text-x-sql");+ });++ it("returns null for a language Trilium has no MIME type for", () => {+ expect(codeBlockLanguage("makefile")).toBeNull();+ expect(codeBlockLanguage("")).toBeNull();+ });+ });++ describe("vsCodePasteHtml", () => {+ it("builds a code block from the plain text of a multi-line copy", () => {+ expect(vsCodePasteHtml(clipboard(VSCODE_TEXT, VSCODE_CSS_DATA, VSCODE_HTML)))+ .toBe(`<pre><code class="language-text-css">${VSCODE_TEXT}</code></pre>`);+ });++ it("builds inline code from a single line, trimmed", () => {+ expect(vsCodePasteHtml(clipboard(" font-size: 1.4em; ", VSCODE_CSS_DATA))).toBe("<code>font-size: 1.4em;</code>");+ // A whole line copied with nothing selected ends in a line break.+ expect(vsCodePasteHtml(clipboard("margin: 0;\r\n", VSCODE_CSS_DATA))).toBe("<code>margin: 0;</code>");+ });++ it("escapes the code", () => {+ expect(vsCodePasteHtml(clipboard("a < b && c > d", VSCODE_CSS_DATA))).toBe("<code>a < b && c > d</code>");+ });++ it("leaves the language out when VS Code names none or an unknown one", () => {+ expect(vsCodePasteHtml(clipboard("a\nb", `{"version":1}`))).toBe("<pre><code>a\nb</code></pre>");+ expect(vsCodePasteHtml(clipboard("a\nb", `{"mode":"makefile"}`))).toBe("<pre><code>a\nb</code></pre>");+ });++ it("declines a clipboard that does not come from VS Code or holds no code", () => {+ expect(vsCodePasteHtml(clipboard(VSCODE_TEXT, undefined, VSCODE_HTML))).toBeNull();+ expect(vsCodePasteHtml(clipboard(VSCODE_TEXT, "not json"))).toBeNull();+ expect(vsCodePasteHtml(clipboard(VSCODE_TEXT, "null"))).toBeNull();+ expect(vsCodePasteHtml(clipboard(" \n ", VSCODE_CSS_DATA))).toBeNull();+ });+ });++ describe("on paste", () => {+ let editor: ClassicEditor;++ beforeEach(async () => {+ editor = await createTestEditor([Essentials, Paragraph, Code, CodeBlock, PasteFromVsCode], {+ codeBlock: {+ languages: [+ { language: "text-x-trilium-auto", label: "Auto-detected" },+ { language: "text-css", label: "CSS" }+ ]+ }+ });+ });++ /** Fires a paste the way `ClipboardObserver` does, with the clipboard HTML as the content. */+ function paste(dataTransfer: ReturnType<typeof clipboard>) {+ editor.editing.view.document.fire("clipboardInput", {+ dataTransfer,+ content: dataTransfer.getData("text/html"),+ method: "paste"+ });++ return _getModelData(editor.model, { withoutSelection: true });+ }++ it("pastes a multi-line copy as a code block in its language, without the theme colors", () => {+ _setModelData(editor.model, "<paragraph>[]</paragraph>");++ expect(paste(clipboard(VSCODE_TEXT, VSCODE_CSS_DATA, VSCODE_HTML))).toBe(+ "<codeBlock language=\"text-css\">#trilium-error-overlay .tn-eo-title {<softBreak></softBreak>"+ + " margin: 0;<softBreak></softBreak> font-size: 1.4em;<softBreak></softBreak>"+ + " font-weight: 600;<softBreak></softBreak>}</codeBlock>"+ );+ });++ it("pastes a single line as inline code within the paragraph", () => {+ _setModelData(editor.model, "<paragraph>Set []to zero.</paragraph>");++ expect(paste(clipboard("margin: 0;", VSCODE_CSS_DATA, "<span style=\"color: #9cdcfe;\">margin: 0;</span>")))+ .toBe("<paragraph>Set <$text code=\"true\">margin: 0;</$text>to zero.</paragraph>");+ });++ it("uses the default language for a language the editor does not offer", () => {+ _setModelData(editor.model, "<paragraph>[]</paragraph>");++ expect(paste(clipboard("a\nb", `{"mode":"python"}`))).toBe(+ "<codeBlock language=\"text-x-trilium-auto\">a<softBreak></softBreak>b</codeBlock>"+ );+ });++ it("pastes plain text into an existing code block", () => {+ _setModelData(editor.model, "<codeBlock language=\"text-css\">[]</codeBlock>");++ expect(paste(clipboard("a\nb", VSCODE_CSS_DATA))).toBe(+ "<codeBlock language=\"text-css\">a<softBreak></softBreak>b</codeBlock>"+ );+ });++ it("leaves a paste from elsewhere alone", () => {+ _setModelData(editor.model, "<paragraph>[]</paragraph>");++ expect(paste(clipboard("a\nb", undefined, "<p>a</p><p>b</p>"))).toBe("<paragraph>a</paragraph><paragraph>b</paragraph>");+ });+ });+});diff --git a/packages/ckeditor5/src/plugins/paste_from_vscode.ts b/packages/ckeditor5/src/plugins/paste_from_vscode.tsnew file mode 100644index 0000000000..a7305da55d--- /dev/null+++ b/packages/ckeditor5/src/plugins/paste_from_vscode.ts@@ -0,0 +1,123 @@+import { getMimeTypeFromMarkdownName, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";+import { Plugin } from "ckeditor5";+import type { ViewDocumentClipboardInputEvent } from "ckeditor5";++/** The clipboard type VS Code writes next to the copied text, holding the language of the editor. */+export const VSCODE_EDITOR_DATA = "vscode-editor-data";++/**+ * VS Code language IDs that `getMimeTypeFromMarkdownName()` does not resolve, or resolves to a+ * variant (`java` to JSP, `json` to JSON-LD, `sql` to MariaDB).+ */+const VSCODE_LANGUAGE_MIMES: Record<string, string> = {+ bat: "application/x-bat",+ dockercompose: "text/x-yaml",+ java: "text/x-java",+ javascriptreact: "text/jsx",+ json: "application/json",+ jsonc: "application/json",+ "objective-c": "text/x-objectivec",+ perl: "text/x-perl",+ php: "text/x-php",+ shellscript: "text/x-sh",+ sql: "text/x-sql",+ swift: "text/x-swift",+ terraform: "text/x-hcl",+ toml: "text/x-toml",+ typescriptreact: "text/typescript-jsx",+ vb: "text/x-vb"+};++/**+ * Pastes code copied from VS Code as code: a single line as inline code, several lines as a code+ * block in the language of the VS Code editor.+ *+ * VS Code puts the syntax-highlighted HTML on the clipboard together with+ * {@link VSCODE_EDITOR_DATA}, a JSON object whose `mode` is the language ID. When that object is+ * present, the plugin replaces the HTML with code built from the plain text, so the indentation is+ * exact and the theme colors are dropped. A language that the editor does not offer falls back to+ * the code block's default language.+ *+ * Pasting into an existing code block is left to `CodeBlockEditing`, whose normal-priority+ * listener inserts the plain text.+ */+export default class PasteFromVsCode extends Plugin {++ static get pluginName() {+ return "PasteFromVsCode" as const;+ }++ init() {+ // `high`, to replace the HTML before `ClipboardPipeline` converts it at `low` priority.+ this.listenTo<ViewDocumentClipboardInputEvent>(+ this.editor.editing.view.document,+ "clipboardInput",+ (_evt, data) => {+ const html = vsCodePasteHtml(data.dataTransfer);+ if (html) {+ data.content = html;+ }+ },+ { priority: "high" }+ );+ }+}++/**+ * The HTML to paste in place of the clipboard's, or `null` if the clipboard holds no code copied+ * from VS Code.+ */+export function vsCodePasteHtml(dataTransfer: { getData(type: string): string }): string | null {+ const mode = readVsCodeMode(dataTransfer.getData(VSCODE_EDITOR_DATA));+ if (mode === null) {+ return null;+ }++ const text = dataTransfer.getData("text/plain").replace(/\r\n?/g, "\n").replace(/\n$/, "");+ if (!text.trim()) {+ return null;+ }++ if (!text.includes("\n")) {+ return `<code>${escapeHtml(text.trim())}</code>`;+ }++ const language = codeBlockLanguage(mode);+ const classAttribute = language ? ` class="language-${language}"` : "";+ return `<pre><code${classAttribute}>${escapeHtml(text)}</code></pre>`;+}++/**+ * The code block language (a MIME type normalized by `normalizeMimeTypeForCKEditor()`) for a VS Code+ * language ID, or `null` if Trilium has no MIME type for it.+ */+export function codeBlockLanguage(mode: string): string | null {+ const mime = VSCODE_LANGUAGE_MIMES[mode] ?? getMimeTypeFromMarkdownName(mode)?.mime;+ return mime ? normalizeMimeTypeForCKEditor(mime) : null;+}++/**+ * The `mode` of the {@link VSCODE_EDITOR_DATA} JSON: the language ID, or an empty string if VS Code+ * named none. `null` if the data is absent or malformed.+ */+function readVsCodeMode(editorData: string): string | null {+ if (!editorData) {+ return null;+ }++ try {+ const parsed: unknown = JSON.parse(editorData);+ if (typeof parsed !== "object" || parsed === null) {+ return null;+ }++ const mode = (parsed as { mode?: unknown }).mode;+ return typeof mode === "string" ? mode : "";+ } catch {+ return null;+ }+}++function escapeHtml(text: string) {+ return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");+}