comark icon indicating copy to clipboard operation
comark copied to clipboard

renderMarkdown breaks headings and inline components that have no text sibling

Open 0z5a opened this issue 1 week ago • 0 comments

Environment

  • Operating System: Darwin
  • Node Version: v24.14.1
  • Package Manager: pnpm@10
  • Comark Version: 0.9.2 (also current main, 74ba41b)
  • Framework: None

Comark Version

v0.9.2

Reproduction

import { parseMarkdown } from 'comark'
import { renderMarkdown } from 'comark/render'

for (const input of ['## [Unreleased]', '# :badge[New]', '**Note**:badge[beta]', '[a]{.x}[b]{.y}']) {
  console.log(JSON.stringify(await renderMarkdown(await parseMarkdown(input))))
}

Output:

"[Unreleased]\n\n\n---"
"::badge\n  New\n  ::\n\n\n==="
"**Note**  ::badge\n  beta\n  ::"
"[a]{.x}\n\n[b]{.y}"

Description

renderMarkdown writes a span or inline component as a block when it is the only child of a heading, or when its siblings are elements but no text. Parsing the output again gives a different document:

  • ## [Unreleased] comes back as a paragraph [Unreleased] followed by a thematic break. The heading is gone. This is the heading Keep a Changelog uses, so a changelog round-tripped through Comark loses it.
  • # :badge[New] becomes a ::badge block followed by a lone ===.
  • **Note**:badge[beta] turns into **Note** ::badge ..., and the badge is no longer a badge when parsed again.
  • [a]{.x}[b]{.y} is split into two paragraphs.
  • The same happens inside a table cell: | *Status*:badge[ok] | comes back as | *Status* ::badge ok :: |, which doesn't parse back to the badge.

## [1.0.0] - 2026-11-21 is fine, because the span has a text sibling.

Cause, from reading src/internal/stringify/handlers/mdc.ts: a component or span is written inline when it has a string sibling, when its parent is in INLINE_HTML_ELEMENTS (a, strong, em, span), or when the context is already inline. A heading, paragraph or table cell isn't in that set. With no text sibling the node gets the block form, and heading.ts then sees a newline in the content and writes a setext heading. format: 'markdown/html' has the same gap in handlers/html.ts, which treats a p or inline-tag parent as inline but not a heading or table cell: # :badge[New] becomes <badge>\n\nNew\n\n</badge>\n===.

I found it with a parse → render → parse round-trip test over short generated inputs. I haven't seen a field report.

I have a fix ready: treat p, h1–h6, th and td as inline parents in both handlers, plus two SPEC fixtures. Happy to open a PR.

Additional context

With that change, all the inputs above round-trip unchanged.

0z5a avatar Nov 21 '26 15:11 0z5a