Skip to content

Commit aea5ccd

Browse files
committed
fix, add test
1 parent 3ca2068 commit aea5ccd

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

packages/lexical-markdown/src/MarkdownImport.ts

+19-5
Original file line numberDiff line numberDiff line change
@@ -294,24 +294,38 @@ function createTextFormatTransformersIndex(
294294
): TextFormatTransformersIndex {
295295
const transformersByTag: Record<string, TextFormatTransformer> = {};
296296
const fullMatchRegExpByTag: Record<string, RegExp> = {};
297-
const openTagsRegExp = [];
297+
const openTagsRegExp: string[] = [];
298298
const escapeRegExp = `(?<![\\\\])`;
299299

300+
// Sort `textTransformers` so that longer tags come before shorter ones
301+
// (prevents `*` from "stealing" text that should match `**`).
302+
textTransformers.sort((a, b) => b.tag.length - a.tag.length);
303+
300304
for (const transformer of textTransformers) {
301305
const {tag} = transformer;
302306
transformersByTag[tag] = transformer;
307+
303308
const tagRegExp = tag.replace(/(\*|\^|\+)/g, '\\$1');
304309
openTagsRegExp.push(tagRegExp);
305310

306-
fullMatchRegExpByTag[tag] = new RegExp(
307-
`(?<![\\\\${tagRegExp}])(${tagRegExp})((\\\\${tagRegExp})?.*?[^${tagRegExp}\\s](\\\\${tagRegExp})?)((?<!\\\\)|(?<=\\\\\\\\))(${tagRegExp})(?![\\\\${tagRegExp}])`,
308-
);
311+
// Single-char tag (e.g. "*"),
312+
if (tag.length === 1) {
313+
fullMatchRegExpByTag[tag] = new RegExp(
314+
`(?<![\\\\${tagRegExp}])(${tagRegExp})((\\\\${tagRegExp})?.*?[^${tagRegExp}\\s](\\\\${tagRegExp})?)((?<!\\\\)|(?<=\\\\\\\\))(${tagRegExp})(?![\\\\${tagRegExp}])`,
315+
);
316+
} else {
317+
// Multi‐char tags (e.g. "**")
318+
fullMatchRegExpByTag[tag] = new RegExp(
319+
`(?<!\\\\)(${tagRegExp})((\\\\${tagRegExp})?.*?[^\\s](\\\\${tagRegExp})?)((?<!\\\\)|(?<=\\\\\\\\))(${tagRegExp})(?!\\\\)`,
320+
);
321+
}
309322
}
310323

311324
return {
312325
// Reg exp to find open tag + content + close tag
313326
fullMatchRegExpByTag,
314-
// Reg exp to find opening tags
327+
328+
// Regexp to locate *any* potential opening tag (longest first).
315329
openTagsRegExp: new RegExp(
316330
`${escapeRegExp}(${openTagsRegExp.join('|')})`,
317331
'g',

packages/lexical-markdown/src/__tests__/unit/LexicalMarkdown.test.ts

+4
Original file line numberDiff line numberDiff line change
@@ -583,6 +583,10 @@ describe('Markdown', () => {
583583
html: '<p><b><strong style="white-space: pre-wrap;">Backtick and asteriks: `**`.</strong></b></p>',
584584
md: '**Backtick and asteriks: \\`\\*\\*\\`.**',
585585
},
586+
{
587+
html: '<p><b><strong style="white-space: pre-wrap;">*test*</strong></b></p>',
588+
md: '**\\*test\\***',
589+
},
586590
];
587591

588592
const HIGHLIGHT_TEXT_MATCH_IMPORT: TextMatchTransformer = {

0 commit comments

Comments
 (0)