From e7aec17d467910576207c51f476966397f7ab6b3 Mon Sep 17 00:00:00 2001 From: faysou Date: Fri, 20 Nov 2026 19:56:06 +0000 Subject: [PATCH] Match backtick runs in protected inline Markdown math (#4895) Protected inline math ($`...`$) now matches the opening backtick run to the first closing run of the same length, as Markdown code spans do: ($``x` + y``$) renders as math, while ($`x` `y`$) keeps two code spans and literal dollars. Co-authored-by: faysou <893862+faysou@users.noreply.github.com> Co-authored-by: faysou <893862+faysou@users.noreply.github.com> --- src/editor/lsp/markdownMath.test.ts | 11 +++++++++++ src/editor/lsp/markdownMath.ts | 7 ++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/editor/lsp/markdownMath.test.ts b/src/editor/lsp/markdownMath.test.ts index 2be1e9189..66a79c992 100644 --- a/src/editor/lsp/markdownMath.test.ts +++ b/src/editor/lsp/markdownMath.test.ts @@ -37,6 +37,17 @@ describe("markdown LaTeX math", () => { expect(root.querySelector("p")?.textContent?.startsWith("Prices $5 and $10, with ")).toBe(true); }); + it("leaves separate code spans inside dollar signs as code", () => { + const root = parseSafe("($`x` `y`$)"); + expect(root.querySelector("p")?.innerHTML).toBe("($x y$)"); + }); + + it("matches a longer backtick delimiter around math inside emphasis", () => { + const root = parseSafe("**($``x` + y``$)**"); + expect(root.querySelector("strong .katex annotation")?.textContent).toBe("x` + y"); + expect(root.querySelector("code")).toBeNull(); + }); + it("keeps an unfinished protected delimiter from swallowing a later formula", () => { const root = parseSafe("Unfinished $`x` and $y$."); expect(root.querySelector("p > code")?.textContent).toBe("x"); diff --git a/src/editor/lsp/markdownMath.ts b/src/editor/lsp/markdownMath.ts index f8da1e679..5c2c60a00 100644 --- a/src/editor/lsp/markdownMath.ts +++ b/src/editor/lsp/markdownMath.ts @@ -39,9 +39,10 @@ function findClosingDelimiter(src: string, from: number, delim: string): number return -1; } -const PROTECTED_INLINE_DOLLAR = /^\$`([^`\r\n]+)`\$/; +// The first backtick run of the opening length ends the code span. +const PROTECTED_INLINE_DOLLAR = /^\$(?`+)(?!`)(?(?:[^`\r\n]|(?!\k(?!`))`+(?!`))+)\k\$/; // Marked masks code spans as `[aaa]` before calling emStrongMask -const MASKED_PROTECTED_INLINE_DOLLAR = /^\$\[(a+)\]\$/; +const MASKED_PROTECTED_INLINE_DOLLAR = /^\$\[(?a+)\]\$/; /** * Matches inline `$...$` from index 0 using Pandoc-style guards so currency @@ -87,7 +88,7 @@ function matchInlineMath( if (src[0] === "$") { const match = protectedDollar.exec(src); if (match) { - const text = match[1]!; + const text = match.groups!.tex!; return text.trim() ? { raw: match[0], text, display: false } : null; } if (src[1] === "`") return null;