@devries-cameron20 / t3code-1 / commits / af54fe2344
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web): make styled composer Markdown markers editable (#30421)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Elliot Drel <elliotdrel@gmail.com>

shivam committed Nov 5, 2026 at 06:52 UTC af54fe23442617c7269d3447d84d2b1241a02692
8 files changed +1181 -197
apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx
+395 -41
@@ -9,13 +9,15 @@ import {
9
10 import type { ServerProviderSkill } from "@t3tools/contracts";
11 import type { Editor } from "@tiptap/core";
12 +import { redoDepth, undoDepth } from "@tiptap/pm/history";
13 +import { NodeSelection } from "@tiptap/pm/state";
14 import { createElement, createRef, useEffect, useState } from "react";
15 import { describe, expect, it, vi } from "vite-plus/test";
16 import { userEvent } from "vite-plus/test/browser";
17
18 import { act, fakeTimers, render } from "../../test/render";
19
18 -import { serializeEditorDoc } from "~/composer-rich-text-doc";
20 +import { flatToMarkdown, pmToFlat, serializeEditorDoc } from "~/composer-rich-text-doc";
21 import { isMacPlatform } from "~/lib/utils";
22 import {
23 ComposerPromptEditorTiptap as ComposerPromptEditor,
@@ -149,24 +151,67 @@ it.each([
151 expect(textWithMark(editor, "code")).toEqual(code);
152 });
153
152 -it("bolds with Mod+B only when text is selected", async () => {
153 - await using screen = await mountEditor("ship it");
154 - const { editor } = screen;
155 - const modB = isMacPlatform(navigator.platform) ? "{Meta>}b{/Meta}" : "{Control>}b{/Control}";
156 - await act(async () => {
157 - editor.commands.focus("end");
158 - });
159 - await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom));
160 - await userEvent.keyboard(modB);
161 - // Without the guard, Tiptap stores bold for the next typed text.
162 - expect(editor.state.storedMarks).toBeNull();
154 +it.each([
155 + { word: "ship", prefix: "", source: ["**ship**"] },
156 + { word: "path\\", prefix: "", source: [] },
157 + { word: "2*3", prefix: "", source: [] },
158 + { word: "b", prefix: "*", source: [] },
159 + { word: "word", prefix: "\\\\*", source: [] },
160 + { word: "word", prefix: "\\\\**", source: [] },
161 + { word: "word", prefix: "\\", source: [] },
162 + { word: "word", prefix: "\\\\", source: ["**word**"] },
163 + { word: "word", prefix: "\\\\\\", source: [] },
164 + {
165 + word: "word",
166 + prefix: "`path\\`",
167 + prefixText: "path\\",
168 + source: ["**word**"],
169 + code: ["path\\"],
170 + },
171 +])(
172 + "bolds $word after '$prefix' with Mod+B only when text is selected",
173 + async ({ word, prefix, prefixText = prefix, source, code = [] }) => {
174 + const value = `${prefix}${word} it`;
175 + await using screen = await mountEditor(value);
176 + const { editor } = screen;
177 + const modB = isMacPlatform(navigator.platform) ? "{Meta>}b{/Meta}" : "{Control>}b{/Control}";
178 + await act(async () => {
179 + editor.commands.focus("end");
180 + });
181 + await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom));
182 + await userEvent.keyboard(modB);
183 + // Without the guard, Tiptap stores bold for the next typed text.
184 + expect(editor.state.storedMarks).toBeNull();
185
164 - await act(async () => {
165 - editor.commands.setTextSelection({ from: 1, to: 5 });
166 - });
167 - await userEvent.keyboard(modB);
168 - await vi.waitFor(() => expect(textWithMark(editor, "bold")).toEqual(["ship"]));
169 -});
186 + await act(async () => {
187 + editor.commands.setTextSelection({
188 + from: prefixText.length + 1,
189 + to: prefixText.length + word.length + 1,
190 + });
191 + });
192 + await userEvent.keyboard(modB);
193 + await vi.waitFor(() =>
194 + expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}**${word}** it`),
195 + );
196 + expect(textWithMark(editor, "markdownSource")).toEqual(source);
197 + const depth = undoDepth(editor.state);
198 + await userEvent.keyboard("{End}");
199 + expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}**${word}** it`);
200 + expect(textWithMark(editor, "bold")).toEqual([word]);
201 + expect(textWithMark(editor, "code")).toEqual(code);
202 + expect(undoDepth(editor.state)).toBe(depth);
203 + await act(async () => {
204 + editor.commands.setTextSelection({
205 + from: prefixText.length + 1,
206 + to: prefixText.length + word.length + 1,
207 + });
208 + });
209 +
210 + // Whether the selection spans shown markers or not, Mod+B removes the bold.
211 + await userEvent.keyboard(modB);
212 + await vi.waitFor(() => expect(serializeEditorDoc(editor.state.doc).value).toBe(value));
213 + },
214 +);
215
216 it.each([false, true])(
217 "composes an umlaut without wrapping the preedit text (rich text: %s)",
@@ -199,6 +244,62 @@ it("lets composition replace selected text without surrounding it", async () =>
244 expect(serializeEditorDoc(editor.state.doc).value).toBe('"');
245 });
246
247 +it.each([
248 + { at: "inside bold", selection: 5, composed: "**bo漢ld** after", bold: ["bo漢ld"] },
249 + {
250 + at: "over the opening markers",
251 + selection: { from: 1, to: 3 },
252 + composed: "漢bold** after",
253 + bold: [],
254 + },
255 + { at: "after the closing markers", selection: 9, composed: "**bold**漢 after", bold: ["bold"] },
256 +])("undoes composition $at in revealed Markdown through the earlier paste", async (row) => {
257 + await using screen = await mountEditor("");
258 + const { editor } = screen;
259 + const value = () => serializeEditorDoc(editor.state.doc).value;
260 + await act(async () => {
261 + editor.view.focus();
262 + const clipboardData = new DataTransfer();
263 + clipboardData.setData("text/plain", "**bold** after");
264 + editor.view.dom.dispatchEvent(new ClipboardEvent("paste", { clipboardData, cancelable: true }));
265 + editor.commands.insertContent("!");
266 + editor.commands.undo();
267 + editor.commands.setTextSelection(3);
268 + });
269 + expect(value()).toBe("**bold** after");
270 + expect(textWithMark(editor, "markdownSource")).toEqual(["**bold**"]);
271 + await act(async () => {
272 + editor.commands.setTextSelection(row.selection);
273 + // A composition canceled before it edits anything keeps the redo and adds no undo.
274 + editor.view.dom.dispatchEvent(new CompositionEvent("compositionstart"));
275 + editor.view.dom.dispatchEvent(new CompositionEvent("compositionend", { data: "" }));
276 + });
277 + expect([undoDepth(editor.state), redoDepth(editor.state)]).toEqual([1, 1]);
278 + await act(async () => {
279 + editor.view.dom.dispatchEvent(new CompositionEvent("compositionstart"));
280 + // ProseMirror numbers each composition; the canceled one was 1.
281 + editor.view.dispatch(editor.state.tr.insertText("漢").setMeta("composition", 2));
282 + editor.view.dom.dispatchEvent(new CompositionEvent("compositionend", { data: "漢" }));
283 + editor.commands.setTextSelection(editor.state.doc.content.size - 1);
284 + });
285 + expect(value()).toBe(row.composed);
286 + await act(async () => {
287 + editor.commands.undo();
288 + });
289 + expect(value()).toBe("**bold** after");
290 + await act(async () => {
291 + editor.commands.undo();
292 + });
293 + expect(value()).toBe("");
294 + await act(async () => {
295 + editor.commands.redo();
296 + editor.commands.redo();
297 + editor.commands.setTextSelection(editor.state.doc.content.size - 1);
298 + });
299 + expect(value()).toBe(row.composed);
300 + expect(textWithMark(editor, "bold")).toEqual(row.bold);
301 +});
302 +
303 it("keeps unknown dollar names editable when restoring and pasting a draft", async () => {
304 const value = "echo $HOME $PATH $anything $notaskill $20 $20k $babysit ";
305 await using screen = await mountEditor(value, true, [babysit]);
@@ -239,6 +340,256 @@ it("keeps the caret inside unknown dollar text across rich and plain remounts",
340 expect(serializeEditorDoc(editor.state.doc).value).toBe("echo $HOXYME now");
341 });
342
343 +async function focusAt(editor: Editor, position: number | "end") {
344 + // ProseMirror rewrites the DOM caret 20ms after focus. Run that now, or it
345 + // can undo the first key before ProseMirror reads the native move.
346 + using _timers = fakeTimers();
347 + await act(async () => {
348 + editor.commands.focus(position);
349 + });
350 + await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom));
351 + vi.runOnlyPendingTimers();
352 +}
353 +
354 +describe("Markdown markers around styled text", () => {
355 + it.each([
356 + { keys: "{Backspace}", expected: "**** after" },
357 + { keys: "X", expected: "**X** after" },
358 + ])("keeps a styled chip selected for $keys when showing source", async ({ keys, expected }) => {
359 + await using screen = await mountEditor("$babysit after", true, [babysit]);
360 + const { editor } = screen;
361 + await focusAt(editor, "end");
362 + await act(async () => {
363 + editor.view.dispatch(editor.state.tr.addMark(1, 2, editor.schema.marks.bold!.create()));
364 + });
365 + expect(editor.state.doc.nodeAt(1)?.type.name).toBe("composer-skill");
366 + await act(async () => {
367 + editor.commands.setNodeSelection(1);
368 + });
369 + expect(editor.state.selection).toBeInstanceOf(NodeSelection);
370 + expect((editor.state.selection as NodeSelection).node.type.name).toBe("composer-skill");
371 + await userEvent.keyboard(keys);
372 + await userEvent.keyboard("{End}");
373 + await vi.waitFor(() => expect(serializeEditorDoc(editor.state.doc).value).toBe(expected));
374 + });
375 +
376 + it.each([
377 + {
378 + name: "deleting the opening markers removes bold",
379 + value: "**bold** after",
380 + caret: 1,
381 + keys: "{Delete}{Delete}",
382 + expected: "bold** after",
383 + marks: {},
384 + },
385 + {
386 + name: "turning ** into * makes it italic",
387 + value: "**bold** after",
388 + caret: 1,
389 + keys: "{Delete}{ArrowRight}{ArrowRight}{ArrowRight}{ArrowRight}{ArrowRight}{Delete}",
390 + expected: "*bold* after",
391 + marks: { italic: ["bold"] },
392 + },
393 + {
394 + name: "backspacing from the closing edge keeps italic",
395 + value: "**bold** after",
396 + caret: 1,
397 + keys: async (editor: Editor) => {
398 + await userEvent.keyboard("{Delete}");
399 + await vi.waitFor(() => expect(editor.state.doc.textContent).toBe("*bold** after"));
400 + for (let position = 2; position <= 8; position += 1) {
401 + await userEvent.keyboard("{ArrowRight}");
402 + await vi.waitFor(() => expect(editor.state.selection.from).toBe(position));
403 + }
404 + await userEvent.keyboard("{Backspace}");
405 + await vi.waitFor(() =>
406 + expect(serializeEditorDoc(editor.state.doc).value).toBe("*bold* after"),
407 + );
408 + },
409 + expected: "*bold* after",
410 + marks: { italic: ["bold"] },
411 + },
412 + {
413 + name: "retyping deleted closing markers restores bold",
414 + value: "**bold** after",
415 + caret: 3,
416 + keys: "{ArrowRight}{ArrowRight}{Delete}{Delete}**",
417 + expected: "**bold** after",
418 + marks: { bold: ["bold"] },
419 + },
420 + {
421 + name: "deleting a backtick removes inline code",
422 + value: "`code` after",
423 + caret: 1,
424 + keys: "{Delete}",
425 + expected: "code` after",
426 + marks: {},
427 + },
428 + {
429 + name: "a line break inside bold keeps both halves bold",
430 + value: "**bold** after",
431 + caret: 3,
432 + keys: "{Shift>}{Enter}{/Shift}",
433 + expected: "**bo**\n**ld** after",
434 + marks: { bold: ["bo", "ld"] },
435 + },
436 + {
437 + name: "splitting a list item inside bold keeps both halves bold",
438 + value: "- **bold** after",
439 + caret: 5,
440 + keys: "{Enter}",
441 + expected: "- **bo**\n- **ld** after",
442 + marks: { bold: ["bo", "ld"] },
443 + },
444 + ])("edits the markers as text: $name", async ({ value, caret, keys, expected, marks }) => {
445 + await using screen = await mountEditor(value);
446 + const { editor } = screen;
447 + // Position 1 is the start of the styled word; 3 is two characters into it (5 in a list item).
448 + await focusAt(editor, caret);
449 + if (typeof keys === "string") await userEvent.keyboard(keys);
450 + else await keys(editor);
451 + await userEvent.keyboard("{End}");
452 + await vi.waitFor(() => expect(serializeEditorDoc(editor.state.doc).value).toBe(expected));
453 + for (const name of ["bold", "italic", "code"] as const) {
454 + expect(textWithMark(editor, name)).toEqual(marks[name as keyof typeof marks] ?? []);
455 + }
456 + });
457 +
458 + it("shows nested formatting as Markdown and restores it when the caret leaves", async () => {
459 + const value = "**a *b* c** d";
460 + await using screen = await mountEditor(value);
461 + const { editor } = screen;
462 + await focusAt(editor, "a b".length + 1);
463 + expect(editor.state.doc.textContent).toBe(value);
464 + expect(textWithMark(editor, "bold")).toEqual([]);
465 + await userEvent.keyboard("{End}");
466 + await vi.waitFor(() => expect(editor.state.doc.textContent).toBe("a b c d"));
467 + expect(textWithMark(editor, "bold")).toEqual(["a ", "b", " c"]);
468 + expect(textWithMark(editor, "italic")).toEqual(["b"]);
469 + expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
470 + });
471 +
472 + it("undoes a marker edit in one step without an extra step for showing markers", async () => {
473 + await using screen = await mountEditor("**bold** after");
474 + const { editor } = screen;
475 + await focusAt(editor, "end");
476 + await userEvent.keyboard("!");
477 + await act(async () => {
478 + editor.commands.setTextSelection(1);
479 + });
480 + await userEvent.keyboard("{Delete}{Delete}{End}");
481 + const value = () => serializeEditorDoc(editor.state.doc).value;
482 + await vi.waitFor(() => expect(value()).toBe("bold** after!"));
483 + await act(async () => {
484 + editor.commands.undo();
485 + });
486 + expect(value()).toBe("**bold** after!");
487 + expect(textWithMark(editor, "markdownSource")).toEqual(["**bold**"]);
488 + const end = () => editor.state.doc.content.size - 1;
489 + // Undo restored the markers as text; leaving hides them without touching the text undo needs.
490 + await act(async () => {
491 + editor.commands.setTextSelection(end());
492 + });
493 + expect(value()).toBe("**bold** after!");
494 + const hidden = editor.view.dom.querySelectorAll(".composer-rich-marker-hidden");
495 + expect(Array.from(hidden, (marker) => marker.textContent)).toEqual(["**", "**"]);
496 + await act(async () => {
497 + editor.commands.undo();
498 + });
499 + expect(value()).toBe("**bold** after");
500 + // Moving the caret into styled text keeps redo, and adds no undo step after it.
501 + await act(async () => {
502 + editor.commands.setTextSelection(3);
503 + });
504 + expect(editor.state.doc.textContent).toBe("**bold** after");
505 + expect(textWithMark(editor, "markdownSource")).toEqual(["**bold**"]);
506 + await act(async () => {
507 + editor.commands.redo();
508 + });
509 + expect(value()).toBe("**bold** after!");
510 + await act(async () => {
511 + editor.commands.setTextSelection(1);
512 + });
513 + await act(async () => {
514 + editor.commands.redo();
515 + });
516 + expect(value()).toBe("bold** after!");
517 + expect(textWithMark(editor, "bold")).toEqual([]);
518 + await act(async () => {
519 + editor.commands.undo();
520 + editor.commands.undo();
521 + });
522 + await act(async () => {
523 + editor.commands.redo();
524 + });
525 + await act(async () => {
526 + editor.commands.setTextSelection(editor.state.doc.content.size - 1);
527 + });
528 + await act(async () => {
529 + editor.commands.undo();
530 + });
531 + // Undo puts the caret back inside the styled text.
532 + expect(editor.state.doc.textContent).toBe("**bold** after");
533 + await act(async () => {
534 + editor.commands.setTextSelection(end());
535 + });
536 + expect(editor.state.doc.textContent).toBe("bold after");
537 + expect(textWithMark(editor, "bold")).toEqual(["bold"]);
538 + // After a completed redo, markers still follow the caret, and Delete edits the opening one.
539 + await userEvent.keyboard("?");
540 + await act(async () => {
541 + editor.commands.undo();
542 + });
543 + await act(async () => {
544 + editor.commands.redo();
545 + });
546 + expect(editor.state.doc.textContent).toBe("bold after?");
547 + await act(async () => {
548 + editor.commands.setTextSelection(1);
549 + });
550 + expect(editor.state.doc.textContent).toBe("**bold** after?");
551 + expect(textWithMark(editor, "markdownSource")).toEqual(["**bold**"]);
552 + await act(async () => {
553 + editor.commands.setTextSelection(end());
554 + });
555 + expect(editor.state.doc.textContent).toBe("bold after?");
556 + expect(textWithMark(editor, "bold")).toEqual(["bold"]);
557 + await act(async () => {
558 + editor.commands.setTextSelection(1);
559 + });
560 + await userEvent.keyboard("{Delete}");
561 + expect(value()).toBe("*bold** after?");
562 + await act(async () => {
563 + editor.commands.undo();
564 + });
565 + expect(value()).toBe("**bold** after?");
566 + expect(textWithMark(editor, "markdownSource")).toEqual(["**bold**"]);
567 + await act(async () => {
568 + editor.commands.setTextSelection(end());
569 + });
570 + expect(editor.state.doc.textContent).toBe("bold after?");
571 + expect(textWithMark(editor, "bold")).toEqual(["bold"]);
572 + });
573 +
574 + it("keeps bold around a skill pasted inside it", async () => {
575 + await using screen = await mountEditor("**helloworld** after", true, [babysit]);
576 + const { editor } = screen;
577 + await focusAt(editor, "hello".length + 1);
578 + await act(async () => {
579 + const clipboardData = new DataTransfer();
580 + clipboardData.setData("text/plain", "$babysit");
581 + editor.view.dom.dispatchEvent(
582 + new ClipboardEvent("paste", { clipboardData, cancelable: true }),
583 + );
584 + });
585 + await userEvent.keyboard("{End}");
586 + await vi.waitFor(() =>
587 + expect(serializeEditorDoc(editor.state.doc).value).toBe("**hello** $babysit **world** after"),
588 + );
589 + expect(textWithMark(editor, "bold")).toEqual(["hello", "world"]);
590 + });
591 +});
592 +
593 const file = {
594 type: "file",
595 id: "file-1",
@@ -386,26 +737,26 @@ describe("an Arabic line", () => {
737 vi.runOnlyPendingTimers();
738 }
739
389 - it("leaves inline code through its start with ArrowRight, which points back", async () => {
390 - // Positions: اكتب at 1-5, sumBy at 6-11, الان at 12-16.
391 - await using screen = await mountEditor("اكتب `sumBy` الان");
740 + it("walks back through inline code and its backticks with ArrowRight", async () => {
741 + const value = "اكتب `sumBy` الان";
742 + await using screen = await mountEditor(value);
743 const { editor } = screen;
744 await focusEnd(editor);
394 - const caret = () => ({
395 - head: editor.state.selection.head,
396 - inCode: (editor.state.storedMarks ?? editor.state.selection.$head.marks()).length > 0,
397 - });
398 - const visited = [caret()];
399 - while (visited.at(-1)!.head > 5) {
745 + const offset = () => {
746 + const map = serializeEditorDoc(editor.state.doc);
747 + return flatToMarkdown(map, pmToFlat(map, editor.state.selection.head));
748 + };
749 + const visited = [offset()];
750 + let sawSource = false;
751 + while (visited.at(-1)! > "اكتب".length) {
752 const before = visited.at(-1)!;
753 await userEvent.keyboard("{ArrowRight}");
402 - await vi.waitFor(() => {
403 - const after = caret();
404 - expect(after.head < before.head || after.inCode !== before.inCode).toBe(true);
405 - });
406 - visited.push(caret());
754 + await vi.waitFor(() => expect(offset()).toBe(before - 1));
755 + sawSource ||= editor.state.doc.textContent === value;
756 + visited.push(offset());
757 }
408 - expect(visited.some((stop) => stop.inCode)).toBe(true);
758 + expect(sawSource).toBe(true);
759 + expect(textWithMark(editor, "code")).toEqual(["sumBy"]);
760 });
761
762 it("shows the backticks on either side of inline code it is editing", async () => {
@@ -415,14 +766,17 @@ describe("an Arabic line", () => {
766 editor.commands.setTextSelection("اكتب su".length + 1);
767 });
768 const code = editor.view.dom.querySelector("code")!;
418 - const word = document.createRange();
419 - word.selectNodeContents([...code.childNodes].find((node) => node instanceof Text)!);
420 - const text = word.getBoundingClientRect();
421 - const [open, close] = [...editor.view.dom.querySelectorAll(".composer-rich-marker")].map(
422 - (marker) => marker.getBoundingClientRect(),
423 - );
424 - expect(open!.right).toBeLessThanOrEqual(text.left + 1);
425 - expect(close!.left).toBeGreaterThanOrEqual(text.right - 1);
769 + const text = [...code.childNodes].find((node) => node instanceof Text)!;
770 + expect(text.data).toBe("`sumBy`");
771 + const rect = (from: number, to: number) => {
772 + const range = document.createRange();
773 + range.setStart(text, from);
774 + range.setEnd(text, to);
775 + return range.getBoundingClientRect();
776 + };
777 + const [open, word, close] = [rect(0, 1), rect(1, 6), rect(6, 7)];
778 + expect(open.right).toBeLessThanOrEqual(word.left + 1);
779 + expect(close.left).toBeGreaterThanOrEqual(word.right - 1);
780 });
781
782 it("starts the next line on the right", async () => {
apps/web/src/components/ComposerPromptEditorTiptap.tsx
+81 -110
@@ -12,7 +12,6 @@ import {
12 } from "@tiptap/core";
13 import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tiptap/react";
14 import StarterKit from "@tiptap/starter-kit";
15 -import { type Node as ProseMirrorNode } from "@tiptap/pm/model";
15 import { newlineInCode, splitBlockKeepMarks } from "@tiptap/pm/commands";
16 import { isHistoryTransaction } from "@tiptap/pm/history";
17 import {
@@ -59,6 +58,11 @@ import {
58 } from "~/composer-logic";
59 import { useStableCallback } from "~/hooks/useStableCallback";
60 import { caretLineDirection, ComposerTextDirectionExtension } from "~/composer-text-direction";
61 +import {
62 + collapseShownMarkdownSource,
63 + ComposerMarkdownSourceExtension,
64 +} from "~/composer-markdown-source";
65 +import { MARKDOWN_SOURCE_MARK } from "~/composer-rich-text";
66 import {
67 collectComposerPromptInlineTokens,
68 selectionTouchesMentionBoundary,
@@ -69,7 +73,6 @@ import {
73 ComposerCodeBlockExtension,
74 ComposerListExtensions,
75 buildTiptapContent,
72 - caretTakesMarksBefore,
76 ComposerBoldSelectionOnlyExtension,
77 convertBulletItemToTask,
78 ComposerCodeExtension,
@@ -524,46 +527,6 @@ function ComposerContextReferenceNodeView({ node }: NodeViewProps) {
527 );
528 }
529
527 -type StyledRange = {
528 - from: number;
529 - to: number;
530 - markers: { at: number; side: number; text: string }[];
531 -};
532 -
533 -function collectStyledRanges(doc: ProseMirrorNode): StyledRange[] {
534 - const ranges: StyledRange[] = [];
535 - const map = serializeEditorDoc(doc);
536 - let range: StyledRange | null = null;
537 - let openLength = 0;
538 - for (const run of map.runs) {
539 - if (run.nodeName === "codeBlock") continue;
540 - if (run.openLen > 0) {
541 - range ??= { from: run.pmPos, to: run.pmPos, markers: [] };
542 - range.markers.push({
543 - at: run.pmPos,
544 - side: -1,
545 - text: map.value.slice(run.mdStart, run.mdStart + run.openLen),
546 - });
547 - }
548 - if (range === null) continue;
549 - range.to = run.pmPos + run.docLen;
550 - if (run.closeLen > 0) {
551 - const end = run.mdStart + run.mdLen;
552 - range.markers.push({
553 - at: range.to,
554 - side: -2,
555 - text: map.value.slice(end - run.closeLen, end),
556 - });
557 - }
558 - openLength += run.openLen - run.closeLen;
559 - if (openLength === 0) {
560 - ranges.push(range);
561 - range = null;
562 - }
563 - }
564 - return ranges;
565 -}
566 -
530 /** Wait for a character after '- ' so task markers reach their input rule before becoming bullets. */
531 function listMarkerInputRule(find: RegExp, listType: "bulletList" | "orderedList"): InputRule {
532 return new InputRule({
@@ -684,75 +647,41 @@ function isInCodeBlock(view: EditorView): boolean {
647 return view.state.selection.$from.parent.type.spec.code === true;
648 }
649
687 -const MarkerPluginKey = new PluginKey("composer-rich-markers");
650 +const ChipSelectionPluginKey = new PluginKey<DecorationSet>("composer-chip-range-selection");
651
689 -const ComposerMarkerPlugin = new Plugin({
690 - key: MarkerPluginKey,
691 - state: {
692 - init: (_, state) => decorationsForSelection(state),
693 - apply: (tr, old, _, state) =>
694 - tr.docChanged || tr.selectionSet || tr.storedMarksSet ? decorationsForSelection(state) : old,
695 - },
696 - props: {
697 - decorations(state) {
698 - return MarkerPluginKey.getState(state);
699 - },
652 +/** Highlights chips inside a text selection; their node views draw no native highlight. */
653 +const ComposerChipSelectionExtension = Extension.create({
654 + name: "composer-chip-range-selection",
655 + addProseMirrorPlugins() {
656 + return [
657 + new Plugin<DecorationSet>({
658 + key: ChipSelectionPluginKey,
659 + state: {
660 + init: (_, state) => chipSelectionDecorations(state),
661 + apply: (tr, old, _, state) =>
662 + tr.docChanged || tr.selectionSet ? chipSelectionDecorations(state) : old,
663 + },
664 + props: {
665 + decorations: (state) => ChipSelectionPluginKey.getState(state),
666 + },
667 + }),
668 + ];
669 },
670 });
671
703 -function decorationsForSelection(state: EditorState): DecorationSet {
704 - const { doc, selection } = state;
705 - const caretSide = caretTakesMarksBefore(state) ? 3 : 0;
706 - const rtl = caretLineDirection(state) === "rtl";
672 +function chipSelectionDecorations({ doc, selection }: EditorState): DecorationSet {
673 + if (selection.empty) return DecorationSet.empty;
674 const decorations: Decoration[] = [];
708 - if (!selection.empty) {
709 - doc.nodesBetween(selection.from, selection.to, (node, pos) => {
710 - if (node.type.name.startsWith("composer-")) {
711 - decorations.push(
712 - Decoration.node(pos, pos + node.nodeSize, { class: "composer-chip-range-selected" }),
713 - );
714 - return false;
715 - }
716 - return true;
717 - });
718 - }
719 - for (const range of collectStyledRanges(doc)) {
720 - const active = selection.empty
721 - ? selection.from >= range.from && selection.from <= range.to
722 - : selection.from < range.to && selection.to > range.from;
723 - if (!active) continue;
724 - for (const { at, side: baseSide, text } of range.markers) {
725 - const side = selection.empty && at === selection.from ? baseSide + caretSide : baseSide;
726 - const marker = document.createElement("span");
727 - marker.className = "composer-rich-marker";
728 - marker.textContent = text;
729 - marker.setAttribute("aria-hidden", "true");
730 - // Inline code is isolated left to right. In a right-to-left line its
731 - // opening backtick joins the closing one inside the isolate, or the line
732 - // would put both on the same side of the code.
733 - const codeMarks =
734 - rtl && baseSide === -1 && /^`+$/.test(text)
735 - ? doc.resolve(at).nodeAfter?.marks.filter((mark) => mark.type.spec.code)
736 - : undefined;
737 - decorations.push(
738 - Decoration.widget(at, marker, {
739 - side,
740 - key: `marker-${at}-${side}-${marker.textContent}`,
741 - ...(codeMarks?.length ? { marks: codeMarks } : {}),
742 - }),
743 - );
744 - }
745 - }
675 + doc.nodesBetween(selection.from, selection.to, (node, pos) => {
676 + if (!node.type.name.startsWith("composer-")) return true;
677 + decorations.push(
678 + Decoration.node(pos, pos + node.nodeSize, { class: "composer-chip-range-selected" }),
679 + );
680 + return false;
681 + });
682 return DecorationSet.create(doc, decorations);
683 }
684
749 -const ComposerMarkersExtension = Extension.create({
750 - name: "composer-rich-markers",
751 - addProseMirrorPlugins() {
752 - return [ComposerMarkerPlugin];
753 - },
754 -});
755 -
685 type TiptapEditor = NonNullable<ReturnType<typeof useEditor>>;
686
687 function replaceSkillChips(
@@ -842,9 +771,10 @@ function createComposerExtensions(richText: boolean) {
771 ComposerSkillExtension,
772 ComposerCitationExtension,
773 ComposerContextReferenceExtension,
845 - ComposerMarkersExtension,
774 + ComposerChipSelectionExtension,
775 ...(richText
776 ? [
777 + ComposerMarkdownSourceExtension,
778 ComposerBoldSelectionOnlyExtension,
779 ComposerItalicExtension,
780 ComposerBoldExtension,
@@ -1291,7 +1221,11 @@ function ComposerPromptEditorTiptapInner(
1221 return true;
1222 }
1223 event.preventDefault();
1294 - if ((isTaskItem || isListItem) && instance && splitOrLiftListItem(instance)) {
1224 + if (
1225 + (isTaskItem || isListItem) &&
1226 + instance &&
1227 + splitOrLiftListItem(instance, collapseShownMarkdownSource)
1228 + ) {
1229 return true;
1230 }
1231 if (
@@ -1303,6 +1237,15 @@ function ComposerPromptEditorTiptapInner(
1237 ) {
1238 return true;
1239 }
1240 + // Parse shown Markdown first, or the split leaves each half with one delimiter.
1241 + if (instance) {
1242 + return instance
1243 + .chain()
1244 + .command(collapseShownMarkdownSource)
1245 + .command(({ state, dispatch }) => splitBlockKeepMarks(state, dispatch))
1246 + .scrollIntoView()
1247 + .run();
1248 + }
1249 return splitBlockKeepMarks(view.state, (tr) => {
1250 view.dispatch(tr.scrollIntoView());
1251 });
@@ -1330,11 +1273,12 @@ function ComposerPromptEditorTiptapInner(
1273 return false;
1274 }
1275 // Do not wrap chips, atoms, or styled text; default replacement preserves marks.
1276 + // Shown Markdown source is plain text, so typed delimiters wrap it.
1277 let touchesSpecial = false;
1278 view.state.doc.nodesBetween(from, to, (node) => {
1279 if (
1280 (node.isAtom && node.isInline && !node.isText) ||
1337 - (node.isText && node.marks.length > 0)
1281 + (node.isText && node.marks.some((mark) => mark.type.name !== MARKDOWN_SOURCE_MARK))
1282 ) {
1283 touchesSpecial = true;
1284 return false;
@@ -1368,6 +1312,22 @@ function ComposerPromptEditorTiptapInner(
1312 );
1313 return true;
1314 }
1315 + // Shown Markdown source is parsed when the caret leaves, so paste one line into it as text.
1316 + const sourceType = view.state.schema.marks[MARKDOWN_SOURCE_MARK];
1317 + const { from: pasteFrom, to: pasteTo, $from: $pasteFrom } = view.state.selection;
1318 + if (
1319 + sourceType?.isInSet($pasteFrom.marks()) &&
1320 + !pastedText.includes("\n") &&
1321 + collectComposerPromptInlineTokens(`${pastedText}\n`).length === 0
1322 + ) {
1323 + view.dispatch(
1324 + markAsClipboardEdit(
1325 + view.state.tr.insertText(pastedText, pasteFrom, pasteTo),
1326 + "paste",
1327 + ).scrollIntoView(),
1328 + );
1329 + return true;
1330 + }
1331 const importFragment = readCallbacks().importContextFragment;
1332 let text =
1333 !literalText && importFragment
@@ -1408,6 +1368,8 @@ function ComposerPromptEditorTiptapInner(
1368 markAsClipboardEdit(tr, "paste");
1369 return true;
1370 })
1371 + // Pasted chips and lines would split shown Markdown, so parse it first.
1372 + .command(collapseShownMarkdownSource)
1373 .insertContent(content)
1374 .command(({ tr }) => {
1375 // Move after a pasted rule so the next keystroke cannot replace it; add a trailing line
@@ -1562,9 +1524,8 @@ function ComposerPromptEditorTiptapInner(
1524 },
1525 );
1526 }
1527 + selectMarkdownOffset(editor, normalizedExpandedCursor);
1528 const map = serializeEditorDoc(editor.state.doc);
1566 - const flat = markdownToFlat(map, normalizedExpandedCursor);
1567 - editor.commands.setTextSelection(flatToPm(map, flat));
1529 if (isFocused) scrollTiptapCaretIntoView(editor);
1530 if (pendingCitation) {
1531 citationRequestRef.current = null;
@@ -1633,8 +1594,7 @@ function ComposerPromptEditorTiptapInner(
1594 const boundedCursor = clampEditorCursor(snapshotRef.current.value, nextCursor);
1595 const expandedCursor =
1596 exactExpandedCursor ?? expandEditorCursor(snapshotRef.current.value, boundedCursor);
1636 - const map = serializeEditorDoc(editor.state.doc);
1637 - editor.commands.setTextSelection(flatToPm(map, markdownToFlat(map, expandedCursor)));
1597 + selectMarkdownOffset(editor, expandedCursor);
1598 scrollTiptapCaretIntoView(editor);
1599 if (boundedCursor === snapshotRef.current.cursor) return;
1600 snapshotRef.current = {
@@ -1852,6 +1812,17 @@ function insertMarkdownParagraphs(
1812 insertContent(blocks as JSONContent[]);
1813 }
1814
1815 +/** Placing the caret can show Markdown markers, so place it again in the shown source. */
1816 +function selectMarkdownOffset(editor: TiptapEditor, offset: number): void {
1817 + for (let pass = 0; pass < 2; pass += 1) {
1818 + const map = serializeEditorDoc(editor.state.doc);
1819 + const pos = flatToPm(map, markdownToFlat(map, offset));
1820 + const { selection } = editor.state;
1821 + if (pass > 0 && selection.empty && selection.from === pos) return;
1822 + editor.commands.setTextSelection(pos);
1823 + }
1824 +}
1825 +
1826 /** Native scrolling follows only real input; explicitly reveal programmatically placed carets. */
1827 function scrollTiptapCaretIntoView(editor: TiptapEditor): void {
1828 editor.view.dispatch(editor.state.tr.scrollIntoView());
apps/web/src/composer-markdown-source.ts new
+575
@@ -0,0 +1,575 @@
1 +import { type Command, Extension, Mark as TiptapMark } from "@tiptap/core";
2 +import {
3 + closeHistory,
4 + isHistoryTransaction,
5 + redo,
6 + redoDepth,
7 + undo,
8 + undoDepth,
9 +} from "@tiptap/pm/history";
10 +import type { MarkType, Node as ProseMirrorNode } from "@tiptap/pm/model";
11 +import {
12 + AllSelection,
13 + type EditorState,
14 + NodeSelection,
15 + Plugin,
16 + PluginKey,
17 + type Selection,
18 + TextSelection,
19 + type Transaction,
20 +} from "@tiptap/pm/state";
21 +import { type Mapping, StepMap } from "@tiptap/pm/transform";
22 +import { Decoration, DecorationSet, type EditorView } from "@tiptap/pm/view";
23 +
24 +import {
25 + inlineMarkdownUnitMarks,
26 + MARKDOWN_SOURCE_MARK,
27 + type RichTextMark,
28 +} from "~/composer-rich-text";
29 +import { caretTakesMarksBefore, serializeEditorDoc } from "~/composer-rich-text-doc";
30 +
31 +// Styled text the selection touches becomes source text with the source mark,
32 +// parsed back once the selection leaves. History steps only replay on the shape
33 +// they were recorded in, so the history records both rewrites. Recording would
34 +// clear redo after undo or redo, so until the next edit see `normalizeDetached`.
35 +
36 +const STYLE_MARKS: RichTextMark[] = ["bold", "italic", "strike", "code"];
37 +const PREVIEW_TAGS: Record<Exclude<RichTextMark, "code">, string> = {
38 + bold: "strong",
39 + italic: "em",
40 + strike: "s",
41 +};
42 +const ATOM_TEXT = "";
43 +const DELIMITER = /[*_~`]/;
44 +
45 +type TextRange = { from: number; to: number };
46 +
47 +type StyledRange = TextRange & {
48 + escapedOpener: boolean;
49 + markers: { at: number; closing: boolean; text: string }[];
50 +};
51 +
52 +function collectStyledRanges(doc: ProseMirrorNode): StyledRange[] {
53 + const ranges: StyledRange[] = [];
54 + const map = serializeEditorDoc(doc);
55 + let range: StyledRange | null = null;
56 + let openLength = 0;
57 + for (const run of map.runs) {
58 + if (run.nodeName === "codeBlock") continue;
59 + if (run.openLen > 0) {
60 + let backslashes = 0;
61 + while (map.value[run.mdStart - backslashes - 1] === "\\") backslashes += 1;
62 + range ??= {
63 + from: run.pmPos,
64 + to: run.pmPos,
65 + escapedOpener: backslashes % 2 !== 0,
66 + markers: [],
67 + };
68 + range.markers.push({
69 + at: run.pmPos,
70 + closing: false,
71 + text: map.value.slice(run.mdStart, run.mdStart + run.openLen),
72 + });
73 + }
74 + if (range === null) continue;
75 + range.to = run.pmPos + run.docLen;
76 + if (run.closeLen > 0) {
77 + const end = run.mdStart + run.mdLen;
78 + range.markers.push({
79 + at: range.to,
80 + closing: true,
81 + text: map.value.slice(end - run.closeLen, end),
82 + });
83 + }
84 + openLength += run.openLen - run.closeLen;
85 + if (openLength === 0) {
86 + ranges.push(range);
87 + range = null;
88 + }
89 + }
90 + return ranges;
91 +}
92 +
93 +/** Whether the Markdown that reveal shows for `range` parses back to the same styles. */
94 +function revealsFaithfully(doc: ProseMirrorNode, range: StyledRange): boolean {
95 + if (range.escapedOpener) return false;
96 + const adjacent = withAdjacentDelimiters(doc, range);
97 + if (adjacent.from !== range.from || adjacent.to !== range.to) return false;
98 + // Parsing keeps escapes as text, so styled `path\` or `2*3` stays styled, unshown.
99 + const markers = range.markers.toSorted(
100 + (left, right) => left.at - right.at || Number(right.closing) - Number(left.closing),
101 + );
102 + const expected: Array<RichTextMark[] | null> = [];
103 + let text = "";
104 + let next = 0;
105 + const addMarkers = (pos: number) => {
106 + for (; next < markers.length && markers[next]!.at <= pos; next++) {
107 + text += markers[next]!.text;
108 + expected.push(...markers[next]!.text.split("").map(() => null));
109 + }
110 + };
111 + doc.nodesBetween(range.from, range.to, (node, pos) => {
112 + if (!node.isInline) return true;
113 + const marks = STYLE_MARKS.filter((name) => node.marks.some((mark) => mark.type.name === name));
114 + const from = Math.max(pos, range.from);
115 + const content = node.isText ? node.text!.slice(from - pos, range.to - pos) : ATOM_TEXT;
116 + for (let index = 0; index < content.length; index++) {
117 + addMarkers(from + index);
118 + text += content[index];
119 + expected.push(marks);
120 + }
121 + return false;
122 + });
123 + addMarkers(range.to);
124 + return inlineMarkdownUnitMarks(text).every((marks, index) => sameMarks(marks, expected[index]!));
125 +}
126 +
127 +function touches(selection: Selection, { from, to }: TextRange): boolean {
128 + return selection.empty
129 + ? selection.from >= from && selection.from <= to
130 + : selection.from < to && selection.to > from;
131 +}
132 +
133 +function sourceRegions(doc: ProseMirrorNode, type: MarkType): TextRange[] {
134 + const regions: TextRange[] = [];
135 + doc.descendants((node, pos) => {
136 + if (!node.isTextblock) return true;
137 + let current: TextRange | null = null;
138 + node.forEach((child, offset) => {
139 + const start = pos + 1 + offset;
140 + if (!type.isInSet(child.marks)) {
141 + current = null;
142 + } else if (current) {
143 + current.to = start + child.nodeSize;
144 + } else {
145 + current = { from: start, to: start + child.nodeSize };
146 + regions.push(current);
147 + }
148 + });
149 + return false;
150 + });
151 + return regions;
152 +}
153 +
154 +/** Takes in delimiters typed beside the source, like a closing `**` retyped after its text. */
155 +function withAdjacentDelimiters(doc: ProseMirrorNode, region: TextRange): TextRange {
156 + const before = doc.resolve(region.from).nodeBefore;
157 + const after = doc.resolve(region.to).nodeAfter;
158 + let from = region.from;
159 + let to = region.to;
160 + if (before?.isText && before.marks.length === 0) {
161 + const text = before.text!;
162 + let count = 0;
163 + while (count < text.length && DELIMITER.test(text[text.length - 1 - count]!)) count += 1;
164 + // Only an odd backslash run escapes the first adjacent delimiter.
165 + let backslashes = 0;
166 + while (text[text.length - 1 - count - backslashes] === "\\") backslashes += 1;
167 + if (count > 0 && backslashes % 2 === 1) count -= 1;
168 + from -= count;
169 + }
170 + if (after?.isText && after.marks.length === 0) {
171 + const text = after.text!;
172 + let count = 0;
173 + while (count < text.length && DELIMITER.test(text[count]!)) count += 1;
174 + to += count;
175 + }
176 + return { from, to };
177 +}
178 +
179 +function sameMarks(left: RichTextMark[] | null, right: RichTextMark[] | null): boolean {
180 + if (left === null || right === null) return left === right;
181 + return left.length === right.length && left.every((mark) => right.includes(mark));
182 +}
183 +
184 +/** Calls `visit` for each run of units that parse the same way. */
185 +function forEachUnitRun(
186 + units: ReadonlyArray<RichTextMark[] | null>,
187 + visit: (start: number, end: number, marks: RichTextMark[] | null) => void,
188 +): void {
189 + let start = 0;
190 + while (start < units.length) {
191 + let end = start + 1;
192 + while (end < units.length && sameMarks(units[end]!, units[start]!)) end += 1;
193 + visit(start, end, units[start]!);
194 + start = end;
195 + }
196 +}
197 +
198 +function regionUnits(doc: ProseMirrorNode, { from, to }: TextRange) {
199 + const text = doc.textBetween(from, to, undefined, ATOM_TEXT);
200 + return { text, units: inlineMarkdownUnitMarks(text) };
201 +}
202 +
203 +function collapseRegion(tr: Transaction, region: TextRange, type: MarkType): void {
204 + const { schema } = tr.doc.type;
205 + const { units } = regionUnits(tr.doc, region);
206 + tr.removeMark(region.from, region.to, type);
207 + forEachUnitRun(units, (start, end, marks) => {
208 + for (const name of marks ?? []) {
209 + const markType = schema.marks[name];
210 + if (markType) tr.addMark(region.from + start, region.from + end, markType.create());
211 + }
212 + });
213 + const deletions: TextRange[] = [];
214 + forEachUnitRun(units, (start, end, marks) => {
215 + if (marks === null) deletions.push({ from: region.from + start, to: region.from + end });
216 + });
217 + for (const { from, to } of deletions.toReversed()) tr.delete(from, to);
218 +}
219 +
220 +/** Parses source the selection does not touch back into marks, in place. */
221 +function collapseMarkdownSource(
222 + tr: Transaction,
223 + keep: (region: TextRange) => boolean = () => false,
224 +): void {
225 + const type = tr.doc.type.schema.marks[MARKDOWN_SOURCE_MARK];
226 + if (!type) return;
227 + const regions: TextRange[] = [];
228 + for (const region of sourceRegions(tr.doc, type)) {
229 + const extended = withAdjacentDelimiters(tr.doc, region);
230 + const previous = regions.at(-1);
231 + if (previous && extended.from <= previous.to) previous.to = Math.max(previous.to, extended.to);
232 + else regions.push(extended);
233 + }
234 + for (const region of regions.toReversed()) {
235 + if (keep(region)) tr.addMark(region.from, region.to, type.create());
236 + else collapseRegion(tr, region, type);
237 + }
238 +}
239 +
240 +function mapSelection(tr: Transaction, selection: Selection, map: (pos: number) => number) {
241 + if (selection instanceof AllSelection) return new AllSelection(tr.doc);
242 + if (selection instanceof NodeSelection) {
243 + const pos = map(selection.from);
244 + if (tr.doc.nodeAt(pos)) return NodeSelection.create(tr.doc, pos);
245 + }
246 + return TextSelection.create(tr.doc, map(selection.anchor), map(selection.head));
247 +}
248 +
249 +/** Parses all shown source first, so a command that splits it keeps its styles. */
250 +export const collapseShownMarkdownSource: Command = ({ tr }) => {
251 + collapseMarkdownSource(tr);
252 + return true;
253 +};
254 +
255 +function mapRange(mapping: Mapping, { from, to }: TextRange): TextRange {
256 + return { from: mapping.map(from, 1), to: mapping.map(to, -1) };
257 +}
258 +
259 +/** Shows styled text the selection touches as Markdown, returning the source it added. */
260 +function revealStyledText(tr: Transaction, type: MarkType, typed: boolean, takesBefore: boolean) {
261 + const { schema } = tr.doc.type;
262 + const selection = tr.selection;
263 + const ranges = collectStyledRanges(tr.doc).filter(
264 + (range) => touches(selection, range) && revealsFaithfully(tr.doc, range),
265 + );
266 + const revealed: { range: TextRange; step: number }[] = [];
267 + const insertions: { at: number; length: number; closing: boolean }[] = [];
268 + for (const range of ranges.toReversed()) {
269 + for (const name of STYLE_MARKS) {
270 + const markType = schema.marks[name];
271 + if (markType) tr.removeMark(range.from, range.to, markType);
272 + }
273 + let length = 0;
274 + // Inserting from the end keeps earlier positions valid; at a shared
275 + // position the opening marker goes in first so the closing one ends up before it.
276 + const markers = range.markers.toSorted(
277 + (left, right) => right.at - left.at || Number(left.closing) - Number(right.closing),
278 + );
279 + for (const { at, closing, text } of markers) {
280 + tr.insert(at, schema.text(text, [type.create()]));
281 + insertions.push({ at, length: text.length, closing });
282 + length += text.length;
283 + }
284 + tr.addMark(range.from, range.to + length, type.create());
285 + revealed.push({ range: { from: range.from, to: range.to + length }, step: tr.steps.length });
286 + }
287 + if (ranges.length === 0) return [];
288 + // A caret that arrives at a styled edge stays outside its markers. One that
289 + // just typed styled text stays inside them, so the next character continues it.
290 + const map = (pos: number) => {
291 + let next = pos;
292 + for (const { at, length, closing } of insertions) {
293 + const inside = typed && selection.empty && (closing ? takesBefore : !takesBefore);
294 + if (at < pos || (at === pos && (selection instanceof NodeSelection || closing !== inside))) {
295 + next += length;
296 + }
297 + }
298 + return next;
299 + };
300 + tr.setSelection(mapSelection(tr, selection, map));
301 + return revealed.map(({ range, step }) => mapRange(tr.mapping.slice(step), range));
302 +}
303 +
304 +/** Shows styled text the selection touches as Markdown, and parses source it left. */
305 +function normalizeMarkdownSource(state: EditorState, typed: boolean): Transaction | null {
306 + const type = state.schema.marks[MARKDOWN_SOURCE_MARK];
307 + if (!type) return null;
308 + const tr = state.tr;
309 + collapseMarkdownSource(tr, (region) => touches(state.selection, region));
310 + revealStyledText(tr, type, typed, caretTakesMarksBefore(state));
311 + return tr.docChanged ? tr : null;
312 +}
313 +
314 +/**
315 + * After undo or redo, history items may point inside shown source, and a
316 + * rewrite in the history would clear redo. So until the next recorded edit,
317 + * rewrites stay out of it and only remove text they added: source the history
318 + * knows is hidden instead of parsed, and source revealed here is parsed back.
319 + */
320 +function normalizeDetached(state: EditorState, revealed: TextRange[]): Transaction | null {
321 + const type = state.schema.marks[MARKDOWN_SOURCE_MARK];
322 + if (!type) return null;
323 + const tr = state.tr;
324 + const kept: TextRange[] = [];
325 + for (const region of revealed.toSorted((left, right) => right.from - left.from)) {
326 + if (touches(state.selection, region)) kept.push(region);
327 + else collapseRegion(tr, region, type);
328 + }
329 + const added = revealStyledText(tr, type, false, caretTakesMarksBefore(state));
330 + if (!tr.docChanged) return null;
331 + const shown = [...kept.map((region) => mapRange(tr.mapping, region)), ...added];
332 + return tr.setMeta(markdownSourceKey, shown).setMeta("addToHistory", false);
333 +}
334 +
335 +/** Parses the source `normalizeDetached` revealed, leaving the document the history knows. */
336 +function collapseRevealed(state: EditorState, revealed: TextRange[]): Transaction {
337 + const tr = state.tr;
338 + const type = state.schema.marks[MARKDOWN_SOURCE_MARK];
339 + if (type) {
340 + for (const region of revealed.toSorted((left, right) => right.from - left.from)) {
341 + collapseRegion(tr, region, type);
342 + }
343 + }
344 + return tr.setMeta(markdownSourceKey, []).setMeta("addToHistory", false);
345 +}
346 +
347 +/** Replays `edit` after undoing `collapse`, so the history records the reveal with the edit. */
348 +function rebaseEdit(tr: Transaction, collapse: Transaction, edit: Transaction): Transaction {
349 + for (let index = collapse.steps.length - 1; index >= 0; index--) {
350 + tr.step(collapse.steps[index]!.invert(collapse.docs[index]!));
351 + }
352 + for (const step of edit.steps) tr.step(step);
353 + tr.setSelection(edit.selection.map(tr.doc, StepMap.empty)).setTime(edit.time);
354 + if (edit.storedMarksSet) tr.setStoredMarks(edit.storedMarks);
355 + if (edit.scrolledIntoView) tr.scrollIntoView();
356 + // Metadata has no public accessor, and grouping, paste rules and composition read it.
357 + type WithMeta = { meta: Record<string, unknown> };
358 + Object.assign((tr as unknown as WithMeta).meta, (edit as unknown as WithMeta).meta);
359 + return tr;
360 +}
361 +
362 +const replayKey = new PluginKey("composer-markdown-source-replay");
363 +
364 +/**
365 + * Replays the edit a request carries after the source plugin appended its collapse,
366 + * in the request's one view update so an IME keeps its preedit. History ignores what
367 + * is appended to an unrecorded transaction, so the request itself records nothing.
368 + */
369 +const replayPlugin = new Plugin({
370 + key: replayKey,
371 + appendTransaction([request, collapse], _, state) {
372 + const edit = request?.getMeta(replayKey) as Transaction | undefined;
373 + // Appended transactions otherwise join the previous undo event.
374 + return edit && collapse ? closeHistory(rebaseEdit(state.tr, collapse, edit)) : null;
375 + },
376 +});
377 +
378 +function previewDecorations(
379 + doc: ProseMirrorNode,
380 + type: MarkType,
381 + hidden: Selection | null,
382 +): DecorationSet {
383 + const decorations: Decoration[] = [];
384 + for (const region of sourceRegions(doc, type)) {
385 + const hide = hidden !== null && !touches(hidden, region);
386 + const { text, units } = regionUnits(doc, region);
387 + const codeTicks = new Set<number>();
388 + forEachUnitRun(units, (start, end, marks) => {
389 + for (const name of marks ?? []) {
390 + if (name !== "code") {
391 + decorations.push(
392 + Decoration.inline(region.from + start, region.from + end, {
393 + nodeName: PREVIEW_TAGS[name],
394 + }),
395 + );
396 + continue;
397 + }
398 + // One element holds the ticks and the code, so a right-to-left line
399 + // keeps both ticks on their own sides of it.
400 + let from = start;
401 + let to = end;
402 + if (units[from - 1] === null && text[from - 1] === "`") codeTicks.add((from -= 1));
403 + if (units[to] === null && text[to] === "`") codeTicks.add(to++);
404 + decorations.push(
405 + Decoration.inline(region.from + from, region.from + to, { nodeName: "code", dir: "ltr" }),
406 + );
407 + }
408 + });
409 + forEachUnitRun(
410 + units.map((marks, index) => (marks === null && (hide || !codeTicks.has(index)) ? null : [])),
411 + (start, end, marks) => {
412 + if (marks !== null) return;
413 + decorations.push(
414 + Decoration.inline(region.from + start, region.from + end, {
415 + class: hide ? "composer-rich-marker-hidden" : "composer-rich-marker",
416 + }),
417 + );
418 + },
419 + );
420 + }
421 + return DecorationSet.create(doc, decorations);
422 +}
423 +
424 +type MarkdownSourceState = {
425 + decorations: DecorationSet;
426 + /** From an undo or redo until the next recorded edit; see `normalizeDetached`. */
427 + detached: boolean;
428 + /** Source `normalizeDetached` revealed, which the history knows as styled text. */
429 + revealed: TextRange[];
430 +};
431 +
432 +const markdownSourceKey = new PluginKey<MarkdownSourceState>("composer-markdown-source");
433 +
434 +function markdownSourcePlugin(type: MarkType): Plugin<MarkdownSourceState> {
435 + let view: EditorView | null = null;
436 + return new Plugin<MarkdownSourceState>({
437 + key: markdownSourceKey,
438 + view(editorView) {
439 + view = editorView;
440 + return {
441 + destroy() {
442 + view = null;
443 + },
444 + };
445 + },
446 + state: {
447 + init: (_, state) => ({
448 + decorations: previewDecorations(state.doc, type, null),
449 + detached: false,
450 + revealed: [],
451 + }),
452 + apply: (tr, old, _, state) => {
453 + const history = isHistoryTransaction(tr);
454 + const detached =
455 + history || (old.detached && !(tr.docChanged && tr.getMeta("addToHistory") !== false));
456 + const own = tr.getMeta(markdownSourceKey) as TextRange[] | undefined;
457 + const revealed =
458 + !detached || history
459 + ? []
460 + : (own ??
461 + (tr.docChanged
462 + ? old.revealed.map((range) => mapRange(tr.mapping, range))
463 + : old.revealed));
464 + const redraw = tr.docChanged || detached !== old.detached || (detached && tr.selectionSet);
465 + return {
466 + decorations: redraw
467 + ? previewDecorations(state.doc, type, detached ? state.selection : null)
468 + : old.decorations,
469 + detached,
470 + revealed,
471 + };
472 + },
473 + },
474 + props: {
475 + decorations: (state) => markdownSourceKey.getState(state)?.decorations,
476 + },
477 + appendTransaction(transactions, _, state) {
478 + if (transactions[0]?.getMeta(replayKey)) {
479 + return collapseRevealed(state, markdownSourceKey.getState(state)?.revealed ?? []);
480 + }
481 + // Rewriting text mid-composition would break the IME's preedit.
482 + if (view?.composing) return null;
483 + // Rewrites appended to an undo or redo join its history step, which leaves
484 + // the other direction unmapped. The dispatch hook normalizes after it instead.
485 + if (transactions.some((tr) => isHistoryTransaction(tr) || tr.getMeta(markdownSourceKey))) {
486 + return null;
487 + }
488 + if (!transactions.some((tr) => tr.docChanged || tr.selectionSet)) return null;
489 + const source = markdownSourceKey.getState(state);
490 + if (source?.detached) return normalizeDetached(state, source.revealed);
491 + const tr = normalizeMarkdownSource(
492 + state,
493 + transactions.some((item) => item.docChanged),
494 + );
495 + // With nothing to undo, a recorded rewrite would only add a no-op undo.
496 + if (tr && undoDepth(state) === 0) tr.setMeta("addToHistory", false);
497 + return tr;
498 + },
499 + });
500 +}
501 +
502 +/** Keeps source `normalizeDetached` revealed out of what undo, redo and edits see. */
503 +const MarkdownSourceHistoryExtension = Extension.create({
504 + name: "composer-markdown-source-history",
505 + // Runs after undo grouping, so a rebased edit keeps the grouping chosen for it.
506 + priority: 1,
507 + dispatchTransaction({ transaction, next }) {
508 + const { editor } = this;
509 + const revealed = markdownSourceKey.getState(editor.state)?.revealed ?? [];
510 + if (isHistoryTransaction(transaction)) {
511 + if (revealed.length === 0) {
512 + next(transaction);
513 + } else {
514 + const undoing = redoDepth(editor.state.apply(transaction)) > redoDepth(editor.state);
515 + next(collapseRevealed(editor.state, revealed));
516 + (undoing ? undo : redo)(editor.state, next);
517 + }
518 + const source = markdownSourceKey.getState(editor.state);
519 + const tr = editor.view.composing
520 + ? null
521 + : normalizeDetached(editor.state, source?.revealed ?? []);
522 + if (tr) next(tr);
523 + return;
524 + }
525 + const recordedEdit =
526 + transaction.docChanged &&
527 + transaction.getMeta("addToHistory") !== false &&
528 + transaction.getMeta(markdownSourceKey) === undefined;
529 + if (revealed.length === 0 || !recordedEdit) {
530 + next(transaction);
531 + return;
532 + }
533 + next(editor.state.tr.setMeta(replayKey, transaction));
534 + },
535 +});
536 +
537 +export const ComposerMarkdownSourceExtension = TiptapMark.create({
538 + name: MARKDOWN_SOURCE_MARK,
539 + // Its shortcuts run ahead of the style marks' own.
540 + priority: 1001,
541 + inclusive: false,
542 + parseHTML() {
543 + return [{ tag: "span.composer-markdown-source" }];
544 + },
545 + renderHTML() {
546 + return ["span", { class: "composer-markdown-source" }, 0];
547 + },
548 + addKeyboardShortcuts() {
549 + // Shown markers are plain text, so toggling a style there would wrap them
550 + // in another style. Parse the source first and toggle the result.
551 + const toggle = (name: RichTextMark) => () => {
552 + const { state } = this.editor;
553 + if (state.selection.empty) return false;
554 + const touched = sourceRegions(state.doc, this.type).some((region) =>
555 + touches(state.selection, region),
556 + );
557 + if (!touched) return false;
558 + return this.editor.chain().command(collapseShownMarkdownSource).toggleMark(name).run();
559 + };
560 + return {
561 + "Mod-b": toggle("bold"),
562 + "Mod-B": toggle("bold"),
563 + "Mod-i": toggle("italic"),
564 + "Mod-I": toggle("italic"),
565 + "Mod-Shift-s": toggle("strike"),
566 + "Mod-e": toggle("code"),
567 + };
568 + },
569 + addExtensions() {
570 + return [MarkdownSourceHistoryExtension];
571 + },
572 + addProseMirrorPlugins() {
573 + return [markdownSourcePlugin(this.type), replayPlugin];
574 + },
575 +});
apps/web/src/composer-rich-text-doc.ts
+35 -7
@@ -42,7 +42,12 @@ import { ReplaceStep } from "@tiptap/pm/transform";
42
43 import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
44 import { nextOrderedMarkerText } from "~/composer-list-continuation";
45 -import { parseInlineMarkdown, RICH_TEXT_DELIMITERS, type RichTextMark } from "~/composer-rich-text";
45 +import {
46 + MARKDOWN_SOURCE_MARK,
47 + parseInlineMarkdown,
48 + RICH_TEXT_DELIMITERS,
49 + type RichTextMark,
50 +} from "~/composer-rich-text";
51 import { collectInlineContextIds } from "~/lib/composerContextReferences";
52 import { composerMathRanges } from "@t3tools/shared/composerInlineTokens";
53
@@ -90,6 +95,7 @@ function codePairCaretPlugin(type: MarkType) {
95 if (view.composing || from !== to || text !== "`") return false;
96 const $from = view.state.doc.resolve(from);
97 if (!$from.parent.isTextblock || $from.parent.type.spec.code) return false;
98 + if (touchesMarkdownSource(view.state, from, to)) return false;
99 const before = $from.nodeBefore?.text ?? "";
100 if (closesBacktickPair($from)) {
101 view.dispatch(insert().setMeta(codePairKey, { from: from - 1, to: from + 1 }));
@@ -218,7 +224,10 @@ export const ComposerCodeExtension = Code.extend({
224 find: rule.find,
225 undoable: rule.undoable,
226 handler: (props) => {
221 - if (literalBackticksBefore(props.state.doc.resolve(props.range.from)) % 2 === 1) {
227 + if (
228 + literalBackticksBefore(props.state.doc.resolve(props.range.from)) % 2 === 1 ||
229 + touchesMarkdownSource(props.state, props.range.from, props.range.to)
230 + ) {
231 return null;
232 }
233
@@ -246,6 +255,18 @@ function literalBackticksBefore($pos: ResolvedPos): number {
255 return count;
256 }
257
258 +/**
259 + * Whether `from`-`to`, or the caret at `from`, is in shown Markdown source.
260 + * Typed delimiters there stay text until the caret leaves and the source is parsed.
261 + */
262 +function touchesMarkdownSource(state: EditorState, from: number, to: number): boolean {
263 + const type = state.schema.marks[MARKDOWN_SOURCE_MARK];
264 + if (!type) return false;
265 + if (from < to) return state.doc.rangeHasMark(from, to, type);
266 + const $pos = state.doc.resolve(from);
267 + return [$pos.nodeBefore, $pos.nodeAfter].some((node) => node && type.isInSet(node.marks));
268 +}
269 +
270 // Code permits nested emphasis, so Tiptap's exclusion check cannot protect literal delimiters.
271 function markInputRuleOutsideCode(find: RegExp, type: MarkType) {
272 const rule = markInputRule({ find, type });
@@ -257,6 +278,7 @@ function markInputRuleOutsideCode(find: RegExp, type: MarkType) {
278 const content = match[match.length - 1] ?? "";
279 const textStart = range.from + match[0].indexOf(content);
280 const textEnd = textStart + content.length;
281 + if (touchesMarkdownSource(state, range.from, range.to)) return null;
282 if (
283 code &&
284 (state.doc.rangeHasMark(range.from + match[0].search(/\S/), textStart, code) ||
@@ -1206,7 +1228,8 @@ function renumberFollowingItems(
1228 });
1229 }
1230
1209 -export function splitOrLiftListItem(editor: Editor): boolean {
1231 +/** `prepare` runs first in the same transaction, which the split then reads. */
1232 +export function splitOrLiftListItem(editor: Editor, prepare: Command): boolean {
1233 const $from = editor.state.selection.$from;
1234 const itemType = listItemTypeAt($from);
1235 if (!itemType) return false;
@@ -1221,7 +1244,7 @@ export function splitOrLiftListItem(editor: Editor): boolean {
1244 if (moved) alignListItemWithSiblings(tr, itemType);
1245 return moved;
1246 };
1224 - return editor.can().command(move) && editor.chain().command(move).run();
1247 + return editor.can().command(move) && editor.chain().command(prepare).command(move).run();
1248 }
1249
1250 export function convertBulletItemToTask(
@@ -1639,15 +1662,20 @@ export function pmToFlat(map: RichDocMap, pmPos: number): number {
1662
1663 // Styled boundaries need two caret stops at one position, one for each side's marks.
1664
1665 +// Shown Markdown source has real characters at its edges, so it needs no extra stop.
1666 +function styleMarks(marks: readonly Mark[]): readonly Mark[] {
1667 + return marks.filter((mark) => mark.type.name !== MARKDOWN_SOURCE_MARK);
1668 +}
1669 +
1670 function styledEdge(state: EditorState) {
1671 const { selection } = state;
1672 if (!selection.empty) return null;
1673 const { $from } = selection;
1674 if (!$from.parent.inlineContent) return null;
1647 - const before = $from.nodeBefore?.marks ?? Mark.none;
1648 - const after = $from.nodeAfter?.marks ?? Mark.none;
1675 + const before = styleMarks($from.nodeBefore?.marks ?? Mark.none);
1676 + const after = styleMarks($from.nodeAfter?.marks ?? Mark.none);
1677 if (Mark.sameSet(before, after)) return null;
1650 - return { before, after, current: state.storedMarks ?? $from.marks() };
1678 + return { before, after, current: styleMarks(state.storedMarks ?? $from.marks()) };
1679 }
1680
1681 export function caretTakesMarksBefore(state: EditorState): boolean {
apps/web/src/composer-rich-text.test.ts
+19 -1
@@ -1,6 +1,6 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { parseInlineMarkdown } from "./composer-rich-text";
3 +import { inlineMarkdownUnitMarks, parseInlineMarkdown } from "./composer-rich-text";
4
5 describe("composer rich text markdown", () => {
6 it("preserves unmatched markers, escaped markers, and identifiers", () => {
@@ -56,4 +56,22 @@ describe("composer rich text markdown", () => {
56 { text: "**not bold**", marks: ["code"] },
57 ]);
58 });
59 +
60 + it("maps each source character to its marks, or null for a dropped delimiter", () => {
61 + const bold = ["bold"];
62 + expect(inlineMarkdownUnitMarks("**`*` w** \\*")).toEqual([
63 + null,
64 + null,
65 + null,
66 + ["bold", "code"],
67 + null,
68 + bold,
69 + bold,
70 + null,
71 + null,
72 + [],
73 + [],
74 + [],
75 + ]);
76 + });
77 });
apps/web/src/composer-rich-text.ts
+57 -30
@@ -12,29 +12,35 @@ export const RICH_TEXT_DELIMITERS: Record<RichTextMark, string> = {
12 code: "`",
13 };
14
15 -function pushSpan(spans: RichTextSpan[], text: string, marks: RichTextMark[]): void {
16 - if (!text) return;
17 - const last = spans[spans.length - 1];
18 - if (
19 - last &&
20 - last.marks.length === marks.length &&
21 - last.marks.every((mark, index) => mark === marks[index])
22 - ) {
23 - last.text += text;
24 - } else {
25 - spans.push({ text, marks });
26 - }
15 +/** A run of `text` from `start` to `end` that parses with `marks`. */
16 +interface SourcePiece {
17 + start: number;
18 + end: number;
19 + marks: RichTextMark[];
20 }
21
29 -export function parseInlineMarkdown(text: string): RichTextSpan[] {
30 - const root: RichTextSpan[] = [];
31 - const stack: { delimiter: string; mark: RichTextMark; spans: RichTextSpan[] }[] = [];
32 - const current = () => stack.at(-1)?.spans ?? root;
22 +function sameMarks(left: readonly RichTextMark[], right: readonly RichTextMark[]): boolean {
23 + return left.length === right.length && left.every((mark, index) => mark === right[index]);
24 +}
25 +
26 +// Pieces keep source offsets, so callers can map parsed text back onto the
27 +// characters it came from; parsing only drops delimiters.
28 +function parseInlineMarkdownPieces(text: string): SourcePiece[] {
29 + const root: SourcePiece[] = [];
30 + const stack: { delimiter: string; mark: RichTextMark; start: number; pieces: SourcePiece[] }[] =
31 + [];
32 + const push = (start: number, end: number, marks: RichTextMark[] = []) => {
33 + if (end <= start) return;
34 + const pieces = stack.at(-1)?.pieces ?? root;
35 + const last = pieces.at(-1);
36 + if (last?.end === start && sameMarks(last.marks, marks)) last.end = end;
37 + else pieces.push({ start, end, marks });
38 + };
39 let index = 0;
40 while (index < text.length) {
41 const char = text[index]!;
42 if (char === "\\") {
37 - pushSpan(current(), text.slice(index, index + 2), []);
43 + push(index, Math.min(index + 2, text.length));
44 index += 2;
45 continue;
46 }
@@ -47,16 +53,16 @@ export function parseInlineMarkdown(text: string): RichTextSpan[] {
53 !text.slice(index, close).includes("\n") &&
54 text[close + 1] !== "`"
55 ) {
50 - pushSpan(current(), text.slice(index + 1, close), ["code"]);
56 + push(index + 1, close, ["code"]);
57 index = close + 1;
58 } else {
53 - pushSpan(current(), run, []);
59 + push(index, index + run.length);
60 index += run.length;
61 }
62 continue;
63 }
64 if (char !== "*" && char !== "_" && char !== "~") {
59 - pushSpan(current(), char, []);
65 + push(index, index + 1);
66 index += 1;
67 continue;
68 }
@@ -82,33 +88,54 @@ export function parseInlineMarkdown(text: string): RichTextSpan[] {
88 index + top.delimiter.length <= end
89 ) {
90 stack.pop();
85 - for (const span of top.spans) pushSpan(current(), span.text, [top.mark, ...span.marks]);
91 + for (const piece of top.pieces) push(piece.start, piece.end, [top.mark, ...piece.marks]);
92 index += top.delimiter.length;
93 } else if (canOpen && (char !== "~" || end - index >= 2)) {
94 const length = char === "~" || end - index >= 2 ? 2 : 1;
95 const mark = char === "~" ? "strike" : length === 2 ? "bold" : "italic";
96 // Prevent self-nesting, including alternate delimiters, to bound the stack by supported styles.
97 if (stack.some((frame) => frame.mark === mark)) {
92 - pushSpan(current(), text.slice(index, end), []);
98 + push(index, end);
99 index = end;
100 continue;
101 }
96 - stack.push({
97 - delimiter: char.repeat(length),
98 - mark,
99 - spans: [],
100 - });
102 + stack.push({ delimiter: char.repeat(length), mark, start: index, pieces: [] });
103 index += length;
104 } else {
103 - pushSpan(current(), text.slice(index, end), []);
105 + push(index, end);
106 index = end;
107 }
108 }
109 }
110 while (stack.length > 0) {
111 const frame = stack.pop()!;
110 - pushSpan(current(), frame.delimiter, []);
111 - for (const span of frame.spans) pushSpan(current(), span.text, span.marks);
112 + push(frame.start, frame.start + frame.delimiter.length);
113 + for (const piece of frame.pieces) push(piece.start, piece.end, piece.marks);
114 }
115 return root;
116 }
117 +
118 +export function parseInlineMarkdown(text: string): RichTextSpan[] {
119 + const spans: RichTextSpan[] = [];
120 + for (const { start, end, marks } of parseInlineMarkdownPieces(text)) {
121 + const last = spans.at(-1);
122 + if (last && sameMarks(last.marks, marks)) {
123 + last.text += text.slice(start, end);
124 + } else {
125 + spans.push({ text: text.slice(start, end), marks });
126 + }
127 + }
128 + return spans;
129 +}
130 +
131 +/** Marks text the composer shows as editable Markdown source while the caret is in it. */
132 +export const MARKDOWN_SOURCE_MARK = "markdownSource";
133 +
134 +/** Marks for each UTF-16 unit of `text`, or null for a delimiter that parsing drops. */
135 +export function inlineMarkdownUnitMarks(text: string): Array<RichTextMark[] | null> {
136 + const result: Array<RichTextMark[] | null> = Array.from({ length: text.length }, () => null);
137 + for (const { start, end, marks } of parseInlineMarkdownPieces(text)) {
138 + result.fill(marks, start, end);
139 + }
140 + return result;
141 +}
apps/web/src/index.css
+6 -2
@@ -2446,14 +2446,18 @@ code {
2446 padding: 0.05em 0.25em;
2447 }
2448
2449 +/* Markdown delimiters shown, as editable text, around styled text with the caret in it. */
2450 .composer-rich-marker {
2451 color: var(--muted-foreground);
2452 opacity: 0.75;
2453 font-weight: 400;
2454 font-style: normal;
2455 text-decoration: none;
2455 - user-select: none;
2456 - pointer-events: none;
2456 +}
2457 +
2458 +/* Delimiters of source restored by undo or redo, once the caret leaves it. */
2459 +.composer-rich-marker-hidden {
2460 + display: none;
2461 }
2462
2463 /* Selected chips (node selection from arrowing into or clicking a chip). */
docs/user/composer.md
+13 -6
@@ -14,12 +14,19 @@ to keep a large paste editable in the composer instead.
14
15 ## Formatting
16
17 -The composer writes Markdown and shows it styled as you type. Markers such as
18 -`**` stay in the text and show beside the styled words when your cursor is on
19 -them. Lines starting with `- `, `1. `, `- [ ] `, `> `, `# ` or `---` become lists,
20 -task lists, quotes, headings and rules; ` ``` ` followed by Enter opens a code
21 -block. What you typed is what the agent receives, markers and numbering
22 -included, and `#1234` without a space still looks up a pull request.
17 +The composer writes Markdown and shows it styled as you type. When your cursor
18 +is on styled text, its Markdown shows instead, such as `**bold**`, and the
19 +markers edit like any other text: delete them to remove the style, or change
20 +`**` to `*` for italic. The style updates when your cursor leaves. To write
21 +plain Markdown with no styling, turn off **Settings → Chat → Rich text
22 +composer**. Lines starting with `- `, `1. `, `- [ ] `, `> `, `# ` or `---`
23 +become lists, task lists, quotes, headings and rules; ` ``` ` followed by Enter
24 +opens a code block. What you typed is what the agent receives, markers and
25 +numbering included, and `#1234` without a space still looks up a pull request.
26 +
27 +Some styled text containing or touching literal Markdown characters, such as a
28 +bold `path\` or `2*3`, keeps its styling without showing markers. Use formatting
29 +shortcuts or turn off rich text to edit the formatting of those ranges.
30
31 Enter sends. In a list or quote, **Shift+Enter** continues it, and Shift+Enter
32 on an empty line moves out one level, then leaves it; **Tab** nests a list item