Skip to content

fix: preserve empty list items when serializing markdown - #4691

Closed
Renakoni wants to merge 1 commit into
marktext:developfrom
Renakoni:fix/empty-list-items
Closed

Renakoni wants to merge 1 commit into
marktext:developfrom
Renakoni:fix/empty-list-items

Conversation

@Renakoni

Copy link
Copy Markdown
Contributor

Closes #4679

Summary

Fix Markdown serialization for empty list items.

Previously, an empty list item emitted only its marker, for example - , without a terminating newline. In a tight list, adjacent empty list items were then concatenated into one physical Markdown line.

For example:

- 
- 
- 

z

could be serialized as:

- - - 
z

After reopening the document, CommonMark parses - - - as a thematic break, so the original list structure is lost. A similar issue happens when an empty item appears between populated sibling items, where the following sibling can be reparsed as a nested list item.

This PR fixes the serializer invariant directly: a list item with no children still terminates its own Markdown line.

Type of change

  • Bug fix (non-breaking, fixes an issue)
  • New feature (non-breaking, adds functionality)
  • Breaking change (causes existing functionality to change)
  • Documentation update

Test plan

  • New tests added (or explain why not needed)
  • Manually tested on: Windows 11 Pro 10.0.26200 with MarkText 0.20.0-beta.2 to reproduce the original issue; fix verified with targeted unit tests on develop.

Test command:

pnpm --filter @muyajs/core exec vitest run src/state/__tests__/listSerialization.spec.ts

Result:

Test Files  1 passed (1)
Tests       22 passed (22)

Additional Playwright validation:

  • Started the Muya e2e host in Chromium.
  • Loaded the two issue examples into the editor.
  • Performed a real keyboard edit (z -> zy, c -> cx).
  • Verified window.muya.getMarkdown() preserved the empty list item lines.
  • Re-loaded the saved Markdown and verified the parsed state remained a 3-item bullet list, with no thematic break and no unintended nested list.

Notes for reviewers [optional]

The root cause is in packages/muya/src/state/stateToMarkdown.ts.

_serializeListItem() wrote the item marker first and then appended the serialized children:

result.push(`${indent}${itemMarker}`);
result.push(
    this._convertStatesToMarkdown(children, newIndent, listIndent).substring(
        newIndent.length,
    ),
);

For an empty list item, children is an empty array, so _convertStatesToMarkdown([]) returns an empty string. The serialized output for that item was therefore only the marker with no trailing newline.

The fix is intentionally small: if a list item has no children, return ${indent}${itemMarker}\n before entering the normal child serialization path.

Regression tests cover:

  • Adjacent empty bullet items remaining separate lines after serialization.
  • An empty bullet item between populated sibling items remaining a sibling, not turning the following item into a nested list.

By submitting this pull request, I confirm that my contribution is made under the terms of the MIT license.

Copilot AI review requested due to automatic review settings June 24, 2026 16:01

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes a Markdown round-trip corruption bug in @muyajs/core where empty list items were serialized without a terminating newline, causing adjacent empty items to be concatenated (and potentially re-parsed as a thematic break or unintended nesting) on reload.

Changes:

  • Ensure _serializeListItem() emits a trailing \n when a list item has no children.
  • Add regression tests covering adjacent empty bullet items and an empty bullet item between populated siblings.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
packages/muya/src/state/stateToMarkdown.ts Adds an early return to serialize empty list items as their marker plus a newline, preventing line concatenation.
packages/muya/src/state/tests/listSerialization.spec.ts Adds targeted round-trip + reparse tests to prevent regressions for empty list item serialization.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@Jocs Jocs left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: the fix is correct, but it treats a symptom — the root cause is one level deeper, in markdownToState

First, credit where it's due: this PR fixes the reported data loss (#4679), is minimal, and ships real regression tests that genuinely fail without the change. The serializer guard is a valid backstop. But I think the actual root cause lives in the parser, and fixing it there is cleaner and closes a sibling bug that the serializer patch leaves open.

The invariant: a muya list-item should never have empty children

An empty list-item (children: []) is a degenerate state the rest of the engine doesn't expect:

  • The parser already does the right thing for blockquotes. In markdownToState.ts, the block-end handler synthesizes an empty paragraph for an empty blockquote (#1735):
    if (parentList[0].length === 0 && token.tokenType === 'blockquote') {
        state = { name: 'paragraph', text: '' }
        parentList[0].push(state)
    }
    The list-item block-end does not do this. The asymmetry looks like an oversight, not a deliberate design difference.
  • The editor enforces the invariant everywhere else. Fresh list creation always inserts a paragraph child even when the content is empty, and #4644 had to add a guard in the Enter-split handler (paragraphContent/index.ts, from = offset === 0 ? 1 : offset) precisely to avoid leaving behind a childless item.
  • ListItem.create has no guard (block/commonMark/listItem/index.ts): it maps state.children straight to blocks, so a children: [] state builds an <li> with no content leaf.

The same root cause is two bugs, not one

The serializer collapse (#4679) and a navigation failure on load share this root cause. Because ListItem.create faithfully builds a childless <li>, opening a document that contains empty list items yields items with no content descendant — the exact shape #4644 identifies as making previousContentInContext() / nextContentInContext() return null, so the arrow keys can't move through them. The serializer fix here does nothing for that path; a parser fix fixes both.

Verified: fixing it in the parser is clean and lower-risk

I prototyped the parser fix (mirror the #1735 synthesis for list-item in the block-end handler — a one-line condition) and ran it with the serializer left completely untouched:

  • An empty item now parses to list-item > paragraph(''), restoring the invariant.
  • Round-trip is identity for adjacent empties, an empty item between siblings, and empty ordered items — the existing serializer already emits - \n correctly for an empty-paragraph item, so no serializer special-case is needed at all.
  • Test results: roundTrip.spec.ts 15/15, state/__tests__ (markdownToState + listSerialization + nestedMixedLists) 49/49, and CommonMark conformance 652/652.
  • No conformance risk: renderToStaticHTML → getHighlightHtml → marked, which bypasses the state tree entirely, so changing markdownToState cannot move conformance (confirmed by reading the path and by the 652/652 run).

Recommendation

  • Move the fix into markdownToState (the block-end handler): synthesize an empty paragraph for an empty list-item, mirroring the existing #1735 blockquote handling. This fixes #4679 and the on-load navigation symptom in one place, at the right altitude.
  • Optionally keep a serializer guard as defense-in-depth — childless items can still arrive via OT ops / paste / programmatic state — but frame it as defensive rather than the primary fix.
  • If you adopt the parser fix, the test that currently asserts expect(list.children[1].children).toHaveLength(0) should become toHaveLength(1) (the synthesized empty paragraph). That is the corrected invariant.

One edge-case caveat worth checking whichever way you go: the two approaches are not byte-identical at the boundaries — an empty task item serializes as - [x] \n (trailing space) via this serializer patch, but as - [x]\n (no trailing space) via the parser path. So the task/ordered cases deserve their own explicit assertions.

@Jocs

Jocs commented Jun 26, 2026

Copy link
Copy Markdown
Member

@Renakoni I found #4696 contains the code of this PR?

@Renakoni

Copy link
Copy Markdown
Contributor Author

Yes, you're right. #4696 independently includes the same production-side serialization guard in stateToMarkdown.ts:

if (!children.length)
    return `${indent}${itemMarker}\n`;

That is equivalent to this PR's children.length === 0 check, so the core fix from this PR is already covered there.

The two branches are not actually based on each other; they diverged from the same base. This PR was focused only on
plain empty bullet-list item serialization, while #4696 also handles the related empty task-list parsing/rendering
edge cases.

I'll close this PR in favor of #4696. The only extra value here was the additional plain bullet-list regression
coverage, which can be added to #4696 if you think those cases are still useful.

@Renakoni Renakoni closed this Jun 26, 2026
@Jocs

Jocs commented Jun 26, 2026

Copy link
Copy Markdown
Member

I prefer add the test and include the fixed issue in #4696

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Empty list items are serialized onto one line after editing, corrupting the document on reload

3 participants