Skip to content

Bug: @lexical/markdown text-format combination #2632

Closed

Description

@hanford

When hydrating a lexical editor with the following markdown **Bold *Italic*** calling $convertFromMarkdownString should properly format this as bold & and bold italic text. However, for some reason, it doesn't, and the rendered result is Bold *Italic*

This seems to work when switching between editor content and markdown in the playground, but it does not work when initializing the playground with this content.

Lexical version: 3.8

Steps To Reproduce

  1. Have a lexical instance with initialEditorState that invokes $convertFromMarkdownString('**Bold *Italic***')
  2. See the content be rendered in editor as Bold *Italic* rather than the expected Bold Italic

Link to code example:

https://codesandbox.io/s/many-lexical-autofocus-forked-efq8sq?file=/src/App.js

The current behavior

Content is Bold and asterisks are rendered in editor

The expected behavior

Content should be Bold and Italic text should be italicized

--

Happy to share any more information if it's useful

Activity

  1. hanford commented on Jul 27, 2022

    @hanford
    ContributorAuthor

    Narrowed the issue down to a bug in this function, where when splitText is called, it can break up markdown format syntax so it's not formatted...

    i.e. the following markdown syntax will never be imported correctly:

    *Foo **Bar***
    **Foo *Bar***
    _Foo __bar___
    __Foo _bar___
    

    When findOutermostMatch is called on the above pieces of markdown, it wrongly identifies the outer most pieces of markdown, causing the other contents to then be "split" and subsequent formatting is never formatted correctly

    In the first case, *Foo **Bar***, findOutermostMatch wrongly returns **Bar**, then splitText is called, and the leadingNode and remainingNode are *Foo and * respectively, causing lexical to then render

    image

    --

    I tried modifying the code to look something like this:

    const possibleMatches = Object.keys(textFormatTransformersIndex.fullMatchRegExpByTag)
    
    if (leadingNode || remainderNode) {
      const leaderContainsPossibleFormat = possibleMatches.some(k=> leadingNode?.getTextContent().includes(k))
      const remainderContainsPossibleFormat = possibleMatches.some(k=> remainderNode?.getTextContent().includes(k))
    
      if (leaderContainsPossibleFormat && remainderContainsPossibleFormat) {
        currentNode.mergeWithSibling(leadingNode)
        currentNode.mergeWithSibling(remainderNode)
    
        importTextFormatTransformers(currentNode, textFormatTransformersIndex, textMatchTransformers);
      } else if (leaderContainsPossibleFormat) {
        leadingNode.mergeWithSibling(currentNode)
    
        importTextFormatTransformers(leadingNode, textFormatTransformersIndex, textMatchTransformers);
      } else if (remainderContainsPossibleFormat) {
        currentNode.mergeWithSibling(remainderNode)
    
        importTextFormatTransformers(currentNode, textFormatTransformersIndex, textMatchTransformers);
      }
    }
    

    However, mergeWithSiblings seems to combine formats in a way creates a separate bug, *Foo **Bar*** being both entirely bold and italic, whereas the desired is Foo not being bolded

    --

    I wonder if the next best approach would be modifying or creating more regex's that capture both the beginning formatters, *,**,***,.. etc .. as well as trying to capture the last possible instance. i.e. scan currentNode for * if we see it, try match everything to the last * on the line

  2. fantactuka commented on Jul 28, 2022

    @fantactuka
    Contributor

    @hanford Thanks for digging into it! Was suspecting findOutermostMatch is not working correctly but didn't get a chance to play with regExp. The question is if it's even possible with regExp only. Especially for cases like above when *** is a closing tag for separate * and **. So the logic would be if we have * and ** opened, then the next *** is their combined closing tag, and we don't need to look for any * or ** further.

    Maybe getting all tags matches (with its corresponding matching indices) and then walking through that list, so that we have info of currently started tags which can be used to distinguish between *** being a single tag or two combined closing tags

  3. hanford commented on Aug 3, 2022

    @hanford
    ContributorAuthor

    refs #2303

  4. focux commented on Jan 12, 2023

    @focux
    Contributor

    I'm having this same issue when using bold and italics, however, in your case bold was still working but not italics, and now, none of them is working, seems like something broke in the latest version, here is a reproduction:

    https://codesandbox.io/s/lexical-bold-and-italics-not-working-99cg7q

  5. 777PolarFox777 commented on Aug 11, 2023

    @777PolarFox777

    Looks like there's also an issue when you apply bold/italic on a line that has a a space character after an emoji in the end:
    image

    image

    Not sure if it's a new issue or related

  6. bruno-kumo commented on Mar 14, 2024

    @bruno-kumo

    Hi, are there any updates on this? I've been running into the same bug

  7. aklatzke-kraftful commented on Mar 22, 2024

    @aklatzke-kraftful

    For anyone running into this issue, here's a workaround you may be able to use.

    For me, this was manifesting as the following:

    • Create some bold/italic text in an editor as part of a paragraph
    • Export to markdown, using the provided plugin utilities ($convertToMarkdownString)
    • Reload the editor
    • The text is now gone because it was parsed incorrectly using the provided utility ($convertFromMarkdownString)
    • Subsequent auto-save would wipe the text from the document

    To workaround this, I used the alternate markdown syntax for bold/italics (___ instead of ***) and implemented it in a custom transformer.

    import { Transformer } from "@lexical/markdown";
    import { $createTextNode, $isTextNode, LexicalNode, TextNode } from "lexical";
    
    function $createBoldItalicNode(text?: string) {
      const node = $createTextNode(text);
      node.toggleFormat("bold");
      node.toggleFormat("italic");
      return node;
    }
    
    function $isMarkdownBoldItalicNode(node: LexicalNode): boolean {
      return $isTextNode(node) && node.hasFormat("bold") && node.hasFormat("italic");
    }
    
    export const BOLD_ITALIC_TRANSFORMER: Transformer = {
      export: (node) => {
        if (!$isMarkdownBoldItalicNode(node)) {
          return null;
        }
    
        return `___${node.getTextContent()}___`;
      },
      dependencies: [TextNode],
      regExp: /___(.+?)___/,
      importRegExp: /___(.+?)___/,
      trigger: "___",
      replace: (parentNode, match) => {
        const [, text] = match;
        parentNode.replace($createBoldItalicNode(text));
      },
      type: "text-match",
    };

    Then registered this as the first transformer:

    export const TRANSFORMER_COLLECTION = [
      BOLD_ITALIC_TRANSFORMER,
      ...TRANSFORMERS,
    ];

    This fixed the editor issue, you just need to ensure everything else in your pipeline supports the ___ syntax for the formatting.

  8. etrepum commented on Dec 16, 2024

    @etrepum
    Collaborator

    Should be fixed by #5758

  9. AlexandrDubovchenko commented on Nov 7, 2025

    @AlexandrDubovchenko

    Still have same issue.

    Steps to reproduce:

    Provide $convertFromMarkdownString with BoldItalic

    Result is: Bold *Italic*

    Lexical version: 0.38.2

    @etrepum @yhw5 Please check

  10. Yith1 commented on Jan 13, 2026

    @Yith1

    Still have same issue.

    Steps to reproduce:

    Provide $convertFromMarkdownString with Bold_Italic_

    Result is: Bold Italic

    Lexical version: 0.38.2

    @etrepum @yhw5 Please check

    Also still having this issue using Lexical 0.39.0.

    I asked Claude to do some analysis of the problem. Apologies if it has hallucinated. Here is it's output:

    Test Cases

    import { $convertFromMarkdownString } from "@lexical/markdown";
    import { $getRoot } from "lexical";
    
    // ✅ WORKS: Simple cases
    $convertFromMarkdownString("*italic*", TRANSFORMERS);
    // Result: <em>italic</em> ✓
    
    $convertFromMarkdownString("**bold**", TRANSFORMERS);
    // Result: <strong>bold</strong> ✓
    
    $convertFromMarkdownString("***bold and italic***", TRANSFORMERS);
    // Result: <em><strong>bold and italic</strong></em> ✓
    
    // ✅ WORKS: Properly balanced nesting
    $convertFromMarkdownString("**bold with *italic* inside**", TRANSFORMERS);
    // Result: <strong>bold with <em>italic</em> inside</strong> ✓
    
    $convertFromMarkdownString("*italic with **bold** inside*", TRANSFORMERS);
    // Result: <em>italic with <strong>bold</strong> inside</em> ✓
    
    // ❌ FAILS: Overlapping delimiters (opener before opener, closer after closer)
    $convertFromMarkdownString("ggggg*jhhhh**dsjdhjdj***", TRANSFORMERS);
    // Expected: ggggg<em>jhhhh<strong>dsjdhjdj</strong></em>
    // Actual: ggggg*jhhhh<strong>dsjdhjdj</strong>* ✗

    Root Cause Analysis

    After investigating the @lexical/markdown source code, the issue appears to be in the findOutermostMatch function in LexicalMarkdown.dev.js (lines 308-340).

    The Algorithm Flaw

    The current algorithm:

    1. Finds all opening tags using openTagsRegExp in a left-to-right scan
    2. For each opening tag (in order of appearance), tries to match its full pattern
    3. Returns the first successful match

    This is a greedy left-to-right approach that doesn't respect CommonMark's emphasis delimiter matching rules.

    Why It Fails on *jhhhh**dsjdhjdj***

    1. Scanner finds * at position 5, ** at position 11
    2. Tries to match *...* for position 5 → NO MATCH (finds *jhhhh** which has ** at the end)
    3. Tries to match **...** for position 11 → MATCH! (**dsjdhjdj**)
    4. Applies bold formatting, leaving *jhhhh and * as literal characters

    CommonMark's Algorithm

    Per the CommonMark spec, emphasis delimiter matching should:

    1. Identify delimiter runs and apply flanking rules
    2. Process emphasis from innermost to outermost
    3. Match delimiters based on precedence (*** before ** before *)
    4. Handle overlapping by respecting the delimiter stack

    The CommonMark algorithm is significantly more complex than Lexical's current implementation. See CommonMark spec section 6.2 for the full algorithm.

    Reproduction

    Minimal Test Case

    import { createHeadlessEditor } from '@lexical/headless';
    import { $convertFromMarkdownString, TRANSFORMERS } from '@lexical/markdown';
    import { $getRoot } from 'lexical';
    
    const editor = createHeadlessEditor({
      nodes: [],
      onError: (error) => console.error(error),
    });
    
    editor.update(() => {
      $convertFromMarkdownString('ggggg*jhhhh**dsjdhjdj***', TRANSFORMERS);
      const root = $getRoot();
      console.log(root.getTextContent()); // Shows: ggggg*jhhhhdsjdhjdj*
    });

    Automated Test

    describe('@lexical/markdown emphasis parsing', () => {
      test('should handle overlapping emphasis delimiters per CommonMark spec', () => {
        const editor = createHeadlessEditor({
          nodes: [],
          onError: (error) => console.error(error),
        });
    
        editor.update(() => {
          $convertFromMarkdownString('ggggg*jhhhh**dsjdhjdj***', TRANSFORMERS);
          const root = $getRoot();
          const html = root.getFirstChild()?.exportDOM().element?.innerHTML;
    
          // Should have nested em and strong tags
          expect(html).toContain('<em>');
          expect(html).toContain('<strong>');
          expect(html).toMatch(/ggggg<em>jhhhh<strong>dsjdhjdj<\/strong><\/em>/);
    
          // Should NOT have literal asterisks
          expect(html).not.toContain('*');
        });
      });
    });
  11. etrepum commented on Jan 13, 2026

    @etrepum
    Collaborator

    If you’re experiencing a problem you should open a new issue rather than comment on one that’s been closed

  12. Yith1 commented on Jan 14, 2026

    @Yith1

    If you’re experiencing a problem you should open a new issue rather than comment on one that’s been closed

    Done: #8073

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions