diff --git a/packages/comark/src/auto-close.ts b/packages/comark/src/auto-close.ts index 804e38b5..c4cd74f5 100644 --- a/packages/comark/src/auto-close.ts +++ b/packages/comark/src/auto-close.ts @@ -648,6 +648,16 @@ function healRegion(text: string, o: Opts): string { i += n - 1 continue } + // A `_` run after punctuation and followed by a word char (`__下線、__次`, + // `__a.__b`, `_a(__b`) can only open in CommonMark, so any `_` closer + // appended at EOF would pair with this run instead of the open frames. + if (attachedLeft && isAlnum(next) && isPunct(prev) && top !== null && top.k === F_UNDER) { + while (frames.length > 0 && frames[frames.length - 1].k === F_UNDER) frames.pop() + // The scope a skipped `*` run was recorded in is gone with the frame. + starSkippedLen = 0 + i += n - 1 + continue + } if (openLeft && openRight && enabled) frames.push({ k: F_UNDER, len: n, pos: i }) } i += n - 1 @@ -1114,6 +1124,16 @@ function isAlnum(cp: string): boolean { return ALNUM_CP_RE.test(cp) } +const PUNCT_CP_RE = /\p{P}|\p{S}/u + +/** CommonMark punctuation. A combining mark is neither this nor alphanumeric. */ +function isPunct(cp: string): boolean { + if (cp === '') return false + const c = cp.charCodeAt(0) + if (c <= 127) return c > 32 && c < 127 && !isAlnum(cp) + return PUNCT_CP_RE.test(cp) +} + const OPENING_PUNCT_RE = /\p{Ps}|\p{Pi}/u /** Opening bracket or initial quote: `(`, `[`, `{`, `「`, `“`, ... */ diff --git a/packages/comark/test/auto-close.test.ts b/packages/comark/test/auto-close.test.ts index 731bee6e..af46be61 100644 --- a/packages/comark/test/auto-close.test.ts +++ b/packages/comark/test/auto-close.test.ts @@ -815,6 +815,22 @@ describe('word-internal emphasis ending in punctuation', () => { const healed = autoCloseMarkdown(input) expect((await parseMarkdown(healed)).nodes).toEqual((await parseMarkdown(input)).nodes) }) + + it('does not close underscore emphasis when a later run follows punctuation (#566)', async () => { + for (const input of ['__下線、__次', '__a.__b', '_a(__b', '__a(__b', '__a、_b', '_a、__b', '__a __b.__c']) { + const healed = autoCloseMarkdown(input) + expect(healed).toBe(input) + expect((await parseMarkdown(healed)).nodes).toEqual((await parseMarkdown(input, { autoClose: false })).nodes) + } + }) + + it('still closes underscore emphasis when a later run follows a combining mark', () => { + expect(autoCloseMarkdown('__cafe\u0301__ine')).toBe('__cafe\u0301__ine__') + }) + + it('forgets a skipped star run once the underscore frame around it is discarded', () => { + expect(autoCloseMarkdown('__a**b.__c~~d.**e')).toBe('__a**b.__c~~d.**e**~~') + }) }) describe('autoCloseMarkdown - syntax option', () => {