Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(editor): text highlight (==text==) in description & comments [MUL-2934] (#3661)

Jiayuan Zhang0d51614c9c9a
diff --git a/packages/views/editor/bubble-menu.tsx b/packages/views/editor/bubble-menu.tsx
index 0e1acf5e86..3dc42d6bf7 100644
--- a/packages/views/editor/bubble-menu.tsx
+++ b/packages/views/editor/bubble-menu.tsx
@@ -56,6 +56,7 @@ import {
Italic,
Strikethrough,
Code,
+ Highlighter,
Link2,
List,
ListOrdered,
@@ -92,13 +93,14 @@ function shouldShowBubbleMenu(editor: Editor): boolean {
// Mark Toggle Button
// ---------------------------------------------------------------------------
-type InlineMark = "bold" | "italic" | "strike" | "code";
+type InlineMark = "bold" | "italic" | "strike" | "code" | "highlight";
const toggleMarkActions: Record<InlineMark, (editor: Editor) => void> = {
bold: (e) => e.chain().focus().toggleBold().run(),
italic: (e) => e.chain().focus().toggleItalic().run(),
strike: (e) => e.chain().focus().toggleStrike().run(),
code: (e) => e.chain().focus().toggleCode().run(),
+ highlight: (e) => e.chain().focus().toggleHighlight().run(),
};
function MarkButton({
@@ -471,6 +473,7 @@ function EditorBubbleMenu({
italic: e.isActive("italic"),
strike: e.isActive("strike"),
code: e.isActive("code"),
+ highlight: e.isActive("highlight"),
link: e.isActive("link"),
blockquote: e.isActive("blockquote"),
bulletList: e.isActive("bulletList"),
@@ -591,6 +594,7 @@ function EditorBubbleMenu({
<MarkButton editor={editor} mark="italic" icon={Italic} label={t(($) => $.bubble_menu.italic)} shortcut={`${modKey}+I`} isActive={fmt.italic} />
<MarkButton editor={editor} mark="strike" icon={Strikethrough} label={t(($) => $.bubble_menu.strikethrough)} shortcut={`${modKey}+Shift+S`} isActive={fmt.strike} />
<MarkButton editor={editor} mark="code" icon={Code} label={t(($) => $.bubble_menu.code)} shortcut={`${modKey}+E`} isActive={fmt.code} />
+ <MarkButton editor={editor} mark="highlight" icon={Highlighter} label={t(($) => $.bubble_menu.highlight)} shortcut={`${modKey}+Shift+H`} isActive={fmt.highlight} />
<Separator orientation="vertical" className="mx-0.5 h-5" />
<Tooltip>
<TooltipTrigger render={
diff --git a/packages/views/editor/extensions/highlight.test.ts b/packages/views/editor/extensions/highlight.test.ts
new file mode 100644
index 0000000000..8c01aac700
--- /dev/null
+++ b/packages/views/editor/extensions/highlight.test.ts
@@ -0,0 +1,94 @@
+import { describe, it, expect, afterEach } from "vitest";
+import { Editor } from "@tiptap/core";
+import StarterKit from "@tiptap/starter-kit";
+import { Markdown } from "@tiptap/markdown";
+import { HighlightExtension } from "./highlight";
+
+let editor: Editor | null = null;
+
+function makeEditor(markdown: string): Editor {
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+ editor = new Editor({
+ element,
+ extensions: [StarterKit, Markdown, HighlightExtension],
+ });
+ editor.commands.setContent(markdown, { contentType: "markdown" });
+ return editor;
+}
+
+/** Round-trip: load markdown → serialize back to markdown. */
+function roundTrip(markdown: string): string {
+ return makeEditor(markdown).getMarkdown().trim();
+}
+
+afterEach(() => {
+ editor?.destroy();
+ editor = null;
+});
+
+describe("HighlightExtension — markdown serialization (cross-process protocol)", () => {
+ it("round-trips a basic highlight as ==text==", () => {
+ expect(roundTrip("==hi==")).toBe("==hi==");
+ });
+
+ it("round-trips a highlight embedded in a sentence", () => {
+ expect(roundTrip("before ==mid== after")).toBe("before ==mid== after");
+ });
+
+ it("parses ==text== into a highlight mark (<mark> in HTML)", () => {
+ const html = makeEditor("==hi==").getHTML();
+ expect(html).toContain("<mark");
+ expect(html).toContain("hi");
+ });
+
+ it("preserves inner formatting inside a highlight", () => {
+ // bold nested inside highlight must survive the round-trip
+ expect(roundTrip("==**bold**==")).toBe("==**bold**==");
+ });
+
+ it("serializes a highlight applied via the toggleHighlight command", () => {
+ const e = makeEditor("hello");
+ e.commands.selectAll();
+ e.commands.toggleHighlight();
+ expect(e.getMarkdown().trim()).toBe("==hello==");
+ });
+
+ it("leaves a lone == (comparison) untouched", () => {
+ expect(roundTrip("if a == b")).toBe("if a == b");
+ });
+
+ it("does not treat == inside inline code as a highlight", () => {
+ expect(roundTrip("`a ==b== c`")).toBe("`a ==b== c`");
+ });
+
+ // Boundary regressions (Emacs review, PR #3661).
+
+ it("does not let a == inside inline code close the highlight", () => {
+ const e = makeEditor("==a `b==c` d==");
+ const html = e.getHTML();
+ // whole span highlighted; inner `==` stays inside an inline <code>
+ expect(html).toContain("<mark");
+ expect(html).toContain("<code");
+ expect(html).toContain("b==c");
+ // must NOT have stopped at the code's `==`
+ expect(html).not.toMatch(/<mark[^>]*>a\s*$/);
+ expect(e.getMarkdown().trim()).toBe("==a `b==c` d==");
+ });
+
+ it("does not highlight across a blank line (two literal paragraphs)", () => {
+ const e = makeEditor("==a\n\nb==");
+ expect(e.getHTML()).not.toContain("<mark");
+ expect(e.getMarkdown().trim()).toBe("==a\n\nb==");
+ });
+
+ it("does not highlight across a CRLF blank line", () => {
+ const e = makeEditor("==a\r\n\r\nb==");
+ expect(e.getHTML()).not.toContain("<mark");
+ });
+
+ it("still highlights across a CRLF soft line break", () => {
+ const e = makeEditor("==a\r\nb==");
+ expect(e.getHTML()).toContain("<mark");
+ });
+});
diff --git a/packages/views/editor/extensions/highlight.ts b/packages/views/editor/extensions/highlight.ts
new file mode 100644
index 0000000000..4e687bbc38
--- /dev/null
+++ b/packages/views/editor/extensions/highlight.ts
@@ -0,0 +1,56 @@
+import Highlight from "@tiptap/extension-highlight";
+import { matchHighlightAt } from "../utils/highlight-match";
+
+/**
+ * HighlightExtension — text highlight mark (`==text==` ⇄ <mark>).
+ *
+ * Builds on @tiptap/extension-highlight, which already supplies the `<mark>`
+ * parseHTML/renderHTML, the `==text==` input/paste rules, the
+ * setHighlight/toggleHighlight/unsetHighlight commands, and the Mod-Shift-H
+ * shortcut. On top of that we add @tiptap/markdown serialization so highlights
+ * round-trip through the stored Markdown as `==text==`:
+ *
+ * - renderMarkdown: highlight mark → `==…==`. @tiptap/markdown renders marks by
+ * calling renderMarkdown with a placeholder child and splitting the result
+ * into opening/closing fences, so wrapping the placeholder in `==` yields a
+ * `==` open and `==` close.
+ * - markdownTokenizer + parseMarkdown: `==text==` in stored Markdown → highlight
+ * mark. inlineTokens keeps inner inline formatting (e.g. `==**bold**==`).
+ *
+ * Single colour (yellow) for now — `multicolor` stays off. A future multicolour
+ * variant would need a syntax that can carry a colour (`==text==` cannot), so it
+ * is intentionally out of scope here (see MUL-2934).
+ *
+ * BOUNDARY RULES live in utils/highlight-match.ts and are shared with the
+ * read-only renderer (utils/highlight-markdown.ts) so the editor and the
+ * read-only view can never disagree on what counts as a highlight:
+ * - no whitespace directly inside the fences (`==x==` highlights, `== x ==` not)
+ * - non-empty content (`====` stays literal text)
+ * - neither fence may sit inside code/math (a `==` inside `` `code` `` / `$math$`
+ * is literal), so ``==a `b==c` d==`` highlights the whole span, not `a `b`
+ * - a highlight may not cross a blank line / block boundary
+ */
+
+export const HighlightExtension = Highlight.extend({
+ markdownTokenizer: {
+ name: "highlight",
+ level: "inline" as const,
+ start(src: string) {
+ return src.indexOf("==");
+ },
+ tokenize(src: string, _tokens: unknown, helpers: any) {
+ const match = matchHighlightAt(src, 0);
+ if (!match) return undefined;
+ return {
+ type: "highlight",
+ raw: src.slice(0, match.end),
+ tokens: helpers.inlineTokens(match.inner),
+ };
+ },
+ },
+
+ parseMarkdown: (token: any, helpers: any) =>
+ helpers.applyMark("highlight", helpers.parseInline(token.tokens)),
+
+ renderMarkdown: (_node: any, helpers: any) => `==${helpers.renderChildren()}==`,
+}).configure({ multicolor: false });
diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.ts
index 456f3395b3..24d449d149 100644
--- a/packages/views/editor/extensions/index.ts
+++ b/packages/views/editor/extensions/index.ts
@@ -50,6 +50,7 @@ import { createFileUploadExtension } from "./file-upload";
import { FileCardExtension } from "./file-card";
import { ImageView } from "./image-view";
import { BlockMathExtension, InlineMathExtension } from "./math";
+import { HighlightExtension } from "./highlight";
const lowlight = createLowlight(common);
@@ -144,6 +145,7 @@ export function createEditorExtensions(
TableCell,
BlockMathExtension,
InlineMathExtension,
+ HighlightExtension,
// 3-space indent so nested ordered lists survive CommonMark in ReadonlyContent.
Markdown.configure({ indentation: { style: "space", size: 3 } }),
// Make Cmd+C / Cmd+X / drag write Markdown source to clipboard text/plain
diff --git a/packages/views/editor/readonly-content.test.tsx b/packages/views/editor/readonly-content.test.tsx
index 591bb642b9..1e47c40b42 100644
--- a/packages/views/editor/readonly-content.test.tsx
+++ b/packages/views/editor/readonly-content.test.tsx
@@ -126,6 +126,45 @@ describe("ReadonlyContent line breaks", () => {
});
});
+describe("ReadonlyContent highlight Markdown", () => {
+ // `==text==` is lowered to a raw <mark> by highlightToHtml; rehype-raw turns
+ // it into an element and the sanitize schema must whitelist <mark> or it gets
+ // stripped. These guard both halves of that contract.
+ it("renders ==text== as a <mark> element", () => {
+ const { container } = render(<ReadonlyContent content={"a ==hi== b"} />);
+ const mark = container.querySelector("mark");
+ expect(mark).not.toBeNull();
+ expect(mark?.textContent).toBe("hi");
+ });
+
+ it("keeps inner Markdown formatting inside a highlight", () => {
+ const { container } = render(<ReadonlyContent content={"==**bold**=="} />);
+ expect(container.querySelector("mark strong")).not.toBeNull();
+ });
+
+ it("does not highlight == inside inline code", () => {
+ const { container } = render(<ReadonlyContent content={"`a ==b== c`"} />);
+ expect(container.querySelector("mark")).toBeNull();
+ expect(container.querySelector("code")?.textContent).toBe("a ==b== c");
+ });
+
+ // Boundary regressions (Emacs review, PR #3661).
+
+ it("wraps the whole span when an inner == lives in inline code", () => {
+ const { container } = render(<ReadonlyContent content={"==a `b==c` d=="} />);
+ const mark = container.querySelector("mark");
+ expect(mark).not.toBeNull();
+ // inner `==` stays inside the code, not consumed as the closing fence
+ expect(mark?.querySelector("code")?.textContent).toBe("b==c");
+ expect(mark?.textContent).toBe("a b==c d");
+ });
+
+ it("does not highlight across a blank line", () => {
+ const { container } = render(<ReadonlyContent content={"==a\n\nb=="} />);
+ expect(container.querySelector("mark")).toBeNull();
+ });
+});
+
describe("ReadonlyContent issue mention Markdown", () => {
it("renders an issue mention inside a task list as an issue mention card", () => {
const { container, getByTestId } = render(
diff --git a/packages/views/editor/readonly-content.tsx b/packages/views/editor/readonly-content.tsx
index 4f1ac9c9ae..21550c2275 100644
--- a/packages/views/editor/readonly-content.tsx
+++ b/packages/views/editor/readonly-content.tsx
@@ -38,6 +38,7 @@ import { useLinkHover, LinkHoverCard } from "./link-hover-card";
import { openLink, isMentionHref } from "./utils/link-handler";
import { isAllowedFileCardHref } from "@multica/ui/markdown";
import { preprocessMarkdown } from "./utils/preprocess";
+import { highlightToHtml } from "./utils/highlight-markdown";
import { MermaidDiagram } from "./mermaid-diagram";
import { HtmlBlockPreview } from "./html-block-preview";
import { AttachmentDownloadProvider } from "./attachment-download-context";
@@ -64,6 +65,9 @@ const PRE_UNWRAP_RE = /(^|\s)language-(html|mermaid)(\s|$)/;
const sanitizeSchema = {
...defaultSchema,
+ // Allow <mark> (text highlight) — emitted by highlightToHtml from `==text==`.
+ // It carries no attributes, so only the tag name needs whitelisting.
+ tagNames: [...(defaultSchema.tagNames ?? []), "mark"],
protocols: {
...defaultSchema.protocols,
href: [...(defaultSchema.protocols?.href ?? []), "mention", "slash"],
@@ -322,7 +326,10 @@ export const ReadonlyContent = memo(function ReadonlyContent({
className,
attachments,
}: ReadonlyContentProps) {
- const processed = useMemo(() => preprocessMarkdown(content), [content]);
+ const processed = useMemo(
+ () => highlightToHtml(preprocessMarkdown(content)),
+ [content],
+ );
const wrapperRef = useRef<HTMLDivElement>(null);
const hover = useLinkHover(wrapperRef);
diff --git a/packages/views/editor/styles/prose.css b/packages/views/editor/styles/prose.css
index 548a33dcaf..c57181ec28 100644
--- a/packages/views/editor/styles/prose.css
+++ b/packages/views/editor/styles/prose.css
@@ -284,3 +284,16 @@
text-decoration: line-through;
color: var(--muted-foreground);
}
+
+/* Text highlight (`==text==` → <mark>). Single yellow tint that stays legible
+ in both light and dark themes; `color: inherit` keeps the underlying text
+ color so highlighted links/code remain readable. box-decoration-break clones
+ the background across wrapped lines (same approach as inline code above). */
+.rich-text-editor mark {
+ background-color: color-mix(in srgb, #facc15 45%, transparent);
+ color: inherit;
+ border-radius: 0.2em;
+ padding: 0 0.15em;
+ box-decoration-break: clone;
+ -webkit-box-decoration-break: clone;
+}
diff --git a/packages/views/editor/utils/highlight-markdown.test.ts b/packages/views/editor/utils/highlight-markdown.test.ts
new file mode 100644
index 0000000000..7e82fc9e1e
--- /dev/null
+++ b/packages/views/editor/utils/highlight-markdown.test.ts
@@ -0,0 +1,86 @@
+import { describe, it, expect } from "vitest";
+import { highlightToHtml } from "./highlight-markdown";
+
+describe("highlightToHtml", () => {
+ it("lowers a basic highlight to <mark>", () => {
+ expect(highlightToHtml("a ==hi== b")).toBe("a <mark>hi</mark> b");
+ });
+
+ it("keeps inner markdown intact for nested formatting", () => {
+ expect(highlightToHtml("==**bold**==")).toBe("<mark>**bold**</mark>");
+ });
+
+ it("handles multiple highlights on one line", () => {
+ expect(highlightToHtml("==a== and ==b==")).toBe(
+ "<mark>a</mark> and <mark>b</mark>",
+ );
+ });
+
+ it("requires non-space directly inside the fences", () => {
+ expect(highlightToHtml("== spaced ==")).toBe("== spaced ==");
+ });
+
+ it("does not match empty fences", () => {
+ expect(highlightToHtml("====")).toBe("====");
+ });
+
+ it("is a no-op when there is no ==", () => {
+ const md = "plain **bold** _italic_ text";
+ expect(highlightToHtml(md)).toBe(md);
+ });
+
+ it("ignores == inside inline code", () => {
+ expect(highlightToHtml("`a ==b== c`")).toBe("`a ==b== c`");
+ });
+
+ it("ignores == inside fenced code blocks", () => {
+ const md = "```\nx ==y== z\n```";
+ expect(highlightToHtml(md)).toBe(md);
+ });
+
+ it("ignores == inside inline math", () => {
+ expect(highlightToHtml("$a ==b== c$")).toBe("$a ==b== c$");
+ });
+
+ it("highlights outside code while leaving code untouched", () => {
+ expect(highlightToHtml("==hi== `x ==y==`")).toBe(
+ "<mark>hi</mark> `x ==y==`",
+ );
+ });
+
+ it("does not treat a == b (comparison) as a highlight", () => {
+ expect(highlightToHtml("if a == b then")).toBe("if a == b then");
+ });
+
+ // Boundary regressions (Emacs review, PR #3661).
+
+ it("does not let a == inside inline code close the highlight", () => {
+ // The inner `==` lives in inline code; the highlight must wrap the whole
+ // span, not stop at the code's `==`.
+ expect(highlightToHtml("==a `b==c` d==")).toBe(
+ "<mark>a `b==c` d</mark>",
+ );
+ });
+
+ it("does not let a == inside inline math close the highlight", () => {
+ expect(highlightToHtml("==a $b==c$ d==")).toBe(
+ "<mark>a $b==c$ d</mark>",
+ );
+ });
+
+ it("does not highlight across a blank line / block boundary", () => {
+ expect(highlightToHtml("==a\n\nb==")).toBe("==a\n\nb==");
+ });
+
+ it("still highlights across a soft line break within a block", () => {
+ expect(highlightToHtml("==a\nb==")).toBe("<mark>a\nb</mark>");
+ });
+
+ it("does not highlight across a CRLF blank line", () => {
+ expect(highlightToHtml("==a\r\n\r\nb==")).toBe("==a\r\n\r\nb==");
+ });
+
+ it("still highlights across a CRLF soft line break", () => {
+ expect(highlightToHtml("==a\r\nb==")).toBe("<mark>a\r\nb</mark>");
+ });
+});
diff --git a/packages/views/editor/utils/highlight-markdown.ts b/packages/views/editor/utils/highlight-markdown.ts
new file mode 100644
index 0000000000..4129ff6db4
--- /dev/null
+++ b/packages/views/editor/utils/highlight-markdown.ts
@@ -0,0 +1,45 @@
+/**
+ * highlight-markdown — read-only `==text==` → `<mark>text</mark>` transform.
+ *
+ * The editor (Tiptap) parses `==text==` natively via the HighlightExtension's
+ * markdownTokenizer. The read-only surface uses react-markdown, which has no
+ * notion of `==` highlight syntax, so we lower it to a raw `<mark>` element here.
+ * readonly-content.tsx already runs `rehype-raw` (so the raw `<mark>` becomes a
+ * real element) and whitelists `mark` in its sanitize schema. Because the inner
+ * text is left untouched, nested Markdown inside a highlight (e.g. `==**bold**==`
+ * or an inline `` `code` ``) is still parsed by remark — matching the editor.
+ *
+ * The matching rules live in highlight-match.ts and are shared with the editor
+ * tokenizer, so the storage ↔ editor ↔ read-only boundary can never drift:
+ * fences may not sit inside code/math, and a highlight may not cross a blank
+ * line / block boundary.
+ */
+
+import { findLiteralRanges, matchHighlightAt } from "./highlight-match";
+
+/**
+ * Lower `==text==` highlight syntax to raw `<mark>` for the react-markdown
+ * read-only pipeline. No-op when the text contains no `==`.
+ */
+export function highlightToHtml(markdown: string): string {
+ if (!markdown.includes("==")) return markdown;
+ const ranges = findLiteralRanges(markdown);
+
+ let result = "";
+ let cursor = 0;
+ let i = markdown.indexOf("==");
+ while (i !== -1) {
+ const match = matchHighlightAt(markdown, i, ranges);
+ if (match) {
+ result += markdown.slice(cursor, i);
+ result += `<mark>${match.inner}</mark>`;
+ cursor = match.end;
+ i = markdown.indexOf("==", match.end);
+ } else {
+ // Not a highlight here — advance past this `==` and keep looking.
+ i = markdown.indexOf("==", i + 2);
+ }
+ }
+ result += markdown.slice(cursor);
+ return result;
+}
diff --git a/packages/views/editor/utils/highlight-match.test.ts b/packages/views/editor/utils/highlight-match.test.ts
new file mode 100644
index 0000000000..625d082f25
--- /dev/null
+++ b/packages/views/editor/utils/highlight-match.test.ts
@@ -0,0 +1,72 @@
+import { describe, it, expect } from "vitest";
+import { matchHighlightAt, findLiteralRanges } from "./highlight-match";
+
+/** Convenience: match at the first `==` and return the inner text, or null. */
+function inner(text: string): string | null {
+ const i = text.indexOf("==");
+ if (i === -1) return null;
+ const m = matchHighlightAt(text, i);
+ return m ? m.inner : null;
+}
+
+describe("matchHighlightAt", () => {
+ it("matches a basic highlight at the opening fence", () => {
+ const m = matchHighlightAt("==hi==", 0);
+ expect(m).toEqual({ end: 6, inner: "hi" });
+ });
+
+ it("returns null when the opening fence is not at i", () => {
+ expect(matchHighlightAt("x==hi==", 0)).toBeNull();
+ });
+
+ it("rejects whitespace directly inside the fences", () => {
+ expect(inner("== x ==")).toBeNull();
+ });
+
+ it("rejects empty content", () => {
+ expect(inner("====")).toBeNull();
+ });
+
+ it("skips a closing == that sits inside inline code", () => {
+ // ==a `b==c` d== → inner is the whole `a `b==c` d`, not `a `b`
+ expect(inner("==a `b==c` d==")).toBe("a `b==c` d");
+ });
+
+ it("skips a closing == that sits inside inline math", () => {
+ expect(inner("==a $b==c$ d==")).toBe("a $b==c$ d");
+ });
+
+ it("does not open a highlight whose opening == is inside inline code", () => {
+ expect(inner("`x==y==z`")).toBeNull();
+ });
+
+ it("does not cross a blank line", () => {
+ expect(inner("==a\n\nb==")).toBeNull();
+ });
+
+ it("allows a soft line break inside a block", () => {
+ expect(inner("==a\nb==")).toBe("a\nb");
+ });
+
+ it("does not cross a CRLF blank line", () => {
+ expect(inner("==a\r\n\r\nb==")).toBeNull();
+ });
+
+ it("allows a CRLF soft line break inside a block", () => {
+ expect(inner("==a\r\nb==")).toBe("a\r\nb");
+ });
+
+ it("matches the nearest valid closing fence", () => {
+ // first valid close wins; trailing == is left over
+ expect(matchHighlightAt("==a==b==", 0)).toEqual({ end: 5, inner: "a" });
+ });
+});
+
+describe("findLiteralRanges", () => {
+ it("treats == inside a fenced block as literal", () => {
+ const text = "```\n==x==\n```";
+ const ranges = findLiteralRanges(text);
+ const fencePos = text.indexOf("==x==");
+ expect(ranges.some((r) => fencePos >= r.start && fencePos < r.end)).toBe(true);
+ });
+});
diff --git a/packages/views/editor/utils/highlight-match.ts b/packages/views/editor/utils/highlight-match.ts
new file mode 100644
index 0000000000..7291b136ac
--- /dev/null
+++ b/packages/views/editor/utils/highlight-match.ts
@@ -0,0 +1,92 @@
+/**
+ * highlight-match — the single source of truth for what `==text==` highlight
+ * spans look like. BOTH the editor tokenizer (extensions/highlight.ts) and the
+ * read-only lowering (utils/highlight-markdown.ts) use this so the storage ↔
+ * editor ↔ read-only boundary rules can never drift.
+ *
+ * Rules for a highlight `==INNER==`:
+ * - no whitespace directly inside the fences (`==x==` ok, `== x ==` not)
+ * - INNER is non-empty (`====` stays literal)
+ * - neither fence may sit inside a code/math literal span — a `==` inside
+ * inline code/math or a fenced/`$$` block is literal and must not open or
+ * close a highlight (so ``==a `b==c` d=="`` highlights the whole thing, the
+ * inner `==` stays code)
+ * - INNER may not cross a blank line / block boundary (`==a\n\nb==` is two
+ * literal paragraphs, matching how the editor lexes it)
+ */
+
+export interface Range {
+ start: number;
+ end: number;
+}
+
+/**
+ * A blank line: a line break, optional spaces/tabs, then another line break.
+ * Handles both LF and CRLF (Windows / pasted) line endings so the boundary
+ * rule holds regardless of how the content was stored.
+ */
+const BLANK_LINE_RE = /\r?\n[ \t]*\r?\n/;
+
+/**
+ * Spans where `==` must NOT be interpreted as highlight syntax: fenced code,
+ * inline code, and inline/display math. Mirrors the code-range scan in
+ * @multica/ui/markdown's linkify so highlight and autolink skip the same
+ * literal contexts. Earlier (block-level) ranges win so a `==`/backtick inside
+ * a fenced block is not also counted as inline.
+ */
+export function findLiteralRanges(text: string): Range[] {
+ const ranges: Range[] = [];
+ const add = (re: RegExp) => {
+ let m: RegExpExecArray | null;
+ re.lastIndex = 0;
+ while ((m = re.exec(text)) !== null) {
+ const start = m.index;
+ if (ranges.some((r) => start >= r.start && start < r.end)) continue;
+ ranges.push({ start, end: start + m[0].length });
+ }
+ };
+ add(/```[\s\S]*?```/g); // fenced code
+ add(/\$\$[\s\S]*?\$\$/g); // display math
+ add(/(?<!\$)\$(?!\$)[^$\n]+\$(?!\$)/g); // inline math
+ add(/(?<!`)`(?!`)[^`\n]+`(?!`)/g); // inline code
+ return ranges;
+}
+
+function isInside(pos: number, ranges: Range[]): boolean {
+ return ranges.some((r) => pos >= r.start && pos < r.end);
+}
+
+/**
+ * Try to match a highlight whose opening `==` begins at `i`. Returns the
+ * exclusive end offset (just past the closing `==`) and the inner text, or
+ * null if no valid highlight starts here.
+ *
+ * `ranges` may be passed in when the caller already computed literal ranges for
+ * the whole text (read-only path); otherwise they are computed from `text`.
+ */
+export function matchHighlightAt(
+ text: string,
+ i: number,
+ ranges?: Range[],
+): { end: number; inner: string } | null {
+ if (text[i] !== "=" || text[i + 1] !== "=") return null;
+ const innerStart = i + 2;
+ // Non-empty and no whitespace directly after the opening fence.
+ if (innerStart >= text.length) return null;
+ if (/\s/.test(text[innerStart]!)) return null;
+
+ const r = ranges ?? findLiteralRanges(text);
+ if (isInside(i, r)) return null; // opening fence is literal (inside code/math)
+
+ // INNER may not cross a blank line: cap the scan at the first one.
+ const blankRel = text.slice(innerStart).search(BLANK_LINE_RE);
+ const scanLimit = blankRel === -1 ? text.length : innerStart + blankRel;
+
+ for (let j = innerStart + 1; j <= scanLimit && j + 1 < text.length; j++) {
+ if (text[j] !== "=" || text[j + 1] !== "=") continue;
+ if (isInside(j, r)) continue; // closing fence is literal — keep scanning
+ if (/\s/.test(text[j - 1]!)) continue; // no whitespace directly before fence
+ return { end: j + 2, inner: text.slice(innerStart, j) };
+ }
+ return null;
+}
diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.json
index 3b73ec9c2b..c6ab0d0f38 100644
--- a/packages/views/locales/en/editor.json
+++ b/packages/views/locales/en/editor.json
@@ -4,6 +4,7 @@
"italic": "Italic",
"strikethrough": "Strikethrough",
"code": "Code",
+ "highlight": "Highlight",
"link": "Link",
"list": "List",
"quote": "Quote",
diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.json
index 504ff7631c..950f44cadb 100644
--- a/packages/views/locales/ja/editor.json
+++ b/packages/views/locales/ja/editor.json
@@ -4,6 +4,7 @@
"italic": "斜体",
"strikethrough": "取り消し線",
"code": "コード",
+ "highlight": "ハイライト",
"link": "リンク",
"list": "リスト",
"quote": "引用",
diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.json
index 51d93c1d59..e2e608f736 100644
--- a/packages/views/locales/ko/editor.json
+++ b/packages/views/locales/ko/editor.json
@@ -4,6 +4,7 @@
"italic": "기울임",
"strikethrough": "취소선",
"code": "코드",
+ "highlight": "강조",
"link": "링크",
"list": "목록",
"quote": "인용",
diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.json
index ec715e6c65..6672a72f3d 100644
--- a/packages/views/locales/zh-Hans/editor.json
+++ b/packages/views/locales/zh-Hans/editor.json
@@ -4,6 +4,7 @@
"italic": "斜体",
"strikethrough": "删除线",
"code": "代码",
+ "highlight": "高亮",
"link": "链接",
"list": "列表",
"quote": "引用",
diff --git a/packages/views/package.json b/packages/views/package.json
index 90ee49dd5d..e5e5e3ca34 100644
--- a/packages/views/package.json
+++ b/packages/views/package.json
@@ -63,6 +63,7 @@
"@tiptap/core": "^3.22.1",
"@tiptap/extension-code-block-lowlight": "^3.22.1",
"@tiptap/extension-document": "^3.22.1",
+ "@tiptap/extension-highlight": "3.22.1",
"@tiptap/extension-image": "^3.22.1",
"@tiptap/extension-link": "^3.22.1",
"@tiptap/extension-list": "^3.22.1",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 89c49482e7..ca4374b2b1 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -972,6 +972,9 @@ importers:
'@tiptap/extension-document':
specifier: ^3.22.1
version: 3.22.1(@tiptap/[email protected](@tiptap/[email protected]))
+ '@tiptap/extension-highlight':
+ specifier: 3.22.1
+ version: 3.22.1(@tiptap/[email protected](@tiptap/[email protected]))
'@tiptap/extension-image':
specifier: ^3.22.1
version: 3.22.1(@tiptap/[email protected](@tiptap/[email protected]))
@@ -4059,6 +4062,11 @@ packages:
peerDependencies:
'@tiptap/core': ^3.22.1
+ '@tiptap/[email protected]':
+ resolution: {integrity: sha512-3XH0HWViJVzr+FUZY/HQn2vasOgOssVlOjdirKck9AmHoDFUceJbAygSJIdj2fZF3RQl0ohjMGi+OpGMVJ83sw==}
+ peerDependencies:
+ '@tiptap/core': ^3.22.1
+
'@tiptap/[email protected]':
resolution: {integrity: sha512-Q18A8IN+gnfptIksPeVAI6oOBGYKAGf+QN0FEJ5OXO4BEAmA3hflflA1rWNfPC4aQNry/N7sAl8Gpd6HuIbz2w==}
peerDependencies:
@@ -14160,6 +14168,10 @@ snapshots:
dependencies:
'@tiptap/core': 3.22.1(@tiptap/[email protected])
+ dependencies:
+ '@tiptap/core': 3.22.1(@tiptap/[email protected])
+
dependencies:
'@tiptap/core': 3.22.1(@tiptap/[email protected])