QLMarkdown icon indicating copy to clipboard operation
QLMarkdown copied to clipboard

Fix inline math extension false positive on currency $ signs

Open RayCharlizard opened this issue 7 months ago • 2 comments

Summary

Fixes #195. The bug had three layers; this PR addresses all three.

Layer 1 — cmark-extra parse: don't match currency as math

Apply pandoc inline-math flanking rules in cmark-extra/extensions/math_ext.c: opening $ must be followed by a non-space, closing $ must be preceded by a non-space and not followed by a digit. This prevents $1.50 ... $7.89 from being matched as $1.50 ... $7.89 (a math span) at parse time.

Layer 2 — Swift gate: don't load MathJax for currency-only files

Settings+render.swift previously gated MathJax injection on rendered_count > 0 || body.contains("$"). The body.contains("$") fallback caused MathJax to load in the WebView for any document containing $ — including currency-only documents. Once MathJax loaded with its default config (inlineMath: [['$', '$']]), it scanned the DOM client-side and re-matched every dollar pair as math, undoing Layer 1's work for the preview path. Dropped the fallback; rendered_count from cmark is now the sole gate.

Layer 3 — MathJax delimiter swap: handle mixed math + currency

For files that contain both real math and currency, Layer 2 isn't enough — rendered_count > 0 because of the real math, so MathJax still loads, and its $...$ default delimiters still re-match currency client-side.

This PR's third commit configures MathJax to use the LaTeX-canonical \(...\) / \[...\] delimiters as the only delimiters, and post-processes the rendered body in Swift (swapMathDelimiters) to rewrite the $...$ / $$...$$ inside cmark-extra's <span class='hl math'> / <div class='hl math'> wrappers. Stray $ outside those wrappers (currency, prose, code) is now invisible to MathJax.

The post-process is in Swift rather than in cmark-extra so the C library's output contract stays stable for any other downstream consumer. The regex uses a </span> / </div> trailing anchor that cannot be forged from inside math content because html_render_math entity-escapes < to &lt;. A defensive os_log(.error) fires if any math span survives the rewrite — silent typesetting failure becomes loud.

Cosmetic side effect (no functional impact)

Raw HTML output from qlmarkdown_cli and the Shortcuts Extension (MdToHtml_Extension, MdToHtmlCode_Extension) now contains \(...\) / \[...\] inside <span class='hl math'> / <div class='hl math'> blocks instead of $...$ / $$...$$. Both render identically under MathJax. WebView consumers (Quick Look preview, in-app preview, share preview) are unaffected visually.

Test plan

  • [x] Currency-only file (no math at all): renders as plain currency. MathJax not loaded.
  • [x] Real inline math ($E=mc^2$): typesets.
  • [x] Display math ($$\int...$$): typesets.
  • [x] Fenced ```math block: typesets.
  • [x] Mixed file (real math AND currency in the same document): math typesets AND currency renders as plain text.
  • [x] HTML-special chars inside math ($a < b$, $x > 0$, $a \& b$): all typeset.
  • [x] Multiline display math: typesets.
  • [x] Two inline math expressions on one line: both typeset independently.
  • [x] CLI sanity: <span class='hl math'>\(E = mc^2\)</span> and inlineMath: [['\\(', '\\)']] both visible in qlmarkdown_cli output.
  • [x] Verified on live build under macOS Quick Look.

RayCharlizard avatar Apr 19 '26 06:04 RayCharlizard

@sbarex — heads up, I've pushed a follow-up commit (f632da3) and updated the PR description.

While running the original parser fix against a live build I noticed the QuickLook preview still mangled currency, even with cmark emitting clean HTML. Root cause was a second gate in QLMarkdown/Settings+render.swift that injected MathJax into the WebView whenever the rendered body contained any $ character — so MathJax then re-matched every $...$ pair client-side, regardless of what cmark did. With the pandoc-rules parser fix in place, cmark_syntax_extension_math_get_rendered_count is now reliable, so the || body.contains("$") fallback can be dropped and the gate becomes truthful.

One known limitation is documented in the code and in the PR description: documents mixing real math and currency in the same file still mangle the currency, because once MathJax loads it re-scans the whole page. Resolving that is a larger change (body post-process or switching to \(...\) delimiters) and I left it as a follow-up rather than bundling it in here.

Verified locally on macOS with a fresh build — currency-only documents produce zero MathJax injections, and a synthetic file with $x+y$, $\alpha$, and $$\sqrt{x+2}$$ typesets correctly. Let me know if you'd like me to split this into two PRs or adjust anything.

RayCharlizard avatar May 13 '26 23:05 RayCharlizard

Quick heads-up — pushed one more commit (548ec69) that closes the mixed-content limitation I'd flagged in the previous comment.

What it does: swaps MathJax's inline/display delimiters to \(...\) / \[...\] (the LaTeX-canonical pair) and post-processes the rendered body in Swift so only the <span class='hl math'> / <div class='hl math'> wrappers cmark-extra emits get their delimiters rewritten. Currency and prose stay untouched. The third layer of the fix that finally makes the mixed math + currency case work.

Why post-process in Swift, not cmark-extra: to keep the C library's output contract stable for any other downstream consumer — the rewrite is a presentation concern specific to the WebView preview, not a parse decision. Happy to move it into cmark-extra if you'd rather, but this seemed the lower-risk layer.

Cosmetic note for reviewers: raw HTML from qlmarkdown_cli and the Shortcuts Extension now contains \(...\) / \[...\] inside math wrappers instead of $...$ / $$...$$. Both render identically under MathJax. WebView consumers see no difference.

Verified on a live build:

  • Currency-only files: no MathJax injected, currency intact.
  • Math-only files (inline, display, fenced ```math): all typeset correctly with the new delimiters.
  • Mixed files (real math + currency together): math typesets AND currency renders as plain text.
  • Edge cases: HTML-escaped chars inside math, multiline display math, two inline expressions on one line, math with embedded \$ — all pass.

A defensive os_log(.error) is wired in for the unlikely case that a future cmark-extra change emits math wrappers the regex doesn't recognize, so any future regression would be loud rather than silent.

PR description has been updated with the full three-layer story. Let me know if you want any of it split into separate PRs or want the cmark-extra-side approach instead.

RayCharlizard avatar May 14 '26 00:05 RayCharlizard

Built this branch locally (QLMardown Debug) and tested against the issue's repro plus a few math cases — the fix holds up.

Currency no longer becomes math:

  • the repro line (… $1,667.84 net) lives in [ + "sales-history.md" + ](…) … derived $/hr …) now renders as plain text, with the link and inline-code intact — previously everything from $1,667.84 through $/hr was swallowed into a single math node.
  • $1,000 and $2,000 → both plain text.
  • I paid $5 … $E=mc^2$ → only $E=mc^2$ is math; the $5 stays plain.

Legitimate math still renders:

  • $x+y$, $\alpha$, $100/2$, $E=mc^2$ → all become \(…\) inline math.

The two layers work together as intended: the pandoc-style opener/closer rules stop currency $ from pairing at parse time, and the \(…\) delimiter swap keeps MathJax's client-side scan from re-matching $ in the rendered DOM. No regressions on the cases I tried. 👍

soreavis avatar Jun 28 '26 12:06 soreavis