Skip to content

Build your personal knowledge base with Trilium Notes

client/AI chat: autoformat block quotes, code blocks, lists and links in the message input field (markdown syntax)

Adorian Doran8938425c65c1
diff --git a/apps/client/src/widgets/react/CKEditor.tsx b/apps/client/src/widgets/react/CKEditor.tsx
index 391fd41a52..13d0b12eb6 100644
--- a/apps/client/src/widgets/react/CKEditor.tsx
+++ b/apps/client/src/widgets/react/CKEditor.tsx
@@ -13,14 +13,15 @@ export interface CKEditorApi {
*/
setText(text: string): void;
/**
- * Appends `text` to the end of the editor as its own block, translating embedded newlines into
- * soft breaks, then leaves two blank lines below it for visual separation with the cursor on the
- * last one, and focuses the editor. Existing content is preserved; an empty editor gets the text
- * at the top with no leading blank.
+ * Appends a `> `-prefixed markdown quote to the end of the editor as a real block-quote element
+ * (its prefixes stripped and content wrapped in a `blockQuote`, so it re-serializes to the same
+ * markdown), then places the cursor in an empty paragraph below it and focuses the editor. Existing
+ * content is preserved; an empty editor gets the quote at the top with no leading blank. Requires
+ * the `BlockQuote` plugin to be loaded on the editor instance.
*
- * @param text text to append (may contain `\n`)
+ * @param markdown a `> `-prefixed markdown blockquote (lines may be joined by `\n`)
*/
- appendBlock(text: string): void;
+ appendBlockQuote(markdown: string): void;
}
interface CKEditorOpts {
@@ -56,9 +57,12 @@ export default function CKEditor({ apiRef, currentValue, editor, config, disable
setText(text: string) {
textEditorRef.current?.setData(text);
},
- appendBlock(text: string) {
+ appendBlockQuote(markdown: string) {
const editor = textEditorRef.current;
if (!editor) return;
+ // Strip the `> ` prefixes to recover the raw content; the block-quote element re-adds
+ // them when the reply is serialized back to markdown.
+ const lines = markdown.split("\n").map((line) => line.replace(/^\s*>\s?/, ""));
editor.model.change((writer) => {
const root = editor.model.document.getRoot();
if (!root) return;
@@ -70,22 +74,21 @@ export default function CKEditor({ apiRef, currentValue, editor, config, disable
writer.remove(onlyChild);
}
- // The text block: one paragraph, its lines joined by soft breaks so the whole
- // excerpt stays a single block (a bare `writer.insert` keeps it from merging into
- // the preceding paragraph, giving the blank-line separation we want).
+ // One paragraph inside the quote, its lines joined by soft breaks so the whole
+ // excerpt stays a single contiguous blockquote.
const paragraph = writer.createElement("paragraph");
- text.split("\n").forEach((line, index) => {
+ lines.forEach((line, index) => {
if (index > 0) writer.appendElement("softBreak", paragraph);
if (line.length > 0) writer.appendText(line, paragraph);
});
- writer.insert(paragraph, writer.createPositionAt(root, "end"));
+ const quote = writer.createElement("blockQuote");
+ writer.append(paragraph, quote);
+ writer.insert(quote, writer.createPositionAt(root, "end"));
- // Two trailing empty paragraphs separate the appended block from where the user
- // types; the cursor lands on the last one.
- const blankLine = writer.createElement("paragraph");
- writer.insert(blankLine, writer.createPositionAfter(paragraph));
+ // A trailing empty paragraph below the quote holds the cursor so the user types
+ // outside (after) the quote.
const cursorParagraph = writer.createElement("paragraph");
- writer.insert(cursorParagraph, writer.createPositionAfter(blankLine));
+ writer.insert(cursorParagraph, writer.createPositionAfter(quote));
writer.setSelection(cursorParagraph, "in");
});
editor.editing.view.focus();
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
index 05f6d4bd3c..9bf0a9bfd8 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
@@ -1,6 +1,6 @@
import "./ChatInputBar.css";
-import { AttributeEditor as CKEditorAttributeEditor, type CKTextEditor, type MentionFeed } from "@triliumnext/ckeditor5";
+import { AttributeEditor as CKEditorAttributeEditor, CHAT_INPUT_PLUGINS, type CKTextEditor, type MentionFeed } from "@triliumnext/ckeditor5";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { t } from "../../../services/i18n.js";
@@ -14,6 +14,8 @@ import Dropdown from "../../react/Dropdown.js";
import { FormDropdownDivider, FormDropdownSubmenu, FormListItem, FormListToggleableItem } from "../../react/FormList.js";
import { useLegacyImperativeHandlers } from "../../react/hooks.js";
import AddProviderModal, { type LlmProviderConfig } from "../options/llm/AddProviderModal.js";
+import { insertNewBlock as insertNewBlockCommand, isSelectionInCodeBlock, outdentListItemAtStart } from "./chat_input_editing.js";
+import { editorHtmlToMarkdown } from "./chat_input_markdown.js";
import { SafeImage } from "./retry_image.js";
import { useChatAttachments } from "./useChatAttachments.js";
import type { UseLlmChatReturn } from "./useLlmChat.js";
@@ -51,36 +53,6 @@ function formatTokenCount(tokens: number): string {
return tokens.toLocaleString();
}
-/**
- * Convert CKEditor HTML into plain text suitable for an LLM prompt.
- *
- * Paragraphs and <br> become newlines. Note reference links (anchors with a
- * `#root/...` href) are rendered as markdown-style `[Title](#root/noteId)` so
- * the LLM sees both the human-readable title and the addressable note path it
- * can feed into note tools.
- */
-function htmlToPlainText(html: string): string {
- const container = document.createElement("div");
- container.innerHTML = html;
- container.querySelectorAll<HTMLAnchorElement>("a[href^='#']").forEach((a) => {
- const href = a.getAttribute("href") ?? "";
- const title = (a.textContent ?? "").trim();
- a.replaceWith(`[${title}](${href})`);
- });
- // Two-space + newline = markdown hard line break (preserves shift+Enter).
- container.querySelectorAll("br").forEach((br) => br.replaceWith(" \n"));
- // Iterate over all child nodes (not just element children) so top-level
- // text nodes — text not wrapped in a block element — aren't silently dropped.
- const parts: string[] = [];
- container.childNodes.forEach((node) => {
- const text = (node.textContent ?? "").trim();
- if (text) {
- parts.push(text);
- }
- });
- return parts.join("\n\n");
-}
-
interface ChatInputBarProps {
/** The chat hook result */
chat: UseLlmChatReturn;
@@ -148,7 +120,7 @@ export default function ChatInputBar({
// the CKEditor's imperative handle has committed by the time this effect first runs.
const registerInputEditor = chat.registerInputEditor;
useEffect(() => {
- registerInputEditor({ appendBlock: (text) => editorApiRef.current?.appendBlock(text) });
+ registerInputEditor({ appendBlockQuote: (text) => editorApiRef.current?.appendBlockQuote(text) });
return () => registerInputEditor(undefined);
}, [registerInputEditor]);
@@ -279,6 +251,8 @@ export default function ChatInputBar({
className="llm-chat-input"
editor={CKEditorAttributeEditor}
config={{
+ // Markdown autoformatting (block quotes, code fences, lists, links) without a toolbar.
+ extraPlugins: CHAT_INPUT_PLUGINS,
toolbar: { items: [] },
placeholder: t("llm_chat.placeholder"),
mention: { feeds: mentionFeeds },
@@ -286,21 +260,53 @@ export default function ChatInputBar({
language: "en"
}}
onChange={(html) => {
- chat.setInput(htmlToPlainText(html ?? ""));
+ chat.setInput(editorHtmlToMarkdown(html ?? ""));
}}
onInitialized={(editor) => {
editorInstanceRef.current = editor;
- // Enter submits, Shift+Enter falls through to ShiftEnter (soft break).
+ const insertNewBlock = () => {
+ insertNewBlockCommand(editor);
+ editor.editing.view.scrollToTheSelection();
+ };
editor.editing.view.document.on(
"enter",
(event, data) => {
- if (data.isSoft) return;
+ // Inside a code block, don't submit — let CodeBlock turn Enter/Shift+Enter
+ // into newlines, so multi-line snippets can be typed.
+ if (isSelectionInCodeBlock(editor)) return;
+ // Shift+Enter builds blocks — a new list item / paragraph, or exiting an empty
+ // list item / code-block line — so lists and blocks can be built while plain
+ // Enter submits. Normally handled by the keydown keystroke below; this is a
+ // fallback for the rare case where the keystroke doesn't cancel the event.
+ if (data.isSoft) {
+ event.stop();
+ data.preventDefault();
+ insertNewBlock();
+ return;
+ }
+ // Plain Enter submits.
event.stop();
data.preventDefault();
submitRef.current(new Event("submit"));
},
{ priority: "high" }
);
+ // Shift/Ctrl/Alt+Enter all insert a new block. Bind them on keydown via keystrokes
+ // rather than the `enter` view event: modified Enter combos don't fire that event, and
+ // — crucially for Shift+Enter — CodeBlock consumes the `enter` event in its own context
+ // (and stops it) before our handler runs, so intercepting on keydown is the only way to
+ // let Shift+Enter leave a code block from its empty last line.
+ editor.keystrokes.set("Shift+Enter", (_keyEvtData, cancel) => { cancel(); insertNewBlock(); });
+ editor.keystrokes.set("Ctrl+Enter", (_keyEvtData, cancel) => { cancel(); insertNewBlock(); });
+ editor.keystrokes.set("Alt+Enter", (_keyEvtData, cancel) => { cancel(); insertNewBlock(); });
+ // Backspace at the very start of a list item leaves the list (outdent → paragraph)
+ // instead of CKEditor's default, which merges the item into the previous one as a
+ // bullet-less continuation block — confusing in a simple chat input. The list handles
+ // this on the `delete` view event (fired from `beforeinput`), so intercepting on the
+ // earlier `keydown` and cancelling suppresses that event before the list can merge.
+ editor.keystrokes.set("Backspace", (_keyEvtData, cancel) => {
+ if (outdentListItemAtStart(editor)) cancel();
+ });
// Capture pasted images at the DOM layer so CKEditor doesn't
// try to embed them as base64 data URLs inside the editor.
// Go through `pasteHandlerRef` so this one-time registration
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_input_editing.spec.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_input_editing.spec.ts
new file mode 100644
index 0000000000..088e87c49d
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_input_editing.spec.ts
@@ -0,0 +1,161 @@
+import {
+ AttributeEditor as CKEditorAttributeEditor,
+ CHAT_INPUT_PLUGINS,
+} from "@triliumnext/ckeditor5";
+import { _getModelData, _setModelData } from "ckeditor5";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import {
+ insertNewBlock,
+ isSelectionInCodeBlock,
+ outdentListItemAtStart,
+} from "./chat_input_editing.js";
+
+// Runs the real CKEditor (our chat plugin set) under happy-dom and asserts the model, so the
+// list/code Enter behavior is verified deterministically rather than by hand in the app.
+describe("chat input editing", () => {
+ let editor: Awaited<ReturnType<typeof CKEditorAttributeEditor.create>>;
+
+ beforeAll(async () => {
+ const el = document.createElement("div");
+ document.body.appendChild(el);
+ editor = await CKEditorAttributeEditor.create(el, {
+ extraPlugins: CHAT_INPUT_PLUGINS,
+ licenseKey: "GPL",
+ });
+ });
+
+ afterAll(async () => {
+ await editor.destroy();
+ });
+
+ describe("insertNewBlock", () => {
+ it("splits a non-empty list item into a new item (so lists can be built)", () => {
+ _setModelData(
+ editor.model,
+ '<paragraph listIndent="0" listItemId="a" listType="bulleted">item[]</paragraph>',
+ );
+ insertNewBlock(editor);
+ expect(
+ (_getModelData(editor.model).match(/listItemId=/g) ?? [])
+ .length,
+ ).toBe(2);
+ });
+
+ it("leaves the list from an empty item (so the list can be exited)", () => {
+ _setModelData(
+ editor.model,
+ '<paragraph listIndent="0" listItemId="a" listType="bulleted">[]</paragraph>',
+ );
+ insertNewBlock(editor);
+ expect(_getModelData(editor.model)).not.toContain("listItemId");
+ });
+
+ it("adds a newline (soft break) inside a code block", () => {
+ _setModelData(
+ editor.model,
+ '<codeBlock language="plaintext">foo[]</codeBlock>',
+ );
+ insertNewBlock(editor);
+ const data = _getModelData(editor.model);
+ expect(data).toContain("softBreak");
+ expect(data).toContain("codeBlock");
+ });
+
+ it("keeps a single blank line in a code block instead of leaving (only exits after two)", () => {
+ _setModelData(
+ editor.model,
+ '<codeBlock language="plaintext">foo<softBreak></softBreak>[]</codeBlock>',
+ );
+ insertNewBlock(editor);
+ const data = _getModelData(editor.model);
+ // Still in the block (no paragraph created), with a second line break — so a blank line can precede more code.
+ expect(data).toContain("codeBlock");
+ expect(data).not.toContain("<paragraph>");
+ expect((data.match(/<softBreak>/g) ?? []).length).toBe(2);
+ });
+
+ it("leaves the code block after two trailing blank lines (so the fence can be exited)", () => {
+ _setModelData(
+ editor.model,
+ '<codeBlock language="plaintext">foo<softBreak></softBreak><softBreak></softBreak>[]</codeBlock>',
+ );
+ insertNewBlock(editor);
+ const data = _getModelData(editor.model);
+ // Caret ends up in a fresh paragraph after the block, which keeps its content but drops the blank lines.
+ expect(data).toContain("<paragraph>[]</paragraph>");
+ expect(data).toContain("foo</codeBlock>");
+ expect(data).not.toContain("softBreak");
+ });
+
+ it("keeps a single blank line in a quote instead of leaving (only exits after two)", () => {
+ _setModelData(
+ editor.model,
+ "<blockQuote><paragraph>quoted</paragraph><paragraph>[]</paragraph></blockQuote>",
+ );
+ insertNewBlock(editor);
+ const data = _getModelData(editor.model);
+ // Caret stays inside the quote (before the closing tag), with a second blank line added.
+ expect(data).toContain("[]</paragraph></blockQuote>");
+ expect(data).not.toContain("</blockQuote><paragraph>[]");
+ });
+
+ it("leaves a block quote after two trailing blank lines (so the quote can be exited)", () => {
+ _setModelData(
+ editor.model,
+ "<blockQuote><paragraph>quoted</paragraph><paragraph></paragraph><paragraph>[]</paragraph></blockQuote>",
+ );
+ insertNewBlock(editor);
+ const data = _getModelData(editor.model);
+ // Both empty blocks are consumed and the caret lands in a paragraph after the quote.
+ expect(data).toContain("</blockQuote><paragraph>[]</paragraph>");
+ expect(data).toContain("quoted");
+ expect(data).not.toContain("<paragraph></paragraph>");
+ });
+
+ it("splits a plain paragraph into a new paragraph", () => {
+ _setModelData(editor.model, "<paragraph>hello[]</paragraph>");
+ insertNewBlock(editor);
+ expect(
+ (_getModelData(editor.model).match(/<paragraph/g) ?? []).length,
+ ).toBe(2);
+ });
+ });
+
+ describe("isSelectionInCodeBlock", () => {
+ it("is true inside a code block and false elsewhere", () => {
+ _setModelData(
+ editor.model,
+ '<codeBlock language="plaintext">foo[]</codeBlock>',
+ );
+ expect(isSelectionInCodeBlock(editor)).toBe(true);
+ _setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ expect(isSelectionInCodeBlock(editor)).toBe(false);
+ });
+ });
+
+ describe("outdentListItemAtStart", () => {
+ it("leaves the list from the start of an item (instead of merging into the previous one)", () => {
+ _setModelData(
+ editor.model,
+ '<paragraph listIndent="0" listItemId="a" listType="bulleted">[]item</paragraph>',
+ );
+ expect(outdentListItemAtStart(editor)).toBe(true);
+ expect(_getModelData(editor.model)).not.toContain("listItemId");
+ });
+
+ it("does nothing when the caret is not at the start of the item", () => {
+ _setModelData(
+ editor.model,
+ '<paragraph listIndent="0" listItemId="a" listType="bulleted">it[]em</paragraph>',
+ );
+ expect(outdentListItemAtStart(editor)).toBe(false);
+ expect(_getModelData(editor.model)).toContain("listItemId");
+ });
+
+ it("does nothing outside a list", () => {
+ _setModelData(editor.model, "<paragraph>[]text</paragraph>");
+ expect(outdentListItemAtStart(editor)).toBe(false);
+ });
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_input_editing.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_input_editing.ts
new file mode 100644
index 0000000000..251a4c0af1
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_input_editing.ts
@@ -0,0 +1,134 @@
+import type { CKTextEditor } from "@triliumnext/ckeditor5";
+
+/** Whether the editor selection sits inside a code block (where Enter should add a newline, not submit). */
+export function isSelectionInCodeBlock(editor: CKTextEditor): boolean {
+ return (
+ editor.model.document.selection
+ .getFirstPosition()
+ ?.parent.is("element", "codeBlock") ?? false
+ );
+}
+
+/**
+ * Insert a new block, mirroring the native Enter behavior so lists and blocks can be built (and exited)
+ * while plain Enter submits. On an empty block, the gesture leaves the enclosing structure instead of
+ * adding another block — the chat routes these gestures through keydown keystrokes, which bypass the
+ * List/BlockQuote/CodeBlock handlers that would natively do this on the `enter` view event:
+ * - on an EMPTY list item → leave the list (`outdentList` → paragraph);
+ * - in a quote, after two trailing blank lines → leave the quote; otherwise add a new block;
+ * - in a code block, after two trailing blank lines → leave the block; otherwise add a newline;
+ * - otherwise → split into a new list item / paragraph (`enter`).
+ *
+ * View scrolling is left to the caller so this stays a pure model operation (and testable without layout).
+ */
+export function insertNewBlock(editor: CKTextEditor): void {
+ const block = editor.model.document.selection.getFirstPosition()?.parent;
+ const emptyListItem =
+ block?.is("element") &&
+ block.isEmpty &&
+ block.hasAttribute("listItemId");
+ if (emptyListItem && editor.commands.get("outdentList")?.isEnabled) {
+ editor.execute("outdentList");
+ return;
+ }
+ if (leaveBlockQuoteAfterBlankLines(editor)) {
+ return;
+ }
+ if (isSelectionInCodeBlock(editor)) {
+ if (!leaveCodeBlockAfterBlankLines(editor)) {
+ editor.execute("shiftEnter");
+ }
+ return;
+ }
+ editor.execute("enter");
+}
+
+/**
+ * When Backspace is pressed at the very start of a list item, leave the list (`outdentList` → paragraph)
+ * instead of CKEditor's default, which merges the item into the previous one as a bullet-less
+ * continuation block. Returns whether it acted (so the caller can stop the delete).
+ */
+export function outdentListItemAtStart(editor: CKTextEditor): boolean {
+ const selection = editor.model.document.selection;
+ const position = selection.getFirstPosition();
+ const block = position?.parent;
+ if (
+ !selection.isCollapsed ||
+ !position?.isAtStart ||
+ !block?.is("element") ||
+ !block.hasAttribute("listItemId")
+ ) {
+ return false;
+ }
+ if (!editor.commands.get("outdentList")?.isEnabled) return false;
+ editor.execute("outdentList");
+ return true;
+}
+
+/**
+ * When the caret is at the end of a code block preceded by two blank lines (two trailing line breaks),
+ * leave the block: consume those blank lines and place the caret in a fresh paragraph after the block.
+ * This matches CKEditor's native "two blank lines to end the block" (which only fires on plain Enter),
+ * so the chat's Shift/Ctrl/Alt+Enter gestures can exit the fence too — while a single blank line is kept
+ * for spacing (so a blank line can precede more code). Returns whether it left the block.
+ */
+function leaveCodeBlockAfterBlankLines(editor: CKTextEditor): boolean {
+ const selection = editor.model.document.selection;
+ if (!selection.isCollapsed) return false;
+ const position = selection.getLastPosition();
+ if (!position?.isAtEnd) return false;
+ const codeBlock = position.parent;
+ const lastBreak = position.nodeBefore;
+ const priorBreak = lastBreak?.previousSibling;
+ if (
+ !codeBlock.is("element", "codeBlock") ||
+ !lastBreak?.is("element", "softBreak") ||
+ !priorBreak?.is("element", "softBreak")
+ ) {
+ return false;
+ }
+ editor.model.change((writer) => {
+ writer.remove(
+ writer.createRange(
+ writer.createPositionBefore(priorBreak),
+ writer.createPositionAfter(lastBreak),
+ ),
+ );
+ const paragraph = writer.createElement("paragraph");
+ writer.insert(paragraph, writer.createPositionAfter(codeBlock));
+ writer.setSelection(paragraph, "in");
+ });
+ return true;
+}
+
+/**
+ * When the caret is in an empty block inside a quote whose previous sibling is also an empty block (two
+ * trailing blank lines), leave the quote: consume both blank lines and place the caret in a paragraph
+ * after the quote. Mirrors the code-block rule so a single blank line can be kept for spacing. Returns
+ * whether it left the quote.
+ */
+function leaveBlockQuoteAfterBlankLines(editor: CKTextEditor): boolean {
+ const selection = editor.model.document.selection;
+ if (!selection.isCollapsed || !editor.commands.get("blockQuote")?.value)
+ return false;
+ const block = selection.getFirstPosition()?.parent;
+ if (!block?.is("element") || !block.isEmpty) return false;
+ const prevBlock = block.previousSibling;
+ const quote = block.parent;
+ if (
+ !prevBlock?.is("element") ||
+ !prevBlock.isEmpty ||
+ !quote?.is("element", "blockQuote")
+ ) {
+ return false;
+ }
+ editor.model.change((writer) => {
+ writer.remove(prevBlock);
+ writer.remove(block);
+ const paragraph = writer.createElement("paragraph");
+ writer.insert(paragraph, writer.createPositionAfter(quote));
+ writer.setSelection(paragraph, "in");
+ if (quote.isEmpty) writer.remove(quote);
+ });
+ return true;
+}
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_input_markdown.spec.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_input_markdown.spec.ts
new file mode 100644
index 0000000000..a5926bfb73
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_input_markdown.spec.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from "vitest";
+
+import { editorHtmlToMarkdown } from "./chat_input_markdown.js";
+
+describe("editorHtmlToMarkdown", () => {
+ it("passes plain paragraphs through, separated by blank lines", () => {
+ expect(editorHtmlToMarkdown("<p>hello</p>")).toBe("hello");
+ expect(editorHtmlToMarkdown("<p>a</p><p>b</p>")).toBe("a\n\nb");
+ });
+
+ it("renders <br> as a markdown hard line break", () => {
+ expect(editorHtmlToMarkdown("<p>a<br>b</p>")).toBe("a \nb");
+ });
+
+ it("renders links as markdown, keeping note-reference hrefs", () => {
+ expect(editorHtmlToMarkdown('<p><a href="#root/abc123">My note</a></p>')).toBe("[My note](#root/abc123)");
+ expect(editorHtmlToMarkdown('<p>see <a href="https://example.com">the site</a></p>'))
+ .toBe("see [the site](https://example.com)");
+ // A bare auto-linked URL (text === href) stays a plain URL.
+ expect(editorHtmlToMarkdown('<p><a href="https://example.com">https://example.com</a></p>'))
+ .toBe("https://example.com");
+ });
+
+ it("renders block quotes with `> ` prefixes, blanking empty quote lines", () => {
+ expect(editorHtmlToMarkdown("<blockquote><p>quoted</p></blockquote>")).toBe("> quoted");
+ expect(editorHtmlToMarkdown("<blockquote><p>a</p><p>b</p></blockquote>")).toBe("> a\n>\n> b");
+ });
+
+ it("keeps hard breaks between quote lines so the attribution stays on its own line", () => {
+ // <br> lines (as the quote-reply feature inserts) keep their ` ` markdown hard break, so
+ // multi-line quotes and the trailing "Show quote source" attribution don't collapse.
+ const hb = " "; // markdown hard break (two trailing spaces)
+ expect(editorHtmlToMarkdown("<blockquote><p>first<br>second<br>(Quoted from &lt;&lt;mid:abc&gt;&gt;)</p></blockquote>"))
+ .toBe(`> first${hb}\n> second${hb}\n> (Quoted from <<mid:abc>>)`);
+ });
+
+ it("renders code blocks as fenced blocks, keeping the language", () => {
+ expect(editorHtmlToMarkdown('<pre><code class="language-python">print(1)</code></pre>'))
+ .toBe("```python\nprint(1)\n```");
+ expect(editorHtmlToMarkdown("<pre><code>plain</code></pre>")).toBe("```\nplain\n```");
+ });
+
+ it("renders bulleted and numbered lists", () => {
+ expect(editorHtmlToMarkdown("<ul><li>a</li><li>b</li></ul>")).toBe("- a\n- b");
+ expect(editorHtmlToMarkdown("<ol><li>a</li><li>b</li></ol>")).toBe("1. a\n2. b");
+ });
+
+ it("indents nested lists", () => {
+ expect(editorHtmlToMarkdown("<ul><li>a<ul><li>b</li></ul></li></ul>")).toBe("- a\n - b");
+ });
+
+ it("returns an empty string for empty content", () => {
+ expect(editorHtmlToMarkdown("<p><br></p>")).toBe("");
+ expect(editorHtmlToMarkdown("")).toBe("");
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_input_markdown.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_input_markdown.ts
new file mode 100644
index 0000000000..3ebfad0ae9
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_input_markdown.ts
@@ -0,0 +1,97 @@
+/**
+ * Serialize the AI chat reply input's CKEditor HTML into markdown for the LLM.
+ *
+ * The reply input enables autoformatting for block quotes, fenced code blocks, lists and links (see
+ * `CHAT_INPUT_PLUGINS`); this turns the resulting elements into their markdown equivalents. Note
+ * reference links keep their `#root/noteId` href so the model can feed them to note tools, and literal
+ * text is passed through **unescaped**, so markdown a user types by hand survives too. Anything not
+ * explicitly handled falls back to its text content, so unknown/pasted formatting degrades gracefully.
+ */
+export function editorHtmlToMarkdown(html: string): string {
+ const container = document.createElement("div");
+ container.innerHTML = html;
+ return serializeChildren(container)
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+}
+
+function serializeChildren(node: Node): string {
+ return Array.from(node.childNodes).map(serializeNode).join("");
+}
+
+function serializeNode(node: Node): string {
+ if (node.nodeType === Node.TEXT_NODE) {
+ return node.textContent ?? "";
+ }
+ if (node.nodeType !== Node.ELEMENT_NODE) {
+ return "";
+ }
+
+ const el = node as HTMLElement;
+ switch (el.tagName.toLowerCase()) {
+ // Two-space + newline = markdown hard line break, preserving Shift+Enter breaks.
+ case "br":
+ return " \n";
+ case "a": {
+ const href = el.getAttribute("href") ?? "";
+ const text = serializeChildren(el).trim();
+ if (!href) return text;
+ // A bare auto-linked URL (text === href) stays a plain URL rather than `[url](url)`.
+ return text === href ? href : `[${text}](${href})`;
+ }
+ case "p":
+ return `${serializeChildren(el)}\n\n`;
+ case "blockquote": {
+ const inner = serializeChildren(el).trim();
+ // Keep each line's trailing ` ` hard break so multi-line quotes — and the trailing
+ // "Show quote source" attribution — render on their own lines instead of collapsing.
+ const quoted = inner.split("\n").map((line) => (line ? `> ${line}` : ">")).join("\n");
+ return `${quoted}\n\n`;
+ }
+ case "pre":
+ return serializeCodeBlock(el);
+ case "ul":
+ return `${serializeList(el, false, 0)}\n`;
+ case "ol":
+ return `${serializeList(el, true, 0)}\n`;
+ default:
+ // Inline wrappers (span, strong, em, …) — keep their text/children.
+ return serializeChildren(el);
+ }
+}
+
+/** A `<pre><code class="language-x">` block → a fenced code block, preserving the language and newlines. */
+function serializeCodeBlock(pre: HTMLElement): string {
+ const codeEl = pre.querySelector("code") ?? pre;
+ const language = codeEl.className.match(/language-(\S+)/)?.[1] ?? "";
+ // Code lines are separated by <br> in the data view; turn them back into real newlines.
+ const clone = codeEl.cloneNode(true) as HTMLElement;
+ clone.querySelectorAll("br").forEach((br) => br.replaceWith("\n"));
+ const code = (clone.textContent ?? "").replace(/\n+$/, "");
+ const fence = "```";
+ return `${fence}${language}\n${code}\n${fence}\n\n`;
+}
+
+/** A `<ul>`/`<ol>` → markdown list markers, recursing into nested lists with two-space indentation. */
+function serializeList(listEl: HTMLElement, ordered: boolean, depth: number): string {
+ const indent = " ".repeat(depth);
+ let out = "";
+ let index = 1;
+ for (const item of Array.from(listEl.children)) {
+ if (item.tagName.toLowerCase() !== "li") continue;
+ const marker = ordered ? `${index++}.` : "-";
+
+ let text = "";
+ let nested = "";
+ for (const child of Array.from(item.childNodes)) {
+ const tag = child.nodeType === Node.ELEMENT_NODE ? (child as HTMLElement).tagName.toLowerCase() : "";
+ if (tag === "ul" || tag === "ol") {
+ nested += serializeList(child as HTMLElement, tag === "ol", depth + 1);
+ } else {
+ text += serializeNode(child);
+ }
+ }
+ out += `${indent}${marker} ${text.trim()}\n${nested}`;
+ }
+ return out;
+}
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
index a1fa4c456d..f746504d7d 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
@@ -15,7 +15,7 @@ export type AttachmentBlock = ImageBlock | FileBlock | TextFileBlock;
/** The subset of the reply-input editor API the chat needs to write into it imperatively. */
export interface InputEditorApi {
- appendBlock(text: string): void;
+ appendBlockQuote(markdown: string): void;
}
/** Distance (px) past the content bottom edge within which the timeline counts as "at bottom". */
@@ -241,7 +241,7 @@ export function useLlmChat(
inputEditorRef.current = api;
}, []);
const appendToInput = useCallback((text: string) => {
- inputEditorRef.current?.appendBlock(text);
+ inputEditorRef.current?.appendBlockQuote(text);
}, []);
const addPendingAttachment = useCallback((attachment: AttachmentBlock) => {
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index ca51d92d7b..5b9ae768f6 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -6,7 +6,7 @@ import { COMMON_PLUGINS, CORE_PLUGINS, POPUP_EDITOR_PLUGINS } from "./plugins.js
import { BalloonEditor, DecoupledEditor, FindAndReplaceEditing, FindCommand } from "ckeditor5";
import "./translation_overrides.js";
export { default as EditorWatchdog } from "./custom_watchdog";
-export { loadPremiumPlugins } from "./plugins.js";
+export { CHAT_INPUT_PLUGINS, loadPremiumPlugins } from "./plugins.js";
export type { EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, WatchdogConfig, WatchdogState } from "ckeditor5";
export type { TemplateDefinition } from "ckeditor5-premium-features";
export { default as buildExtraCommands } from "./extra_slash_commands.js";
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index f7873782b2..dbc14cb846 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -110,6 +110,21 @@ export const CORE_PLUGINS: typeof Plugin[] = [
ReferenceLink
];
+/**
+ * Lightweight formatting plugins for a minimal reply input (e.g. the AI chat) — added on top of an
+ * {@link AttributeEditor} instance via `extraPlugins` to enable markdown **autoformatting** for block
+ * quotes, fenced code blocks, lists and links, without a toolbar. Kept out of {@link CORE_PLUGINS} so
+ * the plain attribute/relation editor stays plain.
+ */
+export const CHAT_INPUT_PLUGINS: typeof Plugin[] = [
+ Autoformat,
+ BlockQuote,
+ CodeBlock,
+ List,
+ Link,
+ AutoLink
+];
+
/**
* Dynamically loads plugins that require a premium CKEditor license key.
* This avoids loading ~6 seconds of premium features code during initial app startup.