@@ -57,6 +57,14 @@ function codeFenceFor(code: string): string {
5757 return "`" . repeat ( Math . max ( 3 , longestRun + 1 ) ) ;
5858}
5959
60+ function outsideCodeFences ( markdown : string , tidy : ( prose : string ) => string ) : string {
61+ // A fence closes only at its own opening run, so split yields [prose, fence, run] triples.
62+ return markdown
63+ . split ( / ( ( ` { 3 , } ) [ \s \S ] * ?(?: \2| $ ) ) / )
64+ . map ( ( part , index ) => ( index % 3 === 0 ? tidy ( part ) : index % 3 === 1 ? part : "" ) )
65+ . join ( "" ) ;
66+ }
67+
6068function resolveCodeBlockLanguage ( pre : Element ) : string | null {
6169 const declared =
6270 pre . closest ( "[data-language]" ) ?. getAttribute ( "data-language" ) ??
@@ -120,11 +128,11 @@ function serializeListItem(
120128 const task = checkbox ? `[${ ( checkbox as HTMLInputElement ) . checked ? "x" : " " } ] ` : "" ;
121129 const bullet = ordered ? `${ index } . ` : "- " ;
122130 const marker = `${ bullet } ${ task } ` ;
123- let content = serializeChildren ( item , inTableCell )
124- . replace ( / \n { 3 , } / g, "\n\n" )
125- . trim ( ) ;
131+ let content = outsideCodeFences ( serializeChildren ( item , inTableCell ) , ( prose ) =>
132+ prose . replace ( / \n { 3 , } / g, "\n\n" ) ,
133+ ) . trim ( ) ;
126134 if ( ! item . querySelector ( ":scope > p" ) ) {
127- content = content . replace ( / \n { 2 , } / g, "\n" ) ;
135+ content = outsideCodeFences ( content , ( prose ) => prose . replace ( / \n { 2 , } / g, "\n" ) ) ;
128136 }
129137 // Continuations align after the bullet; task boxes belong to the item text.
130138 const continuationIndent = " " . repeat ( bullet . length ) ;
@@ -143,9 +151,9 @@ function serializeList(list: Element, ordered: boolean, inTableCell: boolean): s
143151}
144152
145153function serializeBlockquote ( quote : Element , inTableCell : boolean ) : string {
146- const content = serializeChildren ( quote , inTableCell )
147- . replace ( / \n { 3 , } / g, "\n\n" )
148- . trim ( ) ;
154+ const content = outsideCodeFences ( serializeChildren ( quote , inTableCell ) , ( prose ) =>
155+ prose . replace ( / \n { 3 , } / g, "\n\n" ) ,
156+ ) . trim ( ) ;
149157 if ( ! content ) return "" ;
150158 const quoted = content
151159 . split ( "\n" )
@@ -316,13 +324,9 @@ function soleCodeBlock(container: Node): Element | null {
316324}
317325
318326function tidyMarkdown ( markdown : string ) : string {
319- return markdown
320- . split ( / ( ` ` ` [ \s \S ] * ?(?: ` ` ` | $ ) ) / )
321- . map ( ( part , index ) =>
322- index % 2 === 1 ? part : part . replace ( / [ \t ] + (? = \n ) / g, "" ) . replace ( / \n { 3 , } / g, "\n\n" ) ,
323- )
324- . join ( "" )
325- . trim ( ) ;
327+ return outsideCodeFences ( markdown , ( prose ) =>
328+ prose . replace ( / [ \t ] + (? = \n ) / g, "" ) . replace ( / \n { 3 , } / g, "\n\n" ) ,
329+ ) . trim ( ) ;
326330}
327331
328332export function serializeRenderedMarkdownFragment ( container : Node ) : string {
0 commit comments