@mdream/js 2.0.3 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,5 @@
1
1
  import { BLOCKQUOTE_SPACING, DEFAULT_BLOCK_SPACING, LIST_ITEM_SPACING, NO_SPACING, TABLE_ROW_SPACING, isInsideRawHtmlBlock } from "./const.mjs";
2
- import { blockOpenPrefix, continuationPrefix, endsAtHardBreak, figcaptionOwnsBlockSpacing, getLanguageFromClass, isCharacterReferenceTail, isDataUrl, isEmptyLinkHref, isInsideHeading, isInsideTableCell, lastOutputChar, listMarkerLineStart, markRenderedChildContent, orderedItemNumber, parseUnsignedInteger, trimOutputStart, trimTextAtLineStart } from "./utils.mjs";
3
- import { resolveUrl, safeAnchorOutput } from "./url.mjs";
2
+ import { blockOpenPrefix, dropSourceLead, endsAtHardBreak, figcaptionOwnsBlockSpacing, getLanguageFromAttributes, hasNonWhitespace, isBlockChildOfOpenVoid, isCharacterReferenceTail, isDataUrl, isEmptyLinkHref, isInsideHeading, isInsideTableCell, isOpenVoidTag, lastOutputChar, listMarkerLineStart, markRenderedChildContent, needsSpacing, noteBufferRewrite, orderedItemNumber, outputLeadLength, parseUnsignedInteger, parserTagHandlers, pendingMarkerIndent, resolveUrl, safeAnchorOutput, suppressesFormattingInPre, traverseUpToFirstBlockNode, trimOutputStart, trimTextAtLineStart } from "./url.mjs";
4
3
  function serializeMarkdownDestination(destination) {
5
4
  if (!/[\t\n\f\r ()\\<>]/.test(destination)) return destination;
6
5
  return `<${/[\\<>]/.test(destination) ? destination.replace(/[\\<>]/g, "\\$&") : destination}>`;
@@ -10,6 +9,9 @@ function stripsEmptyLink(state, href) {
10
9
  if (!(clean === true || typeof clean === "object" && clean.emptyLinks)) return false;
11
10
  return isEmptyLinkHref(href);
12
11
  }
12
+ function enterOutputEnd(node, state) {
13
+ return state.preFenceOpener === node ? state.codeFence.fragment : state.buffer.length;
14
+ }
13
15
  function serializeMarkdownTitle(title) {
14
16
  return /[\\"]/.test(title) ? title.replace(/[\\"]/g, "\\$&") : title;
15
17
  }
@@ -28,41 +30,150 @@ function isAutolinkUri(s) {
28
30
  }
29
31
  return true;
30
32
  }
31
- function renderBreak(node, state) {
33
+ function renderBreak(state) {
32
34
  const depthMap = state.depthMap;
35
+ if (!depthMap[34] && state.codeText?.kind === "span") return " ";
33
36
  if (isInsideTableCell(state) || isInsideRawHtmlBlock(depthMap) || isInsideHeading(depthMap)) return "<br>";
34
37
  if (depthMap[34] || depthMap[23]) return "\n";
35
- return ` \n${continuationPrefix(node, state.listIndentWidths || [], !state.bufferedBlockquoteDepth)}`;
38
+ return ` \n${state.listIndent ?? ""}`;
36
39
  }
37
40
  const breakHandler = {
38
- enter: ({ node, state }) => renderBreak(node, state),
41
+ enter: ({ state }) => renderBreak(state),
39
42
  isSelfClosing: true,
40
43
  spacing: NO_SPACING,
41
44
  collapsesInnerWhiteSpace: true,
42
45
  isInline: true
43
46
  };
44
- function escapeTrailingHeadingHashes(buffer, positions) {
47
+ const CODE_SPAN_ENTER = {
48
+ _tag: "CodeSpanEnter",
49
+ output: "`"
50
+ };
51
+ const SPACED_CODE_SPAN_ENTER = {
52
+ _tag: "CodeSpanEnter",
53
+ output: " `"
54
+ };
55
+ const CODE_SPAN_EXIT = { _tag: "CodeSpanExit" };
56
+ function inlineCodeEnter(state, separateFromListText = false) {
57
+ const last = lastOutputChar(state.buffer);
58
+ return last === 96 || separateFromListText && last !== -1 && last !== 32 && last !== 10 && last !== 9 && last !== 42 && last !== 95 && last !== 126 && last !== 91 && last !== 62 ? SPACED_CODE_SPAN_ENTER : CODE_SPAN_ENTER;
59
+ }
60
+ const codeLikeHandler = {
61
+ enter: ({ state }) => isInsideRawHtmlBlock(state.depthMap) ? "`" : inlineCodeEnter(state),
62
+ exit: ({ state }) => isInsideRawHtmlBlock(state.depthMap) ? "`" : CODE_SPAN_EXIT,
63
+ collapsesInnerWhiteSpace: true,
64
+ spacing: NO_SPACING,
65
+ isInline: true
66
+ };
67
+ const LEAD_GAP = 0;
68
+ const LEAD_DIGITS = 1;
69
+ const LEAD_INDENT = 2;
70
+ function opensBlockLine(buffer, fragment, cursor) {
71
+ let phase = LEAD_GAP;
72
+ let count = 0;
73
+ for (;;) {
74
+ if (cursor === 0) {
75
+ if (--fragment < 0) return phase !== LEAD_DIGITS || count > 0;
76
+ cursor = buffer[fragment].length;
77
+ continue;
78
+ }
79
+ const code = buffer[fragment].charCodeAt(--cursor);
80
+ if (code === 10) return phase !== LEAD_DIGITS || count > 0;
81
+ if (phase === LEAD_DIGITS) {
82
+ if (code >= 48 && code <= 57) {
83
+ if (++count > 9) return false;
84
+ continue;
85
+ }
86
+ if (count === 0) return false;
87
+ phase = LEAD_INDENT;
88
+ }
89
+ if (code === 32) {
90
+ if (phase === LEAD_GAP) count++;
91
+ continue;
92
+ }
93
+ if (phase !== LEAD_GAP || count === 0) return false;
94
+ if (code === 45 || code === 42 || code === 43) phase = LEAD_INDENT;
95
+ else if (code === 46 || code === 41) {
96
+ phase = LEAD_DIGITS;
97
+ count = 0;
98
+ } else return false;
99
+ }
100
+ }
101
+ function markerOpensBlockLine(state, index, marker) {
102
+ const buffer = state.buffer;
103
+ const memo = state.markerLine;
104
+ if (memo && memo.index === index && buffer[index] === memo.entry && buffer[memo.stop] === memo.stopEntry) return memo.opens;
105
+ const opens = opensBlockLine(buffer, index, marker);
106
+ let fragment = index;
107
+ let cursor = marker;
108
+ for (;;) if (cursor === 0) {
109
+ if (fragment === 0) break;
110
+ cursor = buffer[--fragment].length;
111
+ } else if (isLeadChar(buffer[fragment].charCodeAt(cursor - 1))) cursor--;
112
+ else break;
113
+ state.markerLine = {
114
+ index,
115
+ entry: buffer[index],
116
+ stop: fragment,
117
+ stopEntry: buffer[fragment],
118
+ opens
119
+ };
120
+ return opens;
121
+ }
122
+ function isLeadChar(code) {
123
+ return code === 32 || code >= 48 && code <= 57 || code === 45 || code === 42 || code === 43 || code === 46 || code === 41;
124
+ }
125
+ function isBlankEntry(entry) {
126
+ for (let i = 0; i < entry.length; i++) {
127
+ const code = entry.charCodeAt(i);
128
+ if (code !== 32 && code !== 9) return false;
129
+ }
130
+ return true;
131
+ }
132
+ function escapeTrailingHeadingHashes(state) {
133
+ const buffer = state.buffer;
45
134
  let index = buffer.length - 1;
46
135
  while (index >= 0 && buffer[index] === "") index--;
47
136
  if (index < 0) return;
137
+ const last = index;
138
+ while (index > 0 && isBlankEntry(buffer[index])) index--;
48
139
  const entry = buffer[index];
49
140
  let end = entry.length;
50
141
  while (end > 0 && (entry[end - 1] === " " || entry[end - 1] === " ")) end--;
51
142
  let run = end;
52
143
  while (run > 0 && entry[run - 1] === "#") run--;
53
144
  if (run === end) return;
54
- const previous = buffer[index - 1];
55
- const before = run > 0 ? entry[run - 1] : previous?.charAt(previous.length - 1);
56
- if (before !== " " && before !== " ") return;
57
- const replacement = `${entry.slice(0, run)}\\${entry.slice(run)}`;
58
- positions?.replace(index, index + 1, [replacement], (offset) => offset > run ? offset + 1 : offset);
145
+ let replacement;
146
+ if (opensBlockLine(buffer, index, run)) {
147
+ if (index !== last) return;
148
+ let trimmed = entry.length;
149
+ while (trimmed > end && entry.charCodeAt(trimmed - 1) === 32) trimmed--;
150
+ if (trimmed === entry.length) return;
151
+ replacement = entry.slice(0, trimmed);
152
+ state.outputPositions?.replace(index, index + 1, [replacement]);
153
+ } else {
154
+ const previous = buffer[index - 1];
155
+ const before = run > 0 ? entry[run - 1] : previous?.charAt(previous.length - 1);
156
+ if (before !== " " && before !== " " || inPreCodeFence(state)) return;
157
+ replacement = `${entry.slice(0, run)}\\${entry.slice(run)}`;
158
+ state.outputPositions?.replace(index, index + 1, [replacement], (offset) => offset > run ? offset + 1 : offset);
159
+ }
59
160
  buffer[index] = replacement;
161
+ noteBufferRewrite(state);
162
+ if (state.lastContentCache === entry) state.lastContentCache = replacement;
163
+ }
164
+ function inPreCodeFence(state) {
165
+ return !!state.codeFence && !state.fencesUnreliable && !!state.depthMap?.[34];
166
+ }
167
+ function hasInlineAncestor(node) {
168
+ for (let parent = node.parent; parent; parent = parent.parent) if (parent.tagHandler ? parent.tagHandler.isInline === true : parent.tagId === -1) return true;
169
+ return false;
60
170
  }
61
171
  const LINE_FRESH = -1;
62
172
  const LINE_OPEN = 0;
63
173
  const LINE_ROW = 1;
64
174
  const LINE_CONTENT = 2;
65
- function lineStateBeforeRow(buffer) {
175
+ function lineStateBeforeRow(state) {
176
+ const buffer = state.buffer;
66
177
  let fragment = buffer.length - 1;
67
178
  while (fragment >= 0 && buffer[fragment].length === 0) fragment--;
68
179
  if (fragment < 0) return LINE_OPEN;
@@ -89,12 +200,12 @@ function lineStateBeforeRow(buffer) {
89
200
  }
90
201
  }
91
202
  if (firstNonSpace === -1) return LINE_OPEN;
92
- if (firstNonSpace === 124) return LINE_ROW;
93
- return listMarkerLineStart(buffer, markerFragment, markerIndex) ? LINE_OPEN : LINE_CONTENT;
203
+ if (listMarkerLineStart(buffer, markerFragment, markerIndex, pendingMarkerIndent(state))) return LINE_OPEN;
204
+ return firstNonSpace === 124 ? LINE_ROW : LINE_CONTENT;
94
205
  }
95
206
  function rowMarker(state) {
96
207
  const indent = state.listIndent;
97
- const lineState = lineStateBeforeRow(state.buffer);
208
+ const lineState = lineStateBeforeRow(state);
98
209
  if (!indent) return lineState === LINE_ROW ? "\n| " : lineState === LINE_CONTENT ? "\n\n| " : "| ";
99
210
  switch (lineState) {
100
211
  case LINE_ROW: return `\n${indent}| `;
@@ -118,23 +229,32 @@ function cellExit(node, state) {
118
229
  }
119
230
  function handleHeading(depth) {
120
231
  return {
121
- enter: ({ state }) => {
232
+ enter: ({ node, state }) => {
122
233
  if ((state.depthMap?.[26] || 0) > 0 || isInsideTableCell(state)) return `<h${depth}>`;
123
- return `${"#".repeat(depth)} `;
234
+ const heading = `${"#".repeat(depth)} `;
235
+ if (state.listIndent && lastOutputChar(state.buffer) === 10 && state.blockquotes?.at(-1)?.fragment !== state.buffer.length) return `\n${state.listIndent}${heading}`;
236
+ if (state.listIndent && node.parent?.tagId === 25) {
237
+ const prefix = state.listIndent;
238
+ const open = blockOpenPrefix(state, prefix);
239
+ if (open !== void 0) return `${open}${heading}`;
240
+ }
241
+ return heading;
124
242
  },
125
243
  exit: ({ state }) => {
126
244
  if ((state.depthMap?.[26] || 0) > 0 || isInsideTableCell(state)) return `</h${depth}>`;
127
- escapeTrailingHeadingHashes(state.buffer, state.outputPositions);
245
+ escapeTrailingHeadingHashes(state);
128
246
  },
129
247
  collapsesInnerWhiteSpace: true
130
248
  };
131
249
  }
132
250
  const Strong = {
133
251
  enter: ({ state }) => {
252
+ if (state.codeText) return void 0;
134
253
  if ((state.depthMap?.[15] || 0) > 1) return "";
135
254
  return "**";
136
255
  },
137
256
  exit: ({ node, state }) => {
257
+ if (state.codeText) return void 0;
138
258
  if ((state.depthMap?.[15] || 0) + (node.tagId === 15 ? 1 : 0) > 1) return "";
139
259
  return "**";
140
260
  },
@@ -144,10 +264,12 @@ const Strong = {
144
264
  };
145
265
  const Emphasis = {
146
266
  enter: ({ state }) => {
267
+ if (state.codeText) return void 0;
147
268
  if ((state.depthMap?.[17] || 0) > 1) return "";
148
269
  return "*";
149
270
  },
150
271
  exit: ({ node, state }) => {
272
+ if (state.codeText) return void 0;
151
273
  if ((state.depthMap?.[17] || 0) + (node.tagId === 17 ? 1 : 0) > 1) return "";
152
274
  return "*";
153
275
  },
@@ -188,11 +310,13 @@ const tagHandlers = {
188
310
  },
189
311
  [52]: {
190
312
  excludesTextNodes: true,
191
- isNonNesting: true
313
+ isNonNesting: true,
314
+ spacing: NO_SPACING
192
315
  },
193
316
  [53]: {
194
317
  isNonNesting: true,
195
- excludesTextNodes: true
318
+ excludesTextNodes: true,
319
+ spacing: NO_SPACING
196
320
  },
197
321
  [5]: {
198
322
  collapsesInnerWhiteSpace: true,
@@ -209,12 +333,13 @@ const tagHandlers = {
209
333
  [13]: {
210
334
  enter: ({ node, state }) => {
211
335
  if (isInsideTableCell(state)) return "<hr>";
212
- if (!(state.depthMap?.[25] || state.bufferedBlockquoteDepth)) return "---";
213
- const prefix = continuationPrefix(node, state.listIndentWidths || [], !state.bufferedBlockquoteDepth);
214
- if (!prefix) return "---";
215
- if (state.depthMap?.[25]) state.listRulePending = prefix;
216
- const open = blockOpenPrefix(state.buffer, prefix);
217
- return open === void 0 ? "***" : `${open}---`;
336
+ if (!state.depthMap?.[25]) return "---";
337
+ const prefix = state.listIndent;
338
+ state.listRulePending = prefix;
339
+ const end = enterOutputEnd(node, state);
340
+ if (state.codeFence?.fragment === end - 1 && state.buffer[end - 1].endsWith("\n")) return `${prefix}***`;
341
+ const open = blockOpenPrefix(state, prefix, end);
342
+ return open === void 0 && prefix && !state.lastItemStar ? "***" : `${open ?? ""}---`;
218
343
  },
219
344
  isSelfClosing: true
220
345
  },
@@ -250,7 +375,7 @@ const tagHandlers = {
250
375
  enter: ({ state }) => {
251
376
  return {
252
377
  _tag: "BlockquoteEnter",
253
- output: (state.depthMap?.[25] || 0) > 0 ? "\n" : void 0
378
+ output: (state.depthMap?.[25] || 0) > 0 && !isInsideTableCell(state) ? "\n" : void 0
254
379
  };
255
380
  },
256
381
  exit: () => ({ _tag: "BlockquoteExit" }),
@@ -259,9 +384,10 @@ const tagHandlers = {
259
384
  [34]: {
260
385
  enter: ({ node, state }) => {
261
386
  if (isInsideTableCell(state)) return "<pre>";
387
+ if (!state.preFenceOwnerDepth && !state.preFencePending) state.preFenceInline = hasInlineAncestor(node);
262
388
  return {
263
389
  _tag: "PreEnter",
264
- language: getLanguageFromClass(node.attributes?.class)
390
+ language: getLanguageFromAttributes(node.attributes)
265
391
  };
266
392
  },
267
393
  exit: ({ state }) => {
@@ -274,13 +400,13 @@ const tagHandlers = {
274
400
  if ((state.depthMap?.[34] || 0) > 0) {
275
401
  if (isInsideTableCell(state)) return "<code>";
276
402
  if (state.preFenceOwnerDepth) return;
277
- const language = getLanguageFromClass(node.attributes?.class);
403
+ const language = getLanguageFromAttributes(node.attributes) || state.preFenceLang || "";
278
404
  if ((state.depthMap?.[25] || 0) > 0) {
279
405
  const indent = state.listIndent;
280
406
  return {
281
407
  _tag: "CodeFenceEnter",
282
408
  language,
283
- output: `${blockOpenPrefix(state.buffer, indent) ?? ""}\`\`\`${language}\n`
409
+ output: `${blockOpenPrefix(state, indent) ?? ""}\`\`\`${language}\n`
284
410
  };
285
411
  }
286
412
  return {
@@ -290,18 +416,7 @@ const tagHandlers = {
290
416
  };
291
417
  }
292
418
  if (isInsideRawHtmlBlock(state.depthMap)) return "<code>";
293
- if ((state.depthMap?.[25] || 0) > 0) {
294
- const lastEntry = state.buffer.at(-1);
295
- const lastChar = lastEntry?.charAt(lastEntry.length - 1) || "";
296
- if (lastChar && lastChar !== " " && lastChar !== "\n" && lastChar !== " " && lastChar !== "*" && lastChar !== "_" && lastChar !== "~" && lastChar !== "[" && lastChar !== ">") return {
297
- _tag: "CodeSpanEnter",
298
- output: ` \``
299
- };
300
- }
301
- return {
302
- _tag: "CodeSpanEnter",
303
- output: "`"
304
- };
419
+ return inlineCodeEnter(state, !!state.depthMap?.[25]);
305
420
  },
306
421
  exit: ({ state }) => {
307
422
  if ((state.depthMap?.[34] || 0) > 0) {
@@ -309,7 +424,7 @@ const tagHandlers = {
309
424
  return;
310
425
  }
311
426
  if (isInsideRawHtmlBlock(state.depthMap)) return "</code>";
312
- return { _tag: "CodeSpanExit" };
427
+ return CODE_SPAN_EXIT;
313
428
  },
314
429
  collapsesInnerWhiteSpace: true,
315
430
  spacing: NO_SPACING,
@@ -326,7 +441,10 @@ const tagHandlers = {
326
441
  [25]: {
327
442
  enter: ({ node, state }) => {
328
443
  if (isInsideTableCell(state)) return "<li>";
329
- const marker = node.parent?.tagId === 33 ? `${orderedItemNumber(node.parent, node.index)}. ` : "- ";
444
+ const isOrdered = node.parent?.tagId === 33;
445
+ const markers = state.listMarkers;
446
+ const character = markers && markers.length > 0 ? markers[markers.length - 1] & 255 : 0;
447
+ const marker = isOrdered ? `${orderedItemNumber(node.parent, node.index)}${character === 41 ? ") " : ". "}` : character === 42 ? "* " : "- ";
330
448
  return `${state.listIndent}${marker}`;
331
449
  },
332
450
  exit: ({ state }) => isInsideTableCell(state) ? "</li>" : void 0,
@@ -346,7 +464,15 @@ const tagHandlers = {
346
464
  if (isInsideRawHtmlBlock(state.depthMap) && !node.tagHandler?.literalEnter) return safeAnchorOutput(node, state.options, false, true);
347
465
  const href = resolveUrl(node.attributes.href, state.options?.origin, state.options?.clean);
348
466
  let title = node.attributes?.title;
349
- if (state.lastContentCache === title) title = "";
467
+ let preservesCodeWhitespace = false;
468
+ if (state.codeText?.kind === "span" && !state.depthMap?.[34] && !state.lastTextNode?.containsWhitespace) {
469
+ const buffer = state.buffer;
470
+ let tail = buffer.length - 1;
471
+ while (tail >= 0 && !buffer[tail]) tail--;
472
+ preservesCodeWhitespace = buffer[tail] === state.lastContentCache;
473
+ }
474
+ const cachedText = preservesCodeWhitespace ? state.lastContentCache : state.lastContentCache?.replace(/[ \t\n\f\r]+$/, "");
475
+ if (title && !state.cacheFollowsSeparator && state.droppedPairAt !== state.buffer.length && cachedText === title.replace(/[ \t\n\f\r]+$/, "")) title = "";
350
476
  if (!title && isAutolinkUri(href)) {
351
477
  const buf = state.buffer;
352
478
  let i = buf.length - 1;
@@ -407,9 +533,9 @@ const tagHandlers = {
407
533
  },
408
534
  exit: ({ state }) => isInsideTableCell(state) ? "</table>" : void 0
409
535
  },
410
- [107]: { enter: ({ state }) => {
536
+ [107]: { enter: ({ node, state }) => {
411
537
  if ((state.depthMap?.[25] || 0) === 0 || isInsideTableCell(state)) return void 0;
412
- return blockOpenPrefix(state.buffer, state.listIndent);
538
+ return blockOpenPrefix(state, state.listIndent, enterOutputEnd(node, state));
413
539
  } },
414
540
  [29]: {
415
541
  enter: ({ state }) => {
@@ -480,14 +606,23 @@ const tagHandlers = {
480
606
  collapsesInnerWhiteSpace: true,
481
607
  spacing: NO_SPACING
482
608
  },
483
- [35]: { enter: ({ state }) => {
609
+ [35]: { enter: ({ node, state }) => {
610
+ if ((state.depthMap?.[25] || 0) > 0 && !isInsideTableCell(state) && !state.preFencePending && state.preFenceOpener !== node) {
611
+ const last = lastOutputChar(state.buffer, enterOutputEnd(node, state));
612
+ if (last !== -1 && last !== 32 && last !== 10) return `\n\n${state.listIndent}`;
613
+ }
614
+ } },
615
+ [36]: { enter: ({ state }) => {
484
616
  if ((state.depthMap?.[25] || 0) > 0 && !isInsideTableCell(state)) {
485
- const lastEntry = state.buffer.at(-1);
486
- const lastChar = lastEntry?.charAt(lastEntry.length - 1) || "";
487
- if (lastChar && lastChar !== " " && lastChar !== "\n") return `\n\n${state.listIndent}`;
617
+ let index = state.buffer.length - 1;
618
+ while (index >= 0 && state.buffer[index] === "") index--;
619
+ const entry = state.buffer[index] || "";
620
+ let marker = entry.length;
621
+ while (marker > 0 && entry.length - marker < 7 && entry.charCodeAt(marker - 1) === 35) marker--;
622
+ const hashes = entry.length - marker;
623
+ if (hashes > 0 && hashes <= 6 && markerOpensBlockLine(state, index, marker)) return `\n\n${state.listIndent}`;
488
624
  }
489
625
  } },
490
- [36]: {},
491
626
  [37]: {
492
627
  collapsesInnerWhiteSpace: true,
493
628
  spacing: NO_SPACING,
@@ -522,13 +657,7 @@ const tagHandlers = {
522
657
  spacing: TABLE_ROW_SPACING,
523
658
  excludesTextNodes: true
524
659
  },
525
- [46]: {
526
- enter: () => "`",
527
- exit: () => "`",
528
- collapsesInnerWhiteSpace: true,
529
- spacing: NO_SPACING,
530
- isInline: true
531
- },
660
+ [46]: codeLikeHandler,
532
661
  [47]: { spacing: NO_SPACING },
533
662
  [40]: { spacing: NO_SPACING },
534
663
  [54]: {
@@ -630,13 +759,7 @@ const tagHandlers = {
630
759
  spacing: NO_SPACING,
631
760
  isInline: true
632
761
  },
633
- [82]: {
634
- enter: () => "`",
635
- exit: () => "`",
636
- collapsesInnerWhiteSpace: true,
637
- spacing: NO_SPACING,
638
- isInline: true
639
- },
762
+ [82]: codeLikeHandler,
640
763
  [83]: {
641
764
  enter: () => "",
642
765
  exit: () => "",
@@ -673,26 +796,20 @@ const tagHandlers = {
673
796
  isInline: true
674
797
  },
675
798
  [90]: {
676
- enter: () => "*",
677
- exit: () => "*",
799
+ enter: ({ state }) => state.codeText ? void 0 : "*",
800
+ exit: ({ state }) => state.codeText ? void 0 : "*",
678
801
  collapsesInnerWhiteSpace: true,
679
802
  spacing: NO_SPACING,
680
803
  isInline: true
681
804
  },
682
805
  [91]: {
683
- enter: () => "**",
684
- exit: () => "**",
685
- collapsesInnerWhiteSpace: true,
686
- spacing: NO_SPACING,
687
- isInline: true
688
- },
689
- [92]: {
690
- enter: () => "`",
691
- exit: () => "`",
806
+ enter: ({ state }) => state.codeText ? void 0 : "**",
807
+ exit: ({ state }) => state.codeText ? void 0 : "**",
692
808
  collapsesInnerWhiteSpace: true,
693
809
  spacing: NO_SPACING,
694
810
  isInline: true
695
811
  },
812
+ [92]: codeLikeHandler,
696
813
  [93]: {
697
814
  enter: () => "",
698
815
  exit: () => "",
@@ -766,6 +883,8 @@ const MARKER_TYPE_MASK = 7;
766
883
  const CAPTION_FRAME_SIZE = 4;
767
884
  const CAPTION_OPEN = 1;
768
885
  const CAPTION_INTERNAL_BREAK = 2;
886
+ const CAPTION_HEADING_BREAK = 4;
887
+ const CAPTION_BLOCK_PREFIX = 8;
769
888
  const CAPTION_DEFAULT_SPACING = -1;
770
889
  const CAPTION_NO_ANCHOR = -1;
771
890
  INLINE_MARKER_TYPE[14] = 1;
@@ -782,8 +901,18 @@ INLINE_MARKER_TYPE[23] = 5;
782
901
  INLINE_MARKER_TYPE[82] = 5;
783
902
  INLINE_MARKER_TYPE[92] = 5;
784
903
  INLINE_MARKER_TYPE[81] = 6;
785
- function suppressesFormattingInPre(tagId) {
786
- return tagId === 26 || tagId === 46 || tagId === 110 || tagId === 111 || tagId === 106 || tagId >= 14 && tagId <= 21 || tagId >= 79 && tagId <= 83 || tagId >= 89 && tagId <= 94;
904
+ function isAsciiPunctuation(code) {
905
+ return code >= 33 && code <= 126 && !isAsciiAlphanumeric(code);
906
+ }
907
+ function isAsciiAlphanumeric(code) {
908
+ return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
909
+ }
910
+ function breaksPendingCloser(output, entering, closer) {
911
+ for (let index = 0; index < output.length; index++) {
912
+ const fragment = output[index];
913
+ if (fragment && (entering || fragment.charCodeAt(0) !== closer || fragment.charCodeAt(fragment.length - 1) !== closer)) return true;
914
+ }
915
+ return false;
787
916
  }
788
917
  function newlineRunBefore(buffer, index) {
789
918
  let run = 0;
@@ -796,6 +925,20 @@ function newlineRunBefore(buffer, index) {
796
925
  }
797
926
  return run;
798
927
  }
928
+ function crFollowsLineEnding(buffer, index) {
929
+ let skippedCr = false;
930
+ for (let i = index - 1; i >= 0; i--) {
931
+ const fragment = buffer[i];
932
+ for (let j = fragment.length - 1; j >= 0; j--) {
933
+ if (skippedCr) {
934
+ const code = fragment.charCodeAt(j);
935
+ return code === 10 || code === 13;
936
+ }
937
+ skippedCr = true;
938
+ }
939
+ }
940
+ return false;
941
+ }
799
942
  function newlineRunBeforePrefix(buffer, index, prefix) {
800
943
  let fragment = index - 1;
801
944
  let offset = fragment >= 0 ? buffer[fragment].length : 0;
@@ -816,14 +959,19 @@ function newlineRunBeforePrefix(buffer, index, prefix) {
816
959
  run++;
817
960
  }
818
961
  }
819
- function recordItemMarker(state, index) {
820
- if (index !== 0 || newlineRunBefore(state.buffer, state.buffer.length - 1) !== 1) {
962
+ function recordItemMarker(state, index, lastChar) {
963
+ const buffer = state.buffer;
964
+ const marker = buffer.length - 1;
965
+ const run = index === 0 ? newlineRunBefore(buffer, marker) : -1;
966
+ const afterCr = run === 0 && lastChar === "\r";
967
+ if (afterCr ? crFollowsLineEnding(buffer, buffer[marker - 1] === " " ? marker - 1 : marker) : run !== 1) {
821
968
  state.emptyItemFragment = void 0;
822
969
  return;
823
970
  }
824
- state.emptyItemFragment = state.buffer.length - 1;
971
+ state.emptyItemFragment = marker;
972
+ state.emptyItemAfterCr = afterCr;
825
973
  }
826
- function resolveItemMarker(state, atExit, unresolvedCaptionFragment = -1) {
974
+ function resolveItemMarker(state, atExit, unresolvedCaptionFragment = -1, linkOpen = false) {
827
975
  const fragment = state.emptyItemFragment;
828
976
  if (fragment === void 0) return;
829
977
  const buffer = state.buffer;
@@ -839,7 +987,8 @@ function resolveItemMarker(state, atExit, unresolvedCaptionFragment = -1) {
839
987
  }
840
988
  }
841
989
  if (first === -1 && !atExit) return;
842
- if (first === 10 && !atExit) return;
990
+ const lineEnds = first === 10 || first === 13;
991
+ if (lineEnds && !atExit) return;
843
992
  if (!atExit && unresolvedCaptionFragment !== -1) {
844
993
  let captionOpensItem = true;
845
994
  for (let index = fragment + 1; index < unresolvedCaptionFragment; index++) if (hasNonWhitespace(buffer[index])) {
@@ -849,31 +998,46 @@ function resolveItemMarker(state, atExit, unresolvedCaptionFragment = -1) {
849
998
  if (captionOpensItem) return;
850
999
  }
851
1000
  state.emptyItemFragment = void 0;
852
- if (first !== -1 && first !== 10) return;
853
- const replacement = `\n${buffer[fragment]}`;
854
- state.outputPositions?.replace(fragment, fragment + 1, [replacement], (offset) => offset + 1);
1001
+ if (first !== -1 && !lineEnds) return;
1002
+ const afterCr = state.emptyItemAfterCr;
1003
+ if (first === -1 && afterCr && linkOpen) return;
1004
+ const spaced = afterCr && buffer[fragment - 1] === " ";
1005
+ if (spaced) {
1006
+ state.outputPositions?.replace(fragment - 1, fragment, ["\n"]);
1007
+ buffer[fragment - 1] = "\n";
1008
+ }
1009
+ const separator = afterCr && !spaced ? "\n\n" : "\n";
1010
+ const replacement = separator + buffer[fragment];
1011
+ state.outputPositions?.replace(fragment, fragment + 1, [replacement], (offset) => offset + separator.length);
855
1012
  buffer[fragment] = replacement;
1013
+ noteBufferRewrite(state);
856
1014
  }
857
- function updateListIndent(state, element, eventType) {
858
- if (element.tagId !== 25) return;
1015
+ function updateListIndent(state, element, eventType, output, pluginWrote) {
859
1016
  if (isInsideTableCell(state)) return;
860
1017
  if (eventType === 0) {
861
1018
  const width = element.parent?.tagId === 33 ? String(orderedItemNumber(element.parent, element.index)).length + 2 : 2;
862
1019
  state.listIndentWidths.push(width);
863
1020
  state.listIndent += " ".repeat(width);
1021
+ const markers = state.listMarkers;
1022
+ const top = markers.length - 1;
1023
+ const selected = top >= 0 ? markers[top] & 255 : 0;
1024
+ let written = 0;
1025
+ if (pluginWrote || element.tagHandler?.literalEnter) written = output ? writtenListMarker(output.join("")) : 0;
1026
+ else if (output?.some(hasNonWhitespace)) written = selected;
1027
+ if (written !== 0 && top >= 0) markers[top] = selected | written << 8;
1028
+ state.lastItemStar = written === 42;
864
1029
  } else if (eventType === 1) {
865
1030
  const width = state.listIndentWidths.pop() ?? 0;
866
1031
  state.listIndent = state.listIndent.slice(0, state.listIndent.length - width);
867
1032
  }
868
1033
  }
869
- function needsSpacing(lastChar, firstChar, state) {
870
- if (" \n ".includes(lastChar) || " \n ".includes(firstChar)) return false;
871
- if (lastChar === "|" && firstChar === "<" && state && (state.depthMap[28] || 0) > 0) return true;
872
- return !"[(>*_`".includes(lastChar) && !"])<.,!?:;*_`".includes(firstChar);
1034
+ function needsMarkdownSpacing(lastChar, firstChar, openMarkerCount) {
1035
+ if (lastChar === "~" && openMarkerCount) return firstChar === "~";
1036
+ return needsSpacing(lastChar, firstChar);
873
1037
  }
874
1038
  function shouldAddSpacingBeforeText(lastChar, lastNode, textNode) {
875
1039
  if (!lastChar || "\n [>".includes(lastChar)) return false;
876
- if (textNode.joinsPrevious || lastNode && (lastNode.tagHandler ? lastNode.tagHandler.isInline : lastNode.tagId === -1)) return false;
1040
+ if (textNode.joinsPrevious || lastNode && (lastNode.tagHandler ? lastNode.tagHandler.isInline || isOpenVoidTag(lastNode.tagHandler, lastNode.tagId) : lastNode.tagId === -1)) return false;
877
1041
  const firstChar = textNode.value[0];
878
1042
  if (firstChar === " ") return false;
879
1043
  if (firstChar && ".,!?:;_*`)]".includes(firstChar)) return false;
@@ -988,18 +1152,18 @@ function lineOpensRawHtmlBlock(buffer, scan) {
988
1152
  scan[3] = buffer.length;
989
1153
  scan[4] = 0;
990
1154
  }
991
- function markdownLineIndent(buffer) {
1155
+ function markdownLineIndent(buffer, structuralIndent) {
992
1156
  let spaces = 0;
993
1157
  for (let fragmentIndex = buffer.length - 1; fragmentIndex >= 0; fragmentIndex--) {
994
1158
  const fragment = buffer[fragmentIndex];
995
1159
  for (let index = fragment.length - 1; index >= 0; index--) {
996
1160
  const code = fragment.charCodeAt(index);
997
- if (code === 10) return spaces;
998
- if (code !== 32 || spaces === 3) return listMarkerLineStart(buffer, fragmentIndex, index) ? 0 : -1;
1161
+ if (code === 10 || code === 13) return Math.max(0, spaces - structuralIndent);
1162
+ if (code !== 32 || spaces === structuralIndent + 3) return listMarkerLineStart(buffer, fragmentIndex, index) ? 0 : -1;
999
1163
  spaces++;
1000
1164
  }
1001
1165
  }
1002
- return spaces;
1166
+ return Math.max(0, spaces - structuralIndent);
1003
1167
  }
1004
1168
  function isMarkdownMarkerWhitespace(code) {
1005
1169
  return code === 0 || code === 9 || code === 10 || code === 13 || code === 32;
@@ -1007,23 +1171,88 @@ function isMarkdownMarkerWhitespace(code) {
1007
1171
  function canStartGfmAngleConstruct(code) {
1008
1172
  return code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 33 || code === 47 || code === 63;
1009
1173
  }
1010
- function isThematicBreak(value, start, marker) {
1011
- let count = 0;
1174
+ function isDashLine(value, start) {
1012
1175
  for (let index = start; index < value.length; index++) {
1013
1176
  const code = value.charCodeAt(index);
1014
- if (code === marker) count++;
1015
- else if (code === 10 || code === 13) break;
1016
- else if (code !== 32 && code !== 9) return false;
1177
+ if (code === 10 || code === 13) break;
1178
+ if (code !== 45 && code !== 32 && code !== 9) return false;
1179
+ }
1180
+ return true;
1181
+ }
1182
+ function isEqualsLine(value, start) {
1183
+ let index = start + 1;
1184
+ while (index < value.length && value.charCodeAt(index) === 61) index++;
1185
+ for (; index < value.length; index++) {
1186
+ const code = value.charCodeAt(index);
1187
+ if (code === 10 || code === 13) break;
1188
+ if (code !== 32 && code !== 9) return false;
1017
1189
  }
1018
- return count >= 3;
1190
+ return true;
1019
1191
  }
1020
1192
  const GFM_TEXT_NATIVE_TRIGGER = /[\\*_~`[<\r\n]/;
1021
- function mayNeedGfmTextEscape(value, buffer, depthMap) {
1193
+ function lineStartDigits(state, value) {
1194
+ const buffer = state.buffer;
1195
+ const indent = state.listIndent;
1196
+ let lead = 0;
1197
+ while (value.charCodeAt(lead) >= 48 && value.charCodeAt(lead) <= 57) lead++;
1198
+ let one = lead === 0 || value.charCodeAt(lead - 1) === 49;
1199
+ for (let index = 0; one && index < lead - 1; index++) one = value.charCodeAt(index) === 48;
1200
+ let fragment = buffer.length - 1;
1201
+ let offset = fragment >= 0 ? buffer[fragment].length : 0;
1202
+ let digits = 0;
1203
+ let spaces = 0;
1204
+ let newline = false;
1205
+ for (;;) {
1206
+ while (offset === 0 && fragment >= 0) {
1207
+ fragment--;
1208
+ offset = fragment >= 0 ? buffer[fragment].length : 0;
1209
+ }
1210
+ const code = fragment >= 0 ? buffer[fragment].charCodeAt(--offset) : -1;
1211
+ if (newline) return code === -1 || code === 10 || code === 32 || code === 9 || code === 92 || outputStartsAt(state, fragment, offset + 1) ? digits : 0;
1212
+ if (spaces === 0 && code >= 48 && code <= 57) {
1213
+ if (++digits > 9) return 0;
1214
+ one &&= code === (digits === 1 && lead === 0 ? 49 : 48);
1215
+ continue;
1216
+ }
1217
+ if (digits === 0) return 0;
1218
+ if (code === 32) {
1219
+ if (++spaces > indent.length + 3) return outputStartsAt(state, fragment, offset) ? digits : 0;
1220
+ continue;
1221
+ }
1222
+ if (code === -1 || code === 10) {
1223
+ if (spaces > 3 && spaces < indent.length) return 0;
1224
+ if (code === -1 || one) return digits;
1225
+ newline = true;
1226
+ continue;
1227
+ }
1228
+ return spaces > 0 && spaces <= 3 && listMarkerLineStart(buffer, fragment, offset) || outputStartsAt(state, fragment, offset + 1) ? digits : 0;
1229
+ }
1230
+ }
1231
+ function outputStartsAt(state, fragment, offset) {
1232
+ if (state.drainedContent || state.blockquotes.length !== 0) return false;
1233
+ for (let index = fragment; index >= 0; index--) {
1234
+ const value = state.buffer[index];
1235
+ if (outputLeadLength(value) < (index === fragment ? offset : value.length)) return false;
1236
+ }
1237
+ return true;
1238
+ }
1239
+ function outputStartMarker(value, state) {
1240
+ const lead = outputLeadLength(value);
1241
+ const marker = value.charCodeAt(lead);
1242
+ if (marker !== 35 && marker !== 43 && marker !== 45 && marker !== 61 && marker !== 62 && !(marker >= 48 && marker <= 57)) return -1;
1243
+ if (state.depthMap[28]) for (let index = 0; index < lead; index++) {
1244
+ const code = value.charCodeAt(index);
1245
+ if (code === 10 || code === 13) return -1;
1246
+ }
1247
+ const last = state.buffer.length - 1;
1248
+ return outputStartsAt(state, last, last < 0 ? 0 : state.buffer[last].length) ? lead : -1;
1249
+ }
1250
+ function mayNeedGfmTextEscape(value, buffer, depthMap, structuralIndent) {
1022
1251
  if (value.search(GFM_TEXT_NATIVE_TRIGGER) !== -1) return true;
1023
1252
  if (depthMap[28] && value.includes("|") || depthMap[26] && value.includes("]") || depthMap[22] && value.includes(">")) return true;
1024
1253
  const first = value.charCodeAt(0);
1025
- if (!" #+->".includes(value[0]) && !(first >= 48 && first <= 57)) return false;
1026
- let lineIndent = markdownLineIndent(buffer);
1254
+ if (!" #+->=".includes(value[0]) && !(first >= 48 && first <= 57)) return false;
1255
+ let lineIndent = markdownLineIndent(buffer, structuralIndent);
1027
1256
  if (lineIndent < 0) return false;
1028
1257
  let index = 0;
1029
1258
  while (index < value.length && lineIndent < 3 && value.charCodeAt(index) === 32) {
@@ -1032,17 +1261,16 @@ function mayNeedGfmTextEscape(value, buffer, depthMap) {
1032
1261
  }
1033
1262
  if (index >= value.length) return false;
1034
1263
  const code = value.charCodeAt(index);
1035
- return "#+->".includes(value[index]) || code >= 48 && code <= 57;
1264
+ return "#+->=".includes(value[index]) || code >= 48 && code <= 57;
1036
1265
  }
1037
- function escapeGfmText(value, buffer, depthMap) {
1266
+ function escapeGfmText(value, buffer, depthMap, structuralIndent, orderedDigits = 0, outputStart = -1) {
1038
1267
  const inTable = Boolean(depthMap[28]);
1039
1268
  const inLink = Boolean(depthMap[26]);
1040
1269
  const inBlockquote = Boolean(depthMap[22]);
1041
- let lineIndent = markdownLineIndent(buffer);
1042
- let orderedDigits = 0;
1270
+ let lineIndent = outputStart === -1 ? markdownLineIndent(buffer, structuralIndent) : 0;
1043
1271
  let copiedUntil = 0;
1044
1272
  let escaped = "";
1045
- for (let index = 0; index < value.length; index++) {
1273
+ for (let index = Math.max(0, outputStart); index < value.length; index++) {
1046
1274
  const code = value.charCodeAt(index);
1047
1275
  const character = value[index];
1048
1276
  const next = index + 1 < value.length ? value.charCodeAt(index + 1) : 0;
@@ -1058,14 +1286,20 @@ function escapeGfmText(value, buffer, depthMap) {
1058
1286
  copiedUntil = index + 1;
1059
1287
  continue;
1060
1288
  }
1289
+ if (code === 13) {
1290
+ lineIndent = 0;
1291
+ orderedDigits = 0;
1292
+ continue;
1293
+ }
1061
1294
  let shouldEscape = "\\*_~`[".includes(character) || code === 93 && inLink || code === 124 && inTable || code === 62 && inBlockquote || code === 60 && canStartGfmAngleConstruct(value.charCodeAt(index + 1));
1062
1295
  if (!shouldEscape && lineIndent >= 0) {
1063
1296
  if (code === 35) {
1064
1297
  let end = index + 1;
1065
1298
  while (end < value.length && value.charCodeAt(end) === 35) end++;
1066
1299
  shouldEscape = end - index <= 6 && (end === value.length || isMarkdownMarkerWhitespace(value.charCodeAt(end)));
1067
- } else if (code === 45 || code === 43) shouldEscape = index + 1 === value.length || isMarkdownMarkerWhitespace(value.charCodeAt(index + 1)) || code === 45 && isThematicBreak(value, index, code);
1300
+ } else if (code === 45 || code === 43) shouldEscape = index + 1 === value.length || isMarkdownMarkerWhitespace(value.charCodeAt(index + 1)) || code === 45 && isDashLine(value, index);
1068
1301
  else if (code === 62) shouldEscape = true;
1302
+ else if (code === 61) shouldEscape = isEqualsLine(value, index);
1069
1303
  } else if (!shouldEscape && orderedDigits > 0 && (code === 46 || code === 41)) shouldEscape = index + 1 === value.length || isMarkdownMarkerWhitespace(value.charCodeAt(index + 1));
1070
1304
  if (shouldEscape) {
1071
1305
  escaped += value.slice(copiedUntil, index);
@@ -1088,23 +1322,25 @@ function escapeGfmText(value, buffer, depthMap) {
1088
1322
  }
1089
1323
  return copiedUntil === 0 ? value : escaped + value.slice(copiedUntil);
1090
1324
  }
1091
- function currentColumn(buffer) {
1325
+ function currentColumn(buffer, limit) {
1092
1326
  let col = 0;
1093
1327
  for (let i = buffer.length - 1; i >= 0; i--) {
1094
1328
  const s = buffer[i];
1095
- const nl = s.lastIndexOf("\n");
1096
- if (nl >= 0) return col + columnWidth(s, nl + 1);
1097
- col += columnWidth(s, 0);
1329
+ for (let j = s.length - 1; j >= 0; j--) {
1330
+ const code = s.charCodeAt(j);
1331
+ if (code === 10) return col;
1332
+ if (takesColumn(code) && ++col >= limit) return col;
1333
+ }
1098
1334
  }
1099
1335
  return col;
1100
1336
  }
1101
- function columnWidth(value, start) {
1102
- let width = 0;
1103
- for (let i = start; i < value.length; i++) {
1104
- const code = value.charCodeAt(i);
1105
- if ((code & 64512) !== 56320 && code !== 64976 && code !== 64977) width++;
1106
- }
1107
- return width;
1337
+ function takesColumn(code) {
1338
+ return (code & 64512) !== 56320 && code !== 64976 && code !== 64977;
1339
+ }
1340
+ const BLOCK_START_WORD = /^(?:>|`{3}|~{3}|(?:#{1,6}|\+|-+|=+|\*|\*{3,}|_{3,}|0{0,8}1[.)])$)/;
1341
+ function isSetextMarkerRun(word) {
1342
+ const first = word.charCodeAt(0);
1343
+ return first === 45 ? isDashLine(word, 0) : first === 61 && isEqualsLine(word, 0);
1108
1344
  }
1109
1345
  function wrapText(value, col, width, prefix) {
1110
1346
  const leading = value.charCodeAt(0) === 32;
@@ -1121,7 +1357,7 @@ function wrapText(value, col, width, prefix) {
1121
1357
  const word = value.slice(i, next);
1122
1358
  const wordLen = [...word].length;
1123
1359
  const needSpace = first ? leading : true;
1124
- if (needSpace && col > prefixLen && col + 1 + wordLen > width) {
1360
+ if (needSpace && col > prefixLen && col + 1 + wordLen > width && !isSetextMarkerRun(word) && !BLOCK_START_WORD.test(word)) {
1125
1361
  out += `\n${prefix}`;
1126
1362
  col = prefixLen;
1127
1363
  } else if (needSpace) {
@@ -1142,6 +1378,14 @@ function calculateNewLineConfig(node, state, eventType) {
1142
1378
  const depthMap = state.depthMap;
1143
1379
  const tagId = node.tagId;
1144
1380
  if (tagId !== 25 && (depthMap[25] || 0) > 0) return NO_SPACING;
1381
+ if (eventType === 0 && tagId === 25 && depthMap[25] > 1 && node.index === 0 && node.parent?.tagId === 33 && orderedItemNumber(node.parent, 0) !== 1 && !isInsideTableCell(state) && !insideOpenInlineDelimiter(node, state) && (blockOpenPrefix(state, "") !== void 0 || endsAtHardBreak(state.buffer))) return DEFAULT_BLOCK_SPACING;
1382
+ if (collapsedByAncestor(node, state, eventType)) return NO_SPACING;
1383
+ if (node.tagHandler?.spacing) return node.tagHandler?.spacing;
1384
+ if (tagId === -1) return NO_SPACING;
1385
+ return DEFAULT_BLOCK_SPACING;
1386
+ }
1387
+ function collapsedByAncestor(node, state, eventType) {
1388
+ const tagId = node.tagId;
1145
1389
  const isBlockElement = tagId !== void 0 && (tagId >= 7 && tagId <= 12 || tagId === 35 || tagId === 36 || tagId === 25 || tagId === 106);
1146
1390
  let currParent = node.parent;
1147
1391
  while (currParent) {
@@ -1154,13 +1398,28 @@ function calculateNewLineConfig(node, state, eventType) {
1154
1398
  currParent = currParent.parent;
1155
1399
  continue;
1156
1400
  }
1157
- return NO_SPACING;
1401
+ return !isBlockChildOfOpenVoid(node);
1158
1402
  }
1159
1403
  currParent = currParent.parent;
1160
1404
  }
1161
- if (node.tagHandler?.spacing) return node.tagHandler?.spacing;
1162
- if (tagId === -1) return NO_SPACING;
1163
- return DEFAULT_BLOCK_SPACING;
1405
+ return false;
1406
+ }
1407
+ function headingKeptInlineInItem(heading) {
1408
+ let blockKept = false;
1409
+ let parent = heading.parent;
1410
+ while (parent) {
1411
+ if (blockKept && parent.tagId !== void 0 && parserTagHandlers[parent.tagId]?.isSelfClosing) return false;
1412
+ if (parent.tagId !== 37 && parent.tagHandler?.collapsesInnerWhiteSpace && wrapperWritesDelimiters(parent)) return true;
1413
+ blockKept ||= isBlockChildOfOpenVoid(parent);
1414
+ parent = parent.parent;
1415
+ }
1416
+ return false;
1417
+ }
1418
+ function wrapperWritesDelimiters(node) {
1419
+ const handler = node.tagHandler;
1420
+ if (handler?.literalEnter && node.hasEnterOutput || handler?.literalExit && handler.literalExitHasOutput) return true;
1421
+ if (handler?.literalEnter && handler.literalExit && !node.hasEnterOutput && !handler.literalExitHasOutput) return false;
1422
+ return Boolean(INLINE_MARKER_TYPE[node.tagId]);
1164
1423
  }
1165
1424
  function wrapperEmitsInlineMarkdown(node, state) {
1166
1425
  const handler = node.tagHandler;
@@ -1168,15 +1427,54 @@ function wrapperEmitsInlineMarkdown(node, state) {
1168
1427
  const tagId = node.tagId;
1169
1428
  return INLINE_MARKER_TYPE[tagId] !== void 0 && INLINE_MARKER_TYPE[tagId] !== 0 || tagId === 26 && (node.attributes?.href !== void 0 || isInsideRawHtmlBlock(state.depthMap)) || tagId === 19 || tagId === 20 || tagId === 21 || tagId === 89 || tagId === 80;
1170
1429
  }
1171
- function hasNonWhitespace(value) {
1172
- for (let i = 0; i < value.length; i++) {
1173
- const c = value.charCodeAt(i);
1174
- if (c !== 32 && c !== 9 && c !== 10 && c !== 12 && c !== 13) return true;
1430
+ function trimLeadingSpaces(value) {
1431
+ let start = 0;
1432
+ while (value.charCodeAt(start) === 32) start++;
1433
+ return start === 0 ? value : value.slice(start);
1434
+ }
1435
+ function exitListMarker(output, continuesItem) {
1436
+ let end = output.length;
1437
+ while (end > 0 && isAsciiWhitespace(output.charCodeAt(end - 1))) end--;
1438
+ if (end === 0) return void 0;
1439
+ for (;;) {
1440
+ let start = end;
1441
+ while (start > 0 && output.charCodeAt(start - 1) !== 10 && output.charCodeAt(start - 1) !== 13) start--;
1442
+ if (start === 0 && continuesItem) return void 0;
1443
+ const marker = writtenListMarker(output.slice(start, end));
1444
+ if (marker !== 0 || start === 0 || start < end && !isAsciiWhitespace(output.charCodeAt(start))) return marker;
1445
+ end = start - 1;
1446
+ }
1447
+ }
1448
+ function writtenListMarker(output) {
1449
+ let last = output.length - 1;
1450
+ while (last >= 0 && isAsciiWhitespace(output.charCodeAt(last))) last--;
1451
+ if (last < 0) return 0;
1452
+ let first = output.lastIndexOf("\n", last) + 1;
1453
+ while (isAsciiWhitespace(output.charCodeAt(first))) first++;
1454
+ let end = first;
1455
+ for (let code = output.charCodeAt(end); code >= 48 && code <= 57; code = output.charCodeAt(end)) end++;
1456
+ const digits = end - first;
1457
+ const marker = output.charCodeAt(end);
1458
+ return (digits === 0 ? marker === 45 || marker === 42 || marker === 43 : digits <= 9 && (marker === 46 || marker === 41)) && (end + 1 === output.length || isAsciiWhitespace(output.charCodeAt(end + 1))) ? marker : 0;
1459
+ }
1460
+ function insideOpenInlineDelimiter(node, state) {
1461
+ const rawHtml = isInsideRawHtmlBlock(state.depthMap);
1462
+ for (let parent = node.parent; parent; parent = parent.parent) {
1463
+ const tagId = parent.tagId;
1464
+ if (parent.tagHandler?.collapsesInnerWhiteSpace && tagId !== 21 && tagId !== 19 && tagId !== 20 && tagId !== 80 && tagId !== 89 && !(rawHtml && tagId === 26) && wrapperEmitsInlineMarkdown(parent, state)) return true;
1175
1465
  }
1176
1466
  return false;
1177
1467
  }
1178
1468
  function isAsciiWhitespace(code) {
1179
- return code === 32 || code >= 9 && code <= 13;
1469
+ return code === 32 || code === 9 || code === 10 || code === 12 || code === 13;
1470
+ }
1471
+ const CLOSED_MARKER_REACH = 32;
1472
+ function isTransientOutput(fragment) {
1473
+ for (let index = 0; index < fragment.length; index++) {
1474
+ const code = fragment.charCodeAt(index);
1475
+ if (code !== 42 && code !== 126 && code !== 96 && code !== 34 && !isAsciiWhitespace(code)) return false;
1476
+ }
1477
+ return true;
1180
1478
  }
1181
1479
  function trimAsciiWhitespaceEnd(value) {
1182
1480
  let end = value.length;
@@ -1188,12 +1486,43 @@ function dropEmptyMarker(buffer, packed, markerType, positions) {
1188
1486
  if ((packed & MARKER_TYPE_MASK) === markerType && idx < buffer.length) return dropEmptyLinkText(buffer, idx, positions) ? idx : -1;
1189
1487
  return -1;
1190
1488
  }
1489
+ function isVerticalTabRun(value) {
1490
+ for (let i = 0; i < value.length; i++) {
1491
+ const c = value.charCodeAt(i);
1492
+ if (c !== 11 && !isAsciiWhitespace(c)) return false;
1493
+ }
1494
+ return true;
1495
+ }
1496
+ function dropVerticalTabMarker(buffer, packed, markerType, marker, positions) {
1497
+ const idx = packed >> 3;
1498
+ const opener = buffer[idx];
1499
+ if ((packed & MARKER_TYPE_MASK) !== markerType || opener === void 0 || !opener.endsWith(marker)) return false;
1500
+ for (let index = idx + 1; index < buffer.length; index++) if (!isVerticalTabRun(buffer[index])) return false;
1501
+ const kept = opener.slice(0, opener.length - marker.length);
1502
+ positions?.replace(idx, idx + 1, [kept]);
1503
+ buffer[idx] = kept;
1504
+ return true;
1505
+ }
1506
+ function hasLabelText(value) {
1507
+ for (let index = 0; index < value.length; index++) {
1508
+ const code = value.charCodeAt(index);
1509
+ if (code === 32 || code >= 9 && code <= 13) continue;
1510
+ if (code < 133 || !(code === 133 || code === 160 || code === 5760 || code >= 8192 && code <= 8202 || code === 8232 || code === 8233 || code === 8239 || code === 8287 || code === 12288)) return true;
1511
+ }
1512
+ return false;
1513
+ }
1514
+ function dropBlankLink(buffer, openFragment, positions) {
1515
+ for (let index = openFragment + 1; index < buffer.length; index++) if (hasLabelText(buffer[index])) return false;
1516
+ positions?.replace(openFragment, buffer.length, []);
1517
+ buffer.length = openFragment;
1518
+ return true;
1519
+ }
1191
1520
  function resetRetractedCaptionFrames(frames, count, fragment) {
1192
1521
  if (!frames) return;
1193
1522
  for (let index = 0; index < count; index++) {
1194
1523
  const offset = index * CAPTION_FRAME_SIZE;
1195
1524
  if (frames[offset + 3] >= fragment) {
1196
- frames[offset + 2] = frames[offset + 2] & -2;
1525
+ frames[offset + 2] = frames[offset + 2] & -10;
1197
1526
  frames[offset + 3] = CAPTION_NO_ANCHOR;
1198
1527
  }
1199
1528
  }
@@ -1235,36 +1564,75 @@ function maxLineLeadingRun(value, marker, indent) {
1235
1564
  let run = 0;
1236
1565
  while (value.charCodeAt(index + run) === marker) run++;
1237
1566
  if (run > max) max = run;
1238
- const newline = value.indexOf("\n", lineStart);
1239
- if (newline === -1) break;
1240
- lineStart = newline + 1;
1567
+ let lineEnd = index + run;
1568
+ while (lineEnd < value.length && value.charCodeAt(lineEnd) !== 10 && value.charCodeAt(lineEnd) !== 13) lineEnd++;
1569
+ if (lineEnd >= value.length) break;
1570
+ lineStart = lineEnd + 1;
1241
1571
  }
1242
1572
  return max;
1243
1573
  }
1244
1574
  function finalizeCodeSpan(state, span) {
1245
- let content = state.buffer.slice(span.fragment + 1).join("");
1246
- if ((state.depthMap[28] || 0) > 0 && content.includes("|")) {
1247
- const original = content;
1248
- content = content.replaceAll("|", "\\|");
1249
- state.outputPositions?.replace(span.fragment + 1, state.buffer.length, [content], (offset) => {
1250
- let added = 0;
1251
- for (let index = 0; index < offset; index++) if (original.charCodeAt(index) === 124) added++;
1252
- return offset + added;
1575
+ const original = state.buffer.slice(span.fragment + 1).join("");
1576
+ const escapePipes = !!state.depthMap[28] && original.includes("|");
1577
+ const offsetChanges = state.outputPositions ? [] : void 0;
1578
+ let delta = 0;
1579
+ const content = original.replace(escapePipes ? /\r\n?|\n|\|/g : /\r\n?|\n/g, (match, offset) => {
1580
+ if (offsetChanges && match === "|") offsetChanges.push({
1581
+ at: offset,
1582
+ delta: ++delta
1583
+ });
1584
+ else if (offsetChanges && match.length === 2) offsetChanges.push({
1585
+ at: offset + 1,
1586
+ delta: --delta
1253
1587
  });
1588
+ return match === "|" ? "\\|" : " ";
1589
+ });
1590
+ if (content !== original) {
1591
+ const mapOffset = offsetChanges?.length ? (offset) => {
1592
+ let low = 0;
1593
+ let high = offsetChanges.length;
1594
+ while (low < high) {
1595
+ const mid = low + high >>> 1;
1596
+ if (offsetChanges[mid].at < offset) low = mid + 1;
1597
+ else high = mid;
1598
+ }
1599
+ return offset + (offsetChanges[low - 1]?.delta ?? 0);
1600
+ } : void 0;
1601
+ state.outputPositions?.replace(span.fragment + 1, state.buffer.length, [content], mapOffset);
1254
1602
  state.buffer.length = span.fragment + 1;
1255
1603
  state.buffer.push(content);
1604
+ noteBufferRewrite(state);
1256
1605
  }
1257
1606
  const delimiter = "`".repeat(Math.max(1, maxBacktickRun(content) + 1));
1258
1607
  const padded = content.startsWith("`") || content.endsWith("`");
1259
1608
  const opening = `${span.prefix}${delimiter}${padded ? " " : ""}`;
1260
1609
  if (state.outputPositions && opening !== state.buffer[span.fragment]) state.outputPositions?.replace(span.fragment, span.fragment + 1, [opening]);
1261
1610
  state.buffer[span.fragment] = opening;
1611
+ noteBufferRewrite(state);
1262
1612
  return `${padded ? " " : ""}${delimiter}`;
1263
1613
  }
1614
+ function hasLiteralTagOverride(overrides) {
1615
+ for (const name in overrides) {
1616
+ const override = overrides[name];
1617
+ if (override && typeof override === "object" && (override.enter !== void 0 || override.exit !== void 0)) return true;
1618
+ }
1619
+ return false;
1620
+ }
1621
+ function notePluginFences(state, output) {
1622
+ if (!state.fencesUnreliable && !state.codeFence && output?.some((part) => part.includes("`") || part.includes("~"))) state.fencesUnreliable = true;
1623
+ }
1624
+ function noteGeneratedFences(state, delimiters) {
1625
+ if (!state.fencesUnreliable && !state.codeFence && (mayOpenFence(delimiters.prefix) || mayOpenFence(delimiters.suffix))) state.fencesUnreliable = true;
1626
+ }
1627
+ function mayOpenFence(delimiter) {
1628
+ return delimiter.includes("`") || delimiter.includes("~~~");
1629
+ }
1264
1630
  function startCodeFence(state, fragment, language, indent) {
1631
+ const markerOffset = state.buffer[fragment].lastIndexOf("```");
1632
+ if (!state.fencesUnreliable && (state.preFenceInline || !opensBlockLine(state.buffer, fragment, markerOffset))) state.fencesUnreliable = true;
1265
1633
  state.codeFence = {
1266
1634
  fragment,
1267
- markerOffset: state.buffer[fragment].lastIndexOf("```"),
1635
+ markerOffset,
1268
1636
  indent,
1269
1637
  language
1270
1638
  };
@@ -1274,14 +1642,17 @@ function finalizeCodeFence(state) {
1274
1642
  const fence = state.codeFence;
1275
1643
  if (!fence) return;
1276
1644
  state.codeFence = void 0;
1645
+ state.preFenceOpener = void 0;
1277
1646
  const marker = fence.language.includes("`") ? "~" : "`";
1278
1647
  const markerCode = marker.charCodeAt(0);
1279
1648
  const content = state.buffer.slice(fence.fragment + 1).join("");
1280
1649
  const delimiter = marker.repeat(Math.max(3, maxLineLeadingRun(content, markerCode, fence.indent) + 1));
1281
- const opening = state.buffer[fence.fragment];
1650
+ let opening = state.buffer[fence.fragment];
1651
+ if (content === "" && fence.indent && opening.endsWith(fence.indent)) opening = opening.slice(0, -fence.indent.length);
1282
1652
  const replacement = `${opening.slice(0, fence.markerOffset)}${delimiter}${opening.slice(fence.markerOffset + 3)}`;
1283
1653
  if (state.outputPositions && replacement !== opening) state.outputPositions?.replace(fence.fragment, fence.fragment + 1, [replacement], (offset) => offset <= fence.markerOffset ? offset : offset + delimiter.length - 3);
1284
1654
  state.buffer[fence.fragment] = replacement;
1655
+ noteBufferRewrite(state);
1285
1656
  return delimiter;
1286
1657
  }
1287
1658
  function stripBlockquoteListIndent(line, listIndent) {
@@ -1302,13 +1673,31 @@ function quotedOffset(content, listIndent, offset) {
1302
1673
  sourceStart = lineEnd + 1;
1303
1674
  }
1304
1675
  }
1676
+ function onItemMarkerLine(state, end = state.buffer.length) {
1677
+ if (!state.listIndent) return false;
1678
+ for (let fragment = end - 1; fragment >= 0; fragment--) {
1679
+ const value = state.buffer[fragment];
1680
+ for (let index = value.length - 1; index >= 0; index--) if (value.charCodeAt(index) !== 32) return listMarkerLineStart(state.buffer, fragment, index, pendingMarkerIndent(state));
1681
+ }
1682
+ return false;
1683
+ }
1305
1684
  function finalizeBlockquote(state) {
1306
1685
  const frame = state.blockquotes.pop();
1307
- if (!frame) return;
1686
+ if (!frame) return false;
1308
1687
  state.bufferedBlockquoteDepth = state.blockquotes.length;
1309
1688
  const buffer = state.buffer;
1310
1689
  const content = trimAsciiWhitespaceEnd(buffer.slice(frame.fragment).join(""));
1311
- if (!content && frame.followsWhitespace) return;
1690
+ if (!content && frame.followsWhitespace) {
1691
+ if (frame.itemSeparatorFragments && !endsAtHardBreak(state.buffer)) {
1692
+ const start = frame.fragment - frame.itemSeparatorFragments;
1693
+ state.outputPositions?.replace(start, buffer.length, []);
1694
+ buffer.length = start;
1695
+ state.lastContentCache = buffer.at(-1);
1696
+ state.lastTextNode = void 0;
1697
+ noteBufferRewrite(state);
1698
+ }
1699
+ return false;
1700
+ }
1312
1701
  const prefix = `${frame.listIndent}>`;
1313
1702
  const quoted = content.split("\n").map((line) => {
1314
1703
  const unindented = stripBlockquoteListIndent(line, frame.listIndent);
@@ -1353,11 +1742,14 @@ function finalizeBlockquote(state) {
1353
1742
  buffer.push(quoted.slice(start, end));
1354
1743
  if (end < quoted.length) buffer.push(quoted.slice(end));
1355
1744
  state.lastContentCache = buffer.at(-1);
1356
- return;
1745
+ noteBufferRewrite(state);
1746
+ return true;
1357
1747
  }
1358
1748
  state.outputPositions?.replace(frame.fragment, buffer.length, [quoted], mapPosition);
1359
1749
  buffer.splice(frame.fragment, buffer.length - frame.fragment, quoted);
1360
1750
  state.lastContentCache = quoted;
1751
+ noteBufferRewrite(state);
1752
+ return true;
1361
1753
  }
1362
1754
  function collapseNestedBlockquoteSeparator(buffer, positions) {
1363
1755
  if (newlineRunBefore(buffer, buffer.length) < 2) return;
@@ -1368,9 +1760,10 @@ function collapseNestedBlockquoteSeparator(buffer, positions) {
1368
1760
  }
1369
1761
  function flushPreFence(state) {
1370
1762
  state.preFencePending = false;
1763
+ state.headingBreakPending = false;
1371
1764
  state.preFenceOwnerDepth = state.preFencePendingDepth;
1372
1765
  const lang = state.preFenceLang || "";
1373
- const fence = (state.depthMap[25] || 0) > 0 ? `${blockOpenPrefix(state.buffer, state.listIndent) ?? ""}\`\`\`${lang}\n${state.listIndent}` : `\`\`\`${lang}\n`;
1766
+ const fence = (state.depthMap[25] || 0) > 0 ? `${blockOpenPrefix(state, state.listIndent) ?? ""}\`\`\`${lang}\n${state.listIndent}` : `\`\`\`${lang}\n`;
1374
1767
  state.buffer.push(fence);
1375
1768
  startCodeFence(state, state.buffer.length - 1, lang, state.listIndent);
1376
1769
  state.lastContentCache = fence;
@@ -1386,6 +1779,7 @@ function consumePendingPreChild(state, node, eventType, beforeFlush) {
1386
1779
  else if (element.tagId !== 34 && element.tagId !== 106 && !suppressesFormattingInPre(element.tagId)) {
1387
1780
  beforeFlush();
1388
1781
  flushPreFence(state);
1782
+ state.preFenceOpener = element;
1389
1783
  }
1390
1784
  return false;
1391
1785
  }
@@ -1400,7 +1794,7 @@ function consumeGfmAction(action, state, lifecycle) {
1400
1794
  switch (action._tag) {
1401
1795
  case "BlockquoteEnter": return action.output;
1402
1796
  case "BlockquoteExit":
1403
- finalizeBlockquote(state);
1797
+ lifecycle.quoteWritten = finalizeBlockquote(state);
1404
1798
  return;
1405
1799
  case "PreEnter":
1406
1800
  if (!state.preFenceOwnerDepth && !state.preFencePending) {
@@ -1411,9 +1805,13 @@ function consumeGfmAction(action, state, lifecycle) {
1411
1805
  return;
1412
1806
  case "PreExit": {
1413
1807
  const depth = state.depthMap[34] + 1;
1414
- if (state.preFencePendingDepth === depth) state.preFencePending = false;
1808
+ if (state.preFencePendingDepth === depth) {
1809
+ state.preFencePending = false;
1810
+ state.preFenceLang = "";
1811
+ }
1415
1812
  if (state.preFenceOwnerDepth !== depth) return void 0;
1416
1813
  state.preFenceOwnerDepth = 0;
1814
+ state.preFenceLang = "";
1417
1815
  state.lastTextNode = void 0;
1418
1816
  const indent = state.listIndent;
1419
1817
  const output = (state.depthMap[25] || 0) > 0 ? `\n${indent}\`\`\`\n\n${indent}` : `\n\`\`\``;
@@ -1431,28 +1829,48 @@ function consumeGfmAction(action, state, lifecycle) {
1431
1829
  return action.output;
1432
1830
  }
1433
1831
  }
1434
- function commitGfmAction(action, state, lifecycle, outputStart, owner) {
1832
+ function commitGfmAction(action, state, lifecycle, outputStart, owner, keepsQuoteSeparator, rawHtmlQuoteBoundary = false) {
1435
1833
  switch (action._tag) {
1436
1834
  case "BlockquoteEnter": {
1437
- if (state.blockquotes.length > 0) collapseNestedBlockquoteSeparator(state.buffer, state.outputPositions);
1835
+ if (state.blockquotes.length > 0 && !keepsQuoteSeparator && (!rawHtmlQuoteBoundary || newlineRunBefore(state.buffer, state.buffer.length) > 2)) {
1836
+ collapseNestedBlockquoteSeparator(state.buffer, state.outputPositions);
1837
+ for (const frame of state.blockquotes) frame.fragment = Math.min(frame.fragment, state.buffer.length);
1838
+ outputStart = Math.min(outputStart, state.buffer.length);
1839
+ noteBufferRewrite(state);
1840
+ }
1438
1841
  const before = lastOutputChar(state.buffer);
1439
1842
  state.blockquotes.push({
1440
1843
  fragment: state.buffer.length,
1441
- listIndent: state.listIndent,
1844
+ itemSeparatorFragments: onItemMarkerLine(state, outputStart) ? state.buffer.length - outputStart : 0,
1845
+ listIndent: isInsideTableCell(state) ? "" : state.listIndent,
1442
1846
  followsWhitespace: before === -1 ? state.lastContentCache !== void 0 && isAsciiWhitespace(state.lastContentCache.charCodeAt(state.lastContentCache.length - 1)) : isAsciiWhitespace(before)
1443
1847
  });
1444
1848
  state.bufferedBlockquoteDepth = state.blockquotes.length;
1445
1849
  break;
1446
1850
  }
1447
1851
  case "CodeSpanEnter":
1448
- lifecycle.openCodeSpans.push({
1449
- owner,
1450
- fragment: outputStart,
1451
- prefix: action.output.slice(0, -1)
1452
- });
1852
+ for (let index = outputStart; index < state.buffer.length; index++) {
1853
+ const output = state.buffer[index];
1854
+ if (output.endsWith("`")) {
1855
+ const span = {
1856
+ kind: "span",
1857
+ owner,
1858
+ fragment: index,
1859
+ prefix: output.slice(0, -1)
1860
+ };
1861
+ lifecycle.openCodeSpans.push(span);
1862
+ if (!owner.tagHandler?.literalEnter) state.codeText ??= span;
1863
+ break;
1864
+ }
1865
+ }
1453
1866
  break;
1454
1867
  case "CodeFenceEnter": {
1455
- const fenceFragment = state.buffer.findIndex((fragment, index) => index >= outputStart && fragment.includes("```"));
1868
+ const buffer = state.buffer;
1869
+ let fenceFragment = -1;
1870
+ for (let index = outputStart; index < buffer.length; index++) if (buffer[index].includes("```")) {
1871
+ fenceFragment = index;
1872
+ break;
1873
+ }
1456
1874
  if (fenceFragment < 0) throw new Error("code fence opener missing from output");
1457
1875
  startCodeFence(state, fenceFragment, action.language, state.listIndent);
1458
1876
  break;
@@ -1465,6 +1883,7 @@ function createMarkdownProcessor(options = {}, createStream) {
1465
1883
  outputFormat: "markdown",
1466
1884
  buffer: [],
1467
1885
  outputPositions: void 0,
1886
+ codeText: void 0,
1468
1887
  depthMap: /* @__PURE__ */ new Uint16Array(113),
1469
1888
  depth: 0,
1470
1889
  listIndent: "",
@@ -1472,14 +1891,34 @@ function createMarkdownProcessor(options = {}, createStream) {
1472
1891
  blockquotes: [],
1473
1892
  bufferedBlockquoteDepth: 0,
1474
1893
  emptyItemFragment: void 0,
1894
+ headingBreakPending: false,
1895
+ emptyItemAfterCr: false,
1896
+ pendingLeadingBlank: false,
1897
+ pendingPairSeparator: false,
1898
+ pendingDecodedBlank: false,
1899
+ separatorPending: false,
1900
+ cacheFollowsSeparator: false,
1475
1901
  tableRenderedTable: false,
1476
1902
  tableCurrentRowCells: 0,
1477
1903
  tableColumnAlignments: [],
1478
1904
  tableHeaderCells: 0,
1479
1905
  preFencePending: false,
1480
1906
  preFencePendingDepth: 0,
1481
- preFenceOwnerDepth: 0
1907
+ preFenceOwnerDepth: 0,
1908
+ listMarkers: [],
1909
+ lastItemStar: false,
1910
+ fencesUnreliable: hasLiteralTagOverride(options.tagOverrides),
1911
+ preFenceOpener: void 0
1482
1912
  };
1913
+ let siblingListMarker = 0;
1914
+ let siblingListDepth = 0;
1915
+ let siblingListQuotes = 0;
1916
+ const listMarkerOwners = options.plugins?.length ? [] : void 0;
1917
+ const listMarkerDepths = listMarkerOwners ? [] : void 0;
1918
+ const eventPath = listMarkerOwners ? [] : void 0;
1919
+ const missingAncestors = listMarkerOwners ? [] : void 0;
1920
+ let inGapEvent = false;
1921
+ let listClosedInGap = false;
1483
1922
  const bufferScan = [
1484
1923
  false,
1485
1924
  0,
@@ -1490,17 +1929,66 @@ function createMarkdownProcessor(options = {}, createStream) {
1490
1929
  0
1491
1930
  ];
1492
1931
  let inRawHtmlRegion = false;
1932
+ let rawHtmlNeedsBoundary = false;
1933
+ let pendingRawHtmlBoundary = false;
1493
1934
  const openMarkers = [];
1494
1935
  let openMarkerCount = 0;
1936
+ let pendingCloser = 0;
1937
+ const openMarkerClosers = [];
1938
+ const closedMarkers = [];
1939
+ let closedMarkerCount = 0;
1940
+ let reopenedDelimiter = "";
1941
+ let reopenedType = 0;
1942
+ let unmergedOpener = -1;
1943
+ let unmergedSlot = -1;
1944
+ function heldClosedMarker() {
1945
+ if (closedMarkerCount === 0) return Infinity;
1946
+ const buffer = state.buffer;
1947
+ let reach = CLOSED_MARKER_REACH;
1948
+ for (let index = closedMarkers[closedMarkerCount - 1] + 1; index < buffer.length; index++) {
1949
+ const fragment = buffer[index];
1950
+ reach -= fragment.length;
1951
+ if (reach < 0 || !isTransientOutput(fragment)) {
1952
+ closedMarkerCount = 0;
1953
+ return Infinity;
1954
+ }
1955
+ }
1956
+ if (closedMarkers[closedMarkerCount - 1] >= buffer.length) {
1957
+ closedMarkerCount = 0;
1958
+ return Infinity;
1959
+ }
1960
+ return closedMarkers[0];
1961
+ }
1962
+ const openMarkerFollowsSpace = [];
1963
+ const openMarkerSeparatorTrimmed = [];
1964
+ const openMarkerRunLength = [];
1965
+ let silentMarkerCount = 0;
1966
+ let blankMarkerCount = 0;
1967
+ let breakAfterLastText = false;
1968
+ let pendingSpaceFragment = -1;
1969
+ let pendingSpaceOwned = false;
1970
+ let pendingSpaceTrimmed = false;
1971
+ const literalOpeners = [];
1495
1972
  let captionFrames;
1496
1973
  let captionFrameCount = 0;
1497
1974
  let captionBoundary = 0;
1975
+ let quoteTentativeSpacing;
1498
1976
  let captionBoundarySpacing = 0;
1499
1977
  let captionBreakRun = 0;
1500
- const gfmLifecycle = { openCodeSpans: [] };
1978
+ let captionLineEnd = 0;
1979
+ let captionLineTail = "";
1980
+ let captionLineFragment = -1;
1981
+ let captionLineHead = "";
1982
+ let captionLineOpens = false;
1983
+ const gfmLifecycle = {
1984
+ openCodeSpans: [],
1985
+ quoteWritten: false
1986
+ };
1501
1987
  let openLinkFragment = -1;
1988
+ let openLinkHeadingBreak = false;
1502
1989
  let openLinkCaptionBreakRun = 0;
1503
1990
  let openLinkCaptionFlags;
1991
+ let blankCaptionFrames = 0;
1504
1992
  const clean = options.clean;
1505
1993
  const cleanRules = typeof clean === "object" && clean !== null ? clean : void 0;
1506
1994
  const cleanEmptyLinkText = clean === true || cleanRules?.emptyLinkText === true;
@@ -1510,7 +1998,8 @@ function createMarkdownProcessor(options = {}, createStream) {
1510
1998
  function captionNeedsPreparation() {
1511
1999
  return captionBoundary !== 0 || captionFrameCount !== 0 && (captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 2] & CAPTION_OPEN) === 0;
1512
2000
  }
1513
- function openLink(fragment) {
2001
+ function openLink(fragment, headingBreak) {
2002
+ openLinkHeadingBreak = headingBreak;
1514
2003
  if (!cleanEmptyLinkText) {
1515
2004
  openLinkFragment = -fragment - 2;
1516
2005
  return;
@@ -1546,7 +2035,7 @@ function createMarkdownProcessor(options = {}, createStream) {
1546
2035
  if (spacing === 0) return "";
1547
2036
  if (spacing === CAPTION_DEFAULT_SPACING) spacing = DEFAULT_BLOCK_SPACING[0];
1548
2037
  const indent = includeListIndent ? state.listIndent : "";
1549
- const blockPrefix = blockOpenPrefix(state.buffer, indent, beforeFragment);
2038
+ const blockPrefix = blockOpenPrefix(state, indent, beforeFragment);
1550
2039
  const trailingNewLines = newlineRunBeforePrefix(state.buffer, beforeFragment, indent);
1551
2040
  if (blockPrefix === void 0 && trailingNewLines === 0) return "";
1552
2041
  const missingNewLines = Math.max(0, spacing - trailingNewLines);
@@ -1554,12 +2043,13 @@ function createMarkdownProcessor(options = {}, createStream) {
1554
2043
  if (!prefix) return "";
1555
2044
  const lastIndex = beforeFragment - 1;
1556
2045
  const last = state.buffer[lastIndex];
1557
- if (prefix.charCodeAt(0) === 10 && last?.endsWith(" ")) {
2046
+ if (captionBoundary !== 3 && captionBoundary !== 4 && prefix.charCodeAt(0) === 10 && last?.endsWith(" ")) {
1558
2047
  const trimmed = last.slice(0, -1);
1559
2048
  state.outputPositions?.replace(lastIndex, lastIndex + 1, [trimmed]);
1560
2049
  state.buffer[lastIndex] = trimmed;
1561
2050
  if (state.lastContentCache === last) state.lastContentCache = trimmed;
1562
2051
  state.lastTextNode = void 0;
2052
+ noteBufferRewrite(state);
1563
2053
  }
1564
2054
  return prefix;
1565
2055
  }
@@ -1571,35 +2061,62 @@ function createMarkdownProcessor(options = {}, createStream) {
1571
2061
  state.pendingInlineWhitespace = false;
1572
2062
  return true;
1573
2063
  }
2064
+ function restoreQuoteParentBoundary() {
2065
+ if (captionBoundary === 4 && quoteTentativeSpacing && state.buffer.at(-1) === quoteTentativeSpacing) {
2066
+ const index = state.buffer.length - 1;
2067
+ state.outputPositions?.replace(index, index + 1, []);
2068
+ state.buffer.pop();
2069
+ state.lastContentCache = state.buffer.at(-1);
2070
+ state.lastTextNode = void 0;
2071
+ noteBufferRewrite(state);
2072
+ captionBoundary = 3;
2073
+ quoteTentativeSpacing = void 0;
2074
+ }
2075
+ }
1574
2076
  function prepareCaptionOutput(explicitTop, includeBoundaryListIndent = true) {
1575
2077
  let changed = false;
1576
- if (captionBoundary === 1) changed = appendCaptionSpacing(captionBoundarySpacing, includeBoundaryListIndent);
2078
+ if (captionBoundary === 1 || captionBoundary === 3) changed = appendCaptionSpacing(captionBoundarySpacing, includeBoundaryListIndent);
1577
2079
  const frames = captionFrames;
1578
- if (frames) for (let index = 0; index < captionFrameCount; index++) {
1579
- const offset = index * CAPTION_FRAME_SIZE;
1580
- let flags = frames[offset + 2];
1581
- if (flags & CAPTION_OPEN) continue;
1582
- const anchor = frames[offset + 3];
1583
- const beforeFragment = anchor === CAPTION_NO_ANCHOR ? state.buffer.length : anchor;
1584
- let opening = flags & CAPTION_INTERNAL_BREAK ? "" : captionSpacingPrefix(frames[offset], true, beforeFragment);
1585
- flags |= CAPTION_OPEN;
1586
- if (!explicitTop || index !== captionFrameCount - 1) opening += "*";
1587
- if (opening) {
1588
- if (beforeFragment === state.buffer.length) {
1589
- state.buffer.push(opening);
1590
- state.lastContentCache = opening;
1591
- } else {
1592
- const anchored = state.buffer[beforeFragment];
1593
- const replacement = opening + anchored;
1594
- state.outputPositions?.replace(beforeFragment, beforeFragment + 1, [replacement], (offset) => offset + opening.length);
1595
- state.buffer[beforeFragment] = replacement;
1596
- const codeSpan = gfmLifecycle.openCodeSpans.at(-1);
1597
- if (codeSpan?.fragment === beforeFragment) codeSpan.prefix = opening + codeSpan.prefix;
1598
- if (state.lastContentCache === anchored) state.lastContentCache = replacement;
2080
+ if (frames) {
2081
+ let insertedFragment = -1;
2082
+ let insertedLength = 0;
2083
+ for (let index = 0; index < captionFrameCount; index++) {
2084
+ const offset = index * CAPTION_FRAME_SIZE;
2085
+ let flags = frames[offset + 2];
2086
+ if (flags & CAPTION_OPEN) continue;
2087
+ const anchor = frames[offset + 3];
2088
+ const beforeFragment = anchor === CAPTION_NO_ANCHOR ? state.buffer.length : anchor;
2089
+ let opening = flags & CAPTION_INTERNAL_BREAK && !(flags & CAPTION_BLOCK_PREFIX) ? "" : captionSpacingPrefix(frames[offset], true, beforeFragment);
2090
+ if (state.pendingInlineWhitespace) {
2091
+ if (!opening) {
2092
+ const last = lastOutputChar(state.buffer, beforeFragment);
2093
+ if (last !== -1 && last !== 32 && last !== 10 && last !== 9 && last !== 13) opening = " ";
2094
+ }
2095
+ state.pendingInlineWhitespace = false;
2096
+ }
2097
+ flags |= CAPTION_OPEN;
2098
+ if (!explicitTop || index !== captionFrameCount - 1) opening += "*";
2099
+ if (opening) {
2100
+ if (beforeFragment === state.buffer.length) {
2101
+ state.buffer.push(opening);
2102
+ state.lastContentCache = opening;
2103
+ } else {
2104
+ const anchored = state.buffer[beforeFragment];
2105
+ const at = insertedFragment === beforeFragment ? insertedLength : 0;
2106
+ const replacement = anchored.slice(0, at) + opening + anchored.slice(at);
2107
+ state.outputPositions?.replace(beforeFragment, beforeFragment + 1, [replacement], (offset) => offset >= at ? offset + opening.length : offset);
2108
+ state.buffer[beforeFragment] = replacement;
2109
+ insertedFragment = beforeFragment;
2110
+ insertedLength = at + opening.length;
2111
+ noteBufferRewrite(state);
2112
+ const codeSpan = gfmLifecycle.openCodeSpans.at(-1);
2113
+ if (codeSpan?.fragment === beforeFragment) codeSpan.prefix = codeSpan.prefix.slice(0, at) + opening + codeSpan.prefix.slice(at);
2114
+ if (state.lastContentCache === anchored) state.lastContentCache = replacement;
2115
+ }
2116
+ changed = true;
1599
2117
  }
1600
- changed = true;
2118
+ frames[offset + 2] = flags;
1601
2119
  }
1602
- frames[offset + 2] = flags;
1603
2120
  }
1604
2121
  return changed;
1605
2122
  }
@@ -1621,17 +2138,37 @@ function createMarkdownProcessor(options = {}, createStream) {
1621
2138
  }
1622
2139
  }
1623
2140
  function consumeCaptionTransition(isInlineElement, tagId) {
1624
- captionBoundary = isInlineElement && tagId !== 27 && tagId !== 6 ? 2 : 0;
2141
+ if (!isInlineElement || tagId === 27 || tagId === 6) captionBoundary = 0;
2142
+ else if (captionBoundary === 3) {
2143
+ captionBoundary = 4;
2144
+ quoteTentativeSpacing = void 0;
2145
+ } else if (captionBoundary < 4) captionBoundary = 2;
2146
+ }
2147
+ function settleBlankCaption() {
2148
+ const frames = captionFrames;
2149
+ const end = Math.min(blankCaptionFrames, captionFrameCount);
2150
+ for (let index = 0; index < end; index++) if ((frames[index * CAPTION_FRAME_SIZE + 2] & CAPTION_OPEN) === 0) {
2151
+ state.headingBreakPending = false;
2152
+ flushCaptionBreakRun();
2153
+ prepareCaptionOutput(false);
2154
+ commitCaptionFrames();
2155
+ return;
2156
+ }
2157
+ if (openLinkFragment < 0 && openMarkerCount === 0) commitCaptionFrames();
1625
2158
  }
1626
2159
  function anchorPendingCaptions(fragment) {
1627
2160
  const frames = captionFrames;
1628
2161
  if (!frames) return;
1629
2162
  for (let index = 0; index < captionFrameCount; index++) {
1630
2163
  const offset = index * CAPTION_FRAME_SIZE;
1631
- if ((frames[offset + 2] & CAPTION_OPEN) === 0 && frames[offset + 3] === CAPTION_NO_ANCHOR) frames[offset + 3] = fragment;
2164
+ if ((frames[offset + 2] & CAPTION_OPEN) === 0 && frames[offset + 3] === CAPTION_NO_ANCHOR) {
2165
+ frames[offset + 3] = fragment;
2166
+ if (!(frames[offset + 2] & CAPTION_INTERNAL_BREAK)) frames[offset + 2] |= CAPTION_BLOCK_PREFIX;
2167
+ }
1632
2168
  }
1633
2169
  }
1634
2170
  function commitCaptionFrames() {
2171
+ blankCaptionFrames = 0;
1635
2172
  const frames = captionFrames;
1636
2173
  if (!frames) return;
1637
2174
  for (let index = 0; index < captionFrameCount; index++) {
@@ -1639,7 +2176,7 @@ function createMarkdownProcessor(options = {}, createStream) {
1639
2176
  if (frames[offset + 2] & CAPTION_OPEN) frames[offset + 3] = CAPTION_NO_ANCHOR;
1640
2177
  }
1641
2178
  }
1642
- function flushCaptionBreakRun() {
2179
+ function flushCaptionBreakRun(beforeText = false) {
1643
2180
  if (captionBreakRun === 0) return false;
1644
2181
  let index = state.buffer.length;
1645
2182
  while (index !== 0) {
@@ -1651,13 +2188,43 @@ function createMarkdownProcessor(options = {}, createStream) {
1651
2188
  state.outputPositions?.replace(index, state.buffer.length, [value.slice(0, end)]);
1652
2189
  state.buffer[index] = value.slice(0, end);
1653
2190
  state.buffer.length = index + 1;
2191
+ noteBufferRewrite(state);
1654
2192
  break;
1655
2193
  }
1656
2194
  state.outputPositions?.replace(index, state.buffer.length, []);
1657
2195
  state.buffer.length = index;
2196
+ noteBufferRewrite(state);
1658
2197
  }
1659
- const output = ` \n${state.listIndent}`.repeat(captionBreakRun);
2198
+ const output = (gfmLifecycle.openCodeSpans.length ? "\n" : ` \n${state.listIndent}`).repeat(captionBreakRun);
1660
2199
  captionBreakRun = 0;
2200
+ if (beforeText && !gfmLifecycle.openCodeSpans.length && openMarkerCount && (openMarkers[openMarkerCount - 1] & MARKER_TYPE_MASK) <= 4) for (let frame = 0; frame < captionFrameCount; frame++) {
2201
+ const offset = frame * CAPTION_FRAME_SIZE;
2202
+ const anchor = captionFrames[offset + 3];
2203
+ if (captionFrames[offset + 2] & CAPTION_OPEN || anchor === CAPTION_NO_ANCHOR) continue;
2204
+ let onlyOpeners = true;
2205
+ for (let index = anchor; index < state.buffer.length && onlyOpeners; index++) {
2206
+ const fragment = state.buffer[index];
2207
+ for (let at = 0; at < fragment.length; at++) {
2208
+ const code = fragment.charCodeAt(at);
2209
+ if (code !== 42 && code !== 126) {
2210
+ onlyOpeners = false;
2211
+ break;
2212
+ }
2213
+ }
2214
+ }
2215
+ if (onlyOpeners) {
2216
+ prepareCaptionOutput(false);
2217
+ const fragment = state.buffer[anchor];
2218
+ let at = fragment.length;
2219
+ while (at > 0 && (fragment.charCodeAt(at - 1) === 42 || fragment.charCodeAt(at - 1) === 126)) at--;
2220
+ const replacement = fragment.slice(0, at) + output + fragment.slice(at);
2221
+ state.outputPositions?.replace(anchor, anchor + 1, [replacement], (position) => position >= at ? position + output.length : position);
2222
+ state.buffer[anchor] = replacement;
2223
+ state.lastContentCache = state.buffer.at(-1);
2224
+ noteBufferRewrite(state);
2225
+ return true;
2226
+ }
2227
+ }
1661
2228
  state.buffer.push(output);
1662
2229
  state.lastContentCache = output;
1663
2230
  return true;
@@ -1679,28 +2246,190 @@ function createMarkdownProcessor(options = {}, createStream) {
1679
2246
  state.buffer.length = anchor;
1680
2247
  state.lastContentCache = state.buffer.at(-1);
1681
2248
  state.lastTextNode = void 0;
1682
- } else if (captionBreakRun !== 0 && captionFrameCount === 0) captionBoundary = 2;
2249
+ noteBufferRewrite(state);
2250
+ restoreQuoteParentBoundary();
2251
+ } else if (captionBreakRun !== 0 && captionFrameCount === 0 && captionBoundary < 3) captionBoundary = 2;
2252
+ }
2253
+ function hoistOpenerSpace() {
2254
+ const buffer = state.buffer;
2255
+ const depthMap = state.depthMap;
2256
+ const index = openMarkerCount - 1;
2257
+ let fragment = openMarkers[index] >> 3;
2258
+ const reopened = (openMarkers[index] & MARKER_TYPE_MASK) === MARKER_TYPE_MASK;
2259
+ if ((reopened ? fragment !== buffer.length : fragment !== buffer.length - 1 || (openMarkers[index] & MARKER_TYPE_MASK) > 4) || depthMap[23] || depthMap[34] || depthMap[46] || depthMap[82] || depthMap[92]) return false;
2260
+ if (reopened) {
2261
+ const before = lastOutputChar(buffer);
2262
+ if (before !== -1 && before !== 32 && before !== 10 && before !== 9) {
2263
+ buffer.push(" ");
2264
+ openMarkers[index] = buffer.length << 3 | MARKER_TYPE_MASK;
2265
+ openMarkerFollowsSpace[index] = true;
2266
+ }
2267
+ return true;
2268
+ }
2269
+ if (state.blockquotes.at(-1)?.fragment === fragment + 1) return false;
2270
+ fragment -= openMarkerRunLength[index] - 1;
2271
+ if (literalOpeners.length) {
2272
+ const link = openLinkFragment < -1 ? -openLinkFragment - 2 : openLinkFragment;
2273
+ let at = fragment;
2274
+ while (at > 0 && !buffer[at - 1]) at--;
2275
+ if (followsLiteralOpener(link >= 0 && link === at - 1 ? link : fragment)) return true;
2276
+ }
2277
+ if (buffer[fragment].charCodeAt(0) === 32) return true;
2278
+ let previous = fragment;
2279
+ let before = -1;
2280
+ while (before === -1 && --previous >= 0) {
2281
+ const value = buffer[previous];
2282
+ if (value) before = value.charCodeAt(value.length - 1);
2283
+ }
2284
+ if (previous >= 0 && previous === (openLinkFragment < -1 ? -openLinkFragment - 2 : openLinkFragment)) before = lastOutputChar(buffer, previous);
2285
+ if (before !== -1 && before !== 32 && before !== 10 && before !== 9) {
2286
+ const opener = ` ${buffer[fragment]}`;
2287
+ state.outputPositions?.replace(fragment, fragment + 1, [opener], (offset) => offset > 0 ? offset + 1 : offset);
2288
+ buffer[fragment] = opener;
2289
+ noteBufferRewrite(state);
2290
+ }
2291
+ return true;
2292
+ }
2293
+ function placeLeadingBlank() {
2294
+ const depthMap = state.depthMap;
2295
+ if (depthMap[23] || depthMap[34] || depthMap[46] || depthMap[82] || depthMap[92] || openMarkerCount && hoistOpenerSpace()) return;
2296
+ const end = state.buffer.length - 1;
2297
+ const link = openLinkFragment < -1 ? -openLinkFragment - 2 : openLinkFragment;
2298
+ const opener = openMarkerCount ? openMarkers[openMarkerCount - 1] : MARKER_TYPE_MASK;
2299
+ if (!((opener & MARKER_TYPE_MASK) !== MARKER_TYPE_MASK && opener >> 3 === end) && !(link >= 0 && link === end) && !(literalOpeners.length && followsLiteralOpener(end + 1))) {
2300
+ state.pendingInlineWhitespace = true;
2301
+ state.pendingLeadingBlank = true;
2302
+ state.pendingPairSeparator = false;
2303
+ state.pendingDecodedBlank = false;
2304
+ }
2305
+ }
2306
+ function followsLiteralOpener(fragment) {
2307
+ const end = literalOpeners[literalOpeners.length - 1];
2308
+ if (end < 0 || end > fragment || fragment > state.buffer.length) return false;
2309
+ for (let index = end; index < fragment; index++) if (state.buffer[index]) return false;
2310
+ return true;
2311
+ }
2312
+ function holdLiteralOpener(held) {
2313
+ const end = literalOpeners[literalOpeners.length - 1];
2314
+ if (end < 0 || end >= held) return held;
2315
+ const limit = Math.min(held, state.buffer.length);
2316
+ for (let index = end; index < limit; index++) if (state.buffer[index]) {
2317
+ for (let pair = 1; pair < literalOpeners.length; pair += 2) literalOpeners[pair] = -1;
2318
+ return held;
2319
+ }
2320
+ return end;
2321
+ }
2322
+ function captionExitOpensBlockLine(buff) {
2323
+ let fragment = buff.length - 1;
2324
+ let cursor = buff[fragment].length;
2325
+ let runFragment = -1;
2326
+ let runCursor = 0;
2327
+ for (;;) {
2328
+ if (fragment === captionLineEnd - 1 && cursor === buff[fragment].length && captionLineFragment >= 0 && buff[fragment] === captionLineTail && buff[captionLineFragment] === captionLineHead) {
2329
+ captionLineEnd = buff.length;
2330
+ captionLineTail = buff[captionLineEnd - 1];
2331
+ return captionLineOpens;
2332
+ }
2333
+ if (cursor === 0) {
2334
+ if (fragment === 0) break;
2335
+ cursor = buff[--fragment].length;
2336
+ continue;
2337
+ }
2338
+ if (buff[fragment].charCodeAt(cursor - 1) !== 32) break;
2339
+ runFragment = fragment;
2340
+ runCursor = --cursor;
2341
+ }
2342
+ captionLineEnd = buff.length;
2343
+ captionLineTail = buff[captionLineEnd - 1];
2344
+ captionLineFragment = runFragment;
2345
+ captionLineHead = runFragment < 0 ? "" : buff[runFragment];
2346
+ captionLineOpens = runFragment < 0 ? opensBlockLine(buff, buff.length - 1, buff.at(-1).length) : opensBlockLine(buff, runFragment, runCursor + 1);
2347
+ return captionLineOpens;
2348
+ }
2349
+ function finishRawHtmlBlock(value, generated = false) {
2350
+ if (!pendingRawHtmlBoundary || isInsideRawHtmlBlock(state.depthMap) || !hasNonWhitespace(value)) return;
2351
+ pendingRawHtmlBoundary = false;
2352
+ let leadingNewlines = 0;
2353
+ if (generated) for (let i = 0; i < value.length; i++) {
2354
+ const code = value.charCodeAt(i);
2355
+ if (code === 10) leadingNewlines++;
2356
+ else if (code !== 32 && code !== 9 && code !== 13) break;
2357
+ }
2358
+ let newlines = leadingNewlines;
2359
+ let scanning = true;
2360
+ for (let i = state.buffer.length - 1; i >= 0 && scanning; i--) {
2361
+ const fragment = state.buffer[i];
2362
+ for (let j = fragment.length - 1; j >= 0; j--) {
2363
+ const code = fragment.charCodeAt(j);
2364
+ if (code === 10) {
2365
+ if (++newlines === 2) return;
2366
+ } else if (code !== 32 && code !== 9 && code !== 13) {
2367
+ scanning = false;
2368
+ break;
2369
+ }
2370
+ }
2371
+ }
2372
+ const separator = "\n".repeat(Math.max(0, 2 - newlines)) + (leadingNewlines ? "" : state.listIndent);
2373
+ state.buffer.push(separator);
2374
+ state.lastContentCache = separator;
2375
+ state.lastTextNode = void 0;
1683
2376
  }
1684
2377
  function processTextNode(textNode, lastNode, lastChar) {
2378
+ if (pendingRawHtmlBoundary) {
2379
+ finishRawHtmlBlock(textNode.value);
2380
+ if (!pendingRawHtmlBoundary) {
2381
+ const value = textNode.value;
2382
+ let start = 0;
2383
+ while (start < value.length) {
2384
+ const code = value.charCodeAt(start);
2385
+ if (code !== 32 && code !== 9 && code !== 10 && code !== 13) break;
2386
+ start++;
2387
+ }
2388
+ if (start !== 0) textNode.value = value.slice(start);
2389
+ lastChar = "\n";
2390
+ }
2391
+ }
1685
2392
  if (textNode.trimsAtLineStart) trimTextAtLineStart(textNode, state.buffer);
2393
+ if (textNode.sourceLead && openLinkFragment !== -1 && (openLinkFragment < -1 ? -openLinkFragment - 2 : openLinkFragment) === state.buffer.length - 1) dropSourceLead(textNode);
1686
2394
  if (textNode.value) {
1687
2395
  if (textNode.excludedFromMarkdown) return;
1688
2396
  const ownsCaptionSpace = captionNeedsPreparation();
1689
2397
  if (ownsCaptionSpace) {
1690
- if (textNode.value.charCodeAt(0) === 32) textNode.value = textNode.value.slice(1);
2398
+ if (captionBoundary !== 5 && textNode.value.charCodeAt(0) === 32) textNode.value = textNode.value.slice(1);
1691
2399
  if (!hasNonWhitespace(textNode.value)) return;
1692
- flushCaptionBreakRun();
2400
+ flushCaptionBreakRun(true);
1693
2401
  prepareCaptionOutput(false);
1694
- commitCaptionFrames();
2402
+ if (openLinkFragment >= 0 && !hasLabelText(textNode.value)) blankCaptionFrames = captionFrameCount;
2403
+ else commitCaptionFrames();
1695
2404
  captionBoundary = 0;
1696
2405
  }
1697
2406
  if (state.pendingInlineWhitespace) {
1698
- if (!textNode.value.trim()) return;
1699
- if (lastChar && !" \n \r".includes(lastChar) && !" \n \r".includes(textNode.value[0] || "")) textNode.value = ` ${textNode.value}`;
2407
+ const blank = !hasNonWhitespace(textNode.value);
2408
+ if (blank) {
2409
+ if (!state.pendingLeadingBlank || state.pendingPairSeparator) return;
2410
+ if (textNode.value !== " " || !textNode.containsWhitespace) {
2411
+ state.pendingDecodedBlank = true;
2412
+ return;
2413
+ }
2414
+ }
2415
+ if (!blank && lastChar && !" \n \r".includes(lastChar) && !" \n \r".includes(textNode.value[0] || "") && !(literalOpeners.length && followsLiteralOpener(state.buffer.length)) && !(openMarkerCount && hoistOpenerSpace())) {
2416
+ if (textNode.generatedMarkdown?.prefix || state.pendingLeadingBlank) {
2417
+ state.buffer.push(" ");
2418
+ state.lastContentCache = " ";
2419
+ state.separatorPending = true;
2420
+ lastChar = " ";
2421
+ } else textNode.value = ` ${textNode.value}`;
2422
+ }
1700
2423
  state.pendingInlineWhitespace = false;
1701
2424
  }
1702
2425
  if (textNode.value === " " && (lastChar === " " || lastChar === "\n" || lastChar === " " || lastChar === "\r")) return;
1703
2426
  if (!ownsCaptionSpace && shouldAddSpacingBeforeText(lastChar, lastNode, textNode)) textNode.value = ` ${textNode.value}`;
2427
+ if (openMarkerCount && textNode.value.charCodeAt(0) === 32 && hoistOpenerSpace()) {
2428
+ let start = 1;
2429
+ while (textNode.value.charCodeAt(start) === 32) start++;
2430
+ textNode.value = textNode.value.slice(start);
2431
+ if (!textNode.value) return;
2432
+ }
1704
2433
  if ((state.depthMap[34] || 0) > 0 && (state.depthMap[25] || 0) > 0) {
1705
2434
  const indent = state.listIndent;
1706
2435
  let value = textNode.value.replace(/\n(?!\n|$)/g, `\n${indent}`);
@@ -1716,11 +2445,28 @@ function createMarkdownProcessor(options = {}, createStream) {
1716
2445
  while (parent && parent !== rawHtmlLink) parent = parent.parent;
1717
2446
  textNode.value = escapeRawHtmlText(textNode.value, state.depthMap, rawHtmlLink !== void 0 && parent === rawHtmlLink);
1718
2447
  }
1719
- if (!state.depthMap[34] && !state.depthMap[23] && (!insideRawHtmlBlock || rawHtmlMarkdown) && mayNeedGfmTextEscape(textNode.value, state.buffer, state.depthMap) && (!insideRawHtmlBlock || !lineOpensRawHtmlBlock(state.buffer, bufferScan))) textNode.value = escapeGfmText(textNode.value, state.buffer, state.depthMap);
1720
- if (textNode.generatedMarkdown && textNode.value) textNode.value = `${textNode.generatedMarkdown.prefix}${textNode.value}${textNode.generatedMarkdown.suffix}`;
2448
+ const last = lastChar.charCodeAt(0);
2449
+ const first = last >= 48 && last <= 57 ? textNode.value.charCodeAt(0) : 0;
2450
+ const orderedDigits = (first >= 48 && first <= 57 || first === 46 || first === 41) && !textNode.generatedMarkdown?.prefix ? lineStartDigits(state, textNode.value) : 0;
2451
+ const outputStart = textNode.generatedMarkdown?.prefix ? -1 : outputStartMarker(textNode.value, state);
2452
+ if (!state.depthMap[34] && !state.depthMap[23] && state.codeText?.kind !== "span" && (!insideRawHtmlBlock || rawHtmlMarkdown) && (orderedDigits > 0 || outputStart !== -1 || mayNeedGfmTextEscape(textNode.value, state.buffer, state.depthMap, state.listIndent.length)) && (!insideRawHtmlBlock || !lineOpensRawHtmlBlock(state.buffer, bufferScan))) textNode.value = escapeGfmText(textNode.value, state.buffer, state.depthMap, state.listIndent.length, orderedDigits, outputStart);
2453
+ if (textNode.generatedMarkdown && textNode.value) {
2454
+ noteGeneratedFences(state, textNode.generatedMarkdown);
2455
+ textNode.value = `${textNode.generatedMarkdown.prefix}${textNode.value}${textNode.generatedMarkdown.suffix}`;
2456
+ }
2457
+ if (pendingCloser && textNode.value) {
2458
+ const code = textNode.value.charCodeAt(0);
2459
+ const written = ownsCaptionSpace ? lastOutputChar(state.buffer) : -1;
2460
+ if ((written === -1 ? lastChar.charCodeAt(0) : written) === pendingCloser && isAsciiAlphanumeric(code)) textNode.value = `&#${code};${textNode.value.slice(1)}`;
2461
+ pendingCloser = 0;
2462
+ }
2463
+ state.cacheFollowsSeparator = state.separatorPending === true;
2464
+ state.separatorPending = false;
2465
+ state.droppedPairAt = void 0;
1721
2466
  const wrapWidth = state.options?.wrapWidth;
1722
- if (wrapWidth && canWrapHere(state.depthMap)) {
1723
- const wrapped = wrapText(textNode.value, currentColumn(state.buffer), wrapWidth, continuationPrefix(textNode, state.listIndentWidths, state.blockquotes.length === 0));
2467
+ if (wrapWidth && state.codeText?.kind !== "span" && canWrapHere(state.depthMap)) {
2468
+ const column = currentColumn(state.buffer, Math.max(wrapWidth, state.listIndent.length + 1));
2469
+ const wrapped = wrapText(textNode.value, column, wrapWidth, state.listIndent);
1724
2470
  state.buffer.push(wrapped);
1725
2471
  state.lastContentCache = wrapped;
1726
2472
  } else {
@@ -1729,19 +2475,135 @@ function createMarkdownProcessor(options = {}, createStream) {
1729
2475
  }
1730
2476
  if (openMarkerCount || openLinkFragment >= 0) {
1731
2477
  const hasVisibleText = textNode.containsWhitespace === false || hasNonWhitespace(textNode.value);
1732
- if (openLinkFragment >= 0 && hasVisibleText) openLinkFragment = -openLinkFragment - 2;
1733
- if (openMarkerCount && hasVisibleText) {
1734
- openMarkerCount = 0;
1735
- commitCaptionFrames();
2478
+ if (openLinkFragment >= 0 && hasVisibleText && hasLabelText(textNode.value)) openLinkFragment = -openLinkFragment - 2;
2479
+ if (openMarkerCount && hasNonWhitespace(textNode.value)) {
2480
+ const first = textNode.value.charCodeAt(0);
2481
+ if (first !== 11 && !isAsciiWhitespace(first) || (openMarkers[openMarkerCount - 1] + 1 & MARKER_TYPE_MASK) > 5 || !isVerticalTabRun(textNode.value)) openMarkerCount = 0;
2482
+ if (openLinkFragment < 0) commitCaptionFrames();
2483
+ } else if (openMarkerCount && textNode.containsWhitespace !== true && textNode.value && (openMarkers[openMarkerCount - 1] + 1 & MARKER_TYPE_MASK) > 5) {
2484
+ if (silentMarkerCount >= openMarkerCount) openMarkerCount = 0;
2485
+ else blankMarkerCount = openMarkerCount;
1736
2486
  }
1737
2487
  }
1738
2488
  }
1739
2489
  state.lastTextNode = textNode;
2490
+ breakAfterLastText = false;
2491
+ }
2492
+ function nextListMarker(list, ordered) {
2493
+ const sibling = siblingListMarker;
2494
+ if (sibling !== 0 && siblingListDepth === state.depthMap[25] && siblingListQuotes === state.blockquotes.length && (sibling === 46 || sibling === 41) === ordered) {
2495
+ if (sibling === 45 && listItemsOpenLines(list)) return 42;
2496
+ if (sibling === 46) return 41;
2497
+ }
2498
+ return ordered ? 46 : 45;
2499
+ }
2500
+ function listItemsOpenLines(list) {
2501
+ if (captionFrameCount !== 0) return false;
2502
+ let ancestor = list;
2503
+ while (ancestor && (!ancestor.tagHandler?.collapsesInnerWhiteSpace || ancestor.tagId === 37)) ancestor = ancestor.parent;
2504
+ if (!ancestor) return true;
2505
+ const last = lastOutputChar(state.buffer);
2506
+ return last === 10 || last === -1;
2507
+ }
2508
+ function reconcileListPath(event) {
2509
+ const node = event.node;
2510
+ const path = eventPath;
2511
+ let ancestor = node.parent;
2512
+ let top = path.at(-1);
2513
+ while (ancestor !== top) if (top && (!ancestor || top.depth >= ancestor.depth)) {
2514
+ path.pop();
2515
+ if (top !== node && top === listMarkerOwners.at(-1)) {
2516
+ listMarkerOwners.pop();
2517
+ const depth = listMarkerDepths.pop();
2518
+ const marker = state.listMarkers.pop();
2519
+ if (marker !== void 0 && marker > 255) {
2520
+ siblingListMarker = marker >> 8;
2521
+ siblingListDepth = depth;
2522
+ siblingListQuotes = state.blockquotes.length;
2523
+ }
2524
+ }
2525
+ top = path.at(-1);
2526
+ } else if (ancestor) {
2527
+ missingAncestors.push(ancestor);
2528
+ ancestor = ancestor.parent;
2529
+ } else break;
2530
+ while (missingAncestors.length) path.push(missingAncestors.pop());
2531
+ if (node.type === 1 && event.type === 0) path.push(node);
2532
+ }
2533
+ function closeListMarker(element, exitOutput) {
2534
+ if (listMarkerOwners) {
2535
+ if (listMarkerOwners.at(-1) !== element) return;
2536
+ listMarkerOwners.pop();
2537
+ listMarkerDepths.pop();
2538
+ }
2539
+ let marker = state.listMarkers.pop();
2540
+ if (exitOutput && marker !== void 0) {
2541
+ const written = exitListMarker(exitOutput, marker > 255);
2542
+ if (written !== void 0) {
2543
+ marker = marker & 255 | written << 8;
2544
+ siblingListMarker = 0;
2545
+ }
2546
+ }
2547
+ if (marker !== void 0 && marker > 255) {
2548
+ siblingListMarker = marker >> 8;
2549
+ siblingListDepth = state.depthMap[25];
2550
+ siblingListQuotes = state.blockquotes.length;
2551
+ listClosedInGap = true;
2552
+ }
2553
+ }
2554
+ function processGapEvent(event) {
2555
+ const fragments = state.buffer.length;
2556
+ inGapEvent = true;
2557
+ listClosedInGap = false;
2558
+ processEvent(event);
2559
+ inGapEvent = false;
2560
+ if (listClosedInGap) return;
2561
+ const buffer = state.buffer;
2562
+ if (openMarkerCount === 0 && openLinkFragment < 0 && gfmLifecycle.openCodeSpans.length === 0) {
2563
+ for (let index = Math.min(fragments, buffer.length); index < buffer.length; index++) if (hasNonWhitespace(buffer[index])) {
2564
+ siblingListMarker = 0;
2565
+ break;
2566
+ }
2567
+ }
2568
+ }
2569
+ function settleHeadingBreakAtEvent(node, eventType) {
2570
+ if (node.type === 2 && eventType === 0) {
2571
+ const textNode = node;
2572
+ if (textNode.excludedFromMarkdown || !hasNonWhitespace(textNode.value)) return true;
2573
+ const separator = `\n\n${state.listIndent}`;
2574
+ state.buffer.push(separator);
2575
+ state.lastContentCache = separator;
2576
+ state.headingBreakPending = false;
2577
+ if (!state.depthMap[34]) {
2578
+ const value = textNode.value;
2579
+ let start = 0;
2580
+ let code = value.charCodeAt(0);
2581
+ while (code === 32 || code === 9 || code === 10 || code === 12 || code === 13) code = value.charCodeAt(++start);
2582
+ if (start !== 0) textNode.value = value.slice(start);
2583
+ }
2584
+ } else if (node.type === 1 && eventType === 1 && node.tagId === 25) state.headingBreakPending = false;
2585
+ return false;
1740
2586
  }
1741
2587
  function processEvent(event) {
2588
+ if (eventPath && !inGapEvent) reconcileListPath(event);
2589
+ if (siblingListMarker !== 0 && !inGapEvent) return processGapEvent(event);
1742
2590
  const { type: eventType, node } = event;
1743
2591
  state.depth = node.depth;
2592
+ if (blankCaptionFrames !== 0) settleBlankCaption();
1744
2593
  if (node.type === 1 ? node.excludedFromMarkdown : node.parent?.excludedFromMarkdown) return;
2594
+ const codeCaption = state.codeText !== void 0 && node.type === 1 && node.tagId === 106;
2595
+ if (codeCaption) {
2596
+ const element = node;
2597
+ const literalOutput = eventType === 0 ? element.tagHandler?.literalEnter : element.tagHandler?.literalExit;
2598
+ if (!element.pluginOutput?.length && !literalOutput) return;
2599
+ }
2600
+ if (closedMarkerCount) heldClosedMarker();
2601
+ if (pendingRawHtmlBoundary && eventType === 0 && node.type === 1 && node.tagId === 34 && !node.tagHandler?.literalEnter) pendingRawHtmlBoundary = false;
2602
+ const blank = node.type === 2 && node.leadingBlank ? node.value : void 0;
2603
+ if (blank !== void 0 && !hasNonWhitespace(blank)) {
2604
+ if (blank && !node.excludedFromMarkdown && !state.pendingInlineWhitespace && !captionNeedsPreparation()) placeLeadingBlank();
2605
+ return;
2606
+ }
1745
2607
  if (state.tableRowOpenerPending && state.depthMap[28] <= 1) {
1746
2608
  const tagId = node.type === 1 ? node.tagId : void 0;
1747
2609
  const cellEvent = tagId === 32 || tagId === 31;
@@ -1754,19 +2616,21 @@ function createMarkdownProcessor(options = {}, createStream) {
1754
2616
  }
1755
2617
  }
1756
2618
  if (state.listRulePending !== void 0) {
1757
- const isVisibleText = node.type === 2 && eventType === 0 && hasNonWhitespace(node.value);
2619
+ const isVisibleText = node.type === 2 && eventType === 0 && !node.excludedFromMarkdown && hasNonWhitespace(node.value);
1758
2620
  const opensVisibleElement = node.type === 1 && eventType === 0 && !node.tagHandler?.excludesTextNodes;
1759
2621
  if (isVisibleText || opensVisibleElement) {
1760
- const separator = blockOpenPrefix(state.buffer, state.listRulePending);
2622
+ const separator = `\n\n${state.listRulePending}`;
1761
2623
  state.buffer.push(separator);
1762
2624
  state.lastContentCache = separator;
1763
2625
  state.listRulePending = void 0;
1764
2626
  } else if (node.type === 1 && eventType === 1 && node.tagId === 25) state.listRulePending = void 0;
1765
2627
  else if (node.type === 2) return;
1766
2628
  }
2629
+ if (state.headingBreakPending && settleHeadingBreakAtEvent(node, eventType)) return;
1767
2630
  const lastNode = state.lastNode;
1768
2631
  state.lastNode = event.node;
1769
2632
  const buff = state.buffer;
2633
+ const closerBefore = pendingCloser;
1770
2634
  if (state.preFencePending) {
1771
2635
  const preparePendingPreFence = () => {
1772
2636
  if (captionNeedsPreparation()) {
@@ -1779,10 +2643,14 @@ function createMarkdownProcessor(options = {}, createStream) {
1779
2643
  const pendingElement = node;
1780
2644
  const pendingHandler = pendingElement.tagHandler;
1781
2645
  const literalOverride = eventType === 0 ? pendingHandler?.literalEnter : pendingHandler?.literalExit;
1782
- if (literalOverride && codeOwnsPendingPreFence(state, pendingElement)) state.preFenceLang = getLanguageFromClass(pendingElement.attributes?.class);
2646
+ if (literalOverride && codeOwnsPendingPreFence(state, pendingElement)) {
2647
+ const language = getLanguageFromAttributes(pendingElement.attributes);
2648
+ if (language) state.preFenceLang = language;
2649
+ }
1783
2650
  if (pendingElement.pluginOutput?.length || literalOverride) {
1784
2651
  preparePendingPreFence();
1785
2652
  flushPreFence(state);
2653
+ notePluginFences(state, pendingElement.pluginOutput);
1786
2654
  } else if (consumePendingPreChild(state, node, eventType, preparePendingPreFence)) return;
1787
2655
  } else if (consumePendingPreChild(state, node, eventType, preparePendingPreFence)) return;
1788
2656
  }
@@ -1800,13 +2668,33 @@ function createMarkdownProcessor(options = {}, createStream) {
1800
2668
  const element = node;
1801
2669
  const handler = node.tagHandler;
1802
2670
  const tagId = element.tagId;
2671
+ if (eventType === 1 && state.codeText?.owner === element) state.codeText = void 0;
2672
+ if ((tagId === 24 || tagId === 33) && eventType === 0) {
2673
+ state.listMarkers.push(nextListMarker(element, tagId === 33));
2674
+ listMarkerOwners?.push(element);
2675
+ listMarkerDepths?.push(state.depthMap[25]);
2676
+ }
2677
+ if (eventType === 1) while (literalOpeners.length && literalOpeners[literalOpeners.length - 2] >= element.depth) literalOpeners.length -= 2;
1803
2678
  const insideRawHtmlRegion = isInsideRawHtmlBlock(state.depthMap);
1804
- if (eventType === 0 && state.depthMap[25] && !insideRawHtmlRegion && (tagId === 35 || tagId === 36 || tagId === 34 || tagId === 28) && !handler?.literalEnter && endsAtHardBreak(buff)) {
2679
+ if (captionBoundary === 3 && tagId === 22 && eventType === 0 && onItemMarkerLine(state)) captionBoundary = 0;
2680
+ let emptyQuoteItemExit = false;
2681
+ if (captionBoundary >= 3 && tagId === 25) {
2682
+ restoreQuoteParentBoundary();
2683
+ if (eventType === 1 && onItemMarkerLine(state)) {
2684
+ buff.push("\n");
2685
+ state.lastContentCache = "\n";
2686
+ lastChar = "\n";
2687
+ emptyQuoteItemExit = true;
2688
+ }
2689
+ captionBoundary = 0;
2690
+ }
2691
+ if (eventType === 0 && state.depthMap[25] && !insideRawHtmlRegion && (tagId === 35 || tagId === 36 || tagId === 34 || tagId === 28 || tagId === 13 && !state.listIndent) && !handler?.literalEnter && endsAtHardBreak(buff)) {
1805
2692
  trimTrailingSpaces(buff);
1806
2693
  const separator = tagId === 35 || tagId === 36 ? `\n${state.listIndent}` : "\n";
1807
2694
  buff.push(separator);
1808
2695
  state.lastContentCache = separator;
1809
2696
  state.lastTextNode = void 0;
2697
+ state.headingBreakPending = false;
1810
2698
  lastBuffEntry = separator;
1811
2699
  lastChar = separator.charAt(separator.length - 1);
1812
2700
  }
@@ -1817,8 +2705,9 @@ function createMarkdownProcessor(options = {}, createStream) {
1817
2705
  }
1818
2706
  if (eventType === 0 && handler === breakHandler && !element.pluginOutput?.length) {
1819
2707
  const inPre = state.depthMap[34] !== 0;
1820
- let breakOutput = renderBreak(element, state);
2708
+ let breakOutput = renderBreak(state);
1821
2709
  if (captionBoundary !== 0 || captionFrameCount !== 0) {
2710
+ if (captionBoundary === 5) captionBoundary = 4;
1822
2711
  const pendingCaption = captionFrameCount !== 0 && (captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 2] & CAPTION_OPEN) === 0;
1823
2712
  if (!inPre && breakOutput && !hasNonWhitespace(breakOutput) && buff.length === 0 && !hasYieldedContent && state.blockquotes.length === 0 && pendingCaption) breakOutput = void 0;
1824
2713
  if (breakOutput && hasNonWhitespace(breakOutput) && captionNeedsPreparation()) {
@@ -1830,7 +2719,26 @@ function createMarkdownProcessor(options = {}, createStream) {
1830
2719
  lastChar = lastBuffEntry?.charAt(lastBuffEntry.length - 1) || "";
1831
2720
  }
1832
2721
  }
1833
- if (state.pendingInlineWhitespace) state.pendingInlineWhitespace = false;
2722
+ if (pendingRawHtmlBoundary && breakOutput) finishRawHtmlBlock(breakOutput, true);
2723
+ const captionHasAnchor = captionFrameCount !== 0 && (captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 2] & CAPTION_OPEN) === 0 && captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 3] !== CAPTION_NO_ANCHOR;
2724
+ if (state.pendingInlineWhitespace && !captionHasAnchor) {
2725
+ state.pendingInlineWhitespace = false;
2726
+ if (breakOutput?.charCodeAt(0) === 60) {
2727
+ const last = lastOutputChar(buff);
2728
+ if (last !== -1 && last !== 32 && last !== 10 && last !== 9 && last !== 13) {
2729
+ buff.push(" ");
2730
+ state.lastContentCache = " ";
2731
+ state.separatorPending = true;
2732
+ }
2733
+ }
2734
+ }
2735
+ if (state.headingBreakPending && breakOutput) {
2736
+ if (breakOutput.includes("\n")) state.headingBreakPending = false;
2737
+ else if (hasNonWhitespace(breakOutput)) {
2738
+ state.headingBreakPending = false;
2739
+ breakOutput = `\n\n${state.listIndent}${breakOutput}`;
2740
+ }
2741
+ }
1834
2742
  const lastFragment = state.lastContentCache;
1835
2743
  const lastTextNode = state.lastTextNode;
1836
2744
  if (lastFragment && lastTextNode?.containsWhitespace && typeof lastTextNode.value === "string") {
@@ -1844,7 +2752,7 @@ function createMarkdownProcessor(options = {}, createStream) {
1844
2752
  parent = parent.parent;
1845
2753
  }
1846
2754
  if (!parentInPre || element.parent?.tagId === 34) {
1847
- if (breakOutput?.endsWith("\n") && !parentInPre) {
2755
+ if (breakOutput?.endsWith("\n") && !parentInPre && !breakAfterLastText) {
1848
2756
  const trimmed = trimAsciiWhitespaceEnd(lastFragment);
1849
2757
  if (trimmed.length !== lastFragment.length && buff.at(-1) === lastFragment) {
1850
2758
  state.outputPositions?.replace(buff.length - 1, buff.length, [trimmed]);
@@ -1854,14 +2762,16 @@ function createMarkdownProcessor(options = {}, createStream) {
1854
2762
  state.lastTextNode = void 0;
1855
2763
  }
1856
2764
  }
2765
+ if (!inPre && breakOutput?.endsWith("\n") && lastOutputChar(buff) === 32) trimTrailingSpaces(buff);
1857
2766
  const pendingCaption = captionFrameCount !== 0 && (captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 2] & CAPTION_OPEN) === 0;
1858
- if (breakOutput && pendingCaption && !hasNonWhitespace(breakOutput)) {
2767
+ if (breakOutput && breakOutput !== " " && pendingCaption && !hasNonWhitespace(breakOutput)) {
1859
2768
  for (let index = 0; index < captionFrameCount; index++) {
1860
2769
  const offset = index * CAPTION_FRAME_SIZE + 2;
1861
2770
  if ((captionFrames[offset] & CAPTION_OPEN) === 0) captionFrames[offset] = captionFrames[offset] | CAPTION_INTERNAL_BREAK;
1862
2771
  }
1863
2772
  captionBreakRun++;
1864
2773
  } else if (breakOutput) {
2774
+ if (breakOutput.charCodeAt(0) === 60 && lastOutputChar(buff) === 124) buff.push(" ");
1865
2775
  buff.push(breakOutput);
1866
2776
  state.lastContentCache = breakOutput;
1867
2777
  if (openMarkerCount && hasNonWhitespace(breakOutput)) openMarkerCount = 0;
@@ -1869,23 +2779,34 @@ function createMarkdownProcessor(options = {}, createStream) {
1869
2779
  return;
1870
2780
  }
1871
2781
  let output;
1872
- const hasPluginOutput = !!element.pluginOutput?.length;
1873
- if (hasPluginOutput) {
1874
- output = element.pluginOutput;
2782
+ const pluginOutput = element.pluginOutput;
2783
+ const hasPluginOutput = !!pluginOutput?.length;
2784
+ if (pluginOutput?.length) {
2785
+ notePluginFences(state, pluginOutput);
2786
+ output = pluginOutput;
1875
2787
  element.pluginOutput = void 0;
1876
2788
  }
1877
2789
  let captionBufferChanged = false;
1878
2790
  const eventFn = eventType === 0 ? "enter" : "exit";
1879
2791
  const isInlineElement = handler ? handler.isInline === true : tagId === -1;
2792
+ let closesQuote = false;
2793
+ let closesQuoteWrapper = false;
2794
+ let keepsQuoteSeparator = false;
1880
2795
  let gfmAction;
1881
2796
  let handlerOutput;
1882
- const suppressedInPre = (state.depthMap[34] || 0) > 0 && suppressesFormattingInPre(tagId) && !(eventType === 0 ? handler?.literalEnter : handler?.literalExit);
2797
+ const suppressedInPre = !!state.depthMap[34] && suppressesFormattingInPre(tagId) && !(eventType === 0 ? handler?.literalEnter : handler?.literalExit);
1883
2798
  const emptyTableRow = eventType === 1 && tagId === 30 && state.tableRowOpenerPending && !output && !handler?.literalExit;
1884
2799
  if (eventType === 1 && (handler?.literalExit || output) && gfmLifecycle.openCodeSpans.at(-1)?.owner === element) gfmLifecycle.openCodeSpans.pop();
1885
2800
  if (cleanPass && eventType === 1) cleanPass.exit(element);
1886
- if (!output && !suppressedInPre && handler?.[eventFn]) {
2801
+ if (!output && !suppressedInPre && handler?.[eventFn] && (tagId !== 36 || state.depthMap[25] || handler[eventFn] !== tagHandlers[36].enter)) {
1887
2802
  if (openLinkFragment >= 0 && eventType === 1 && tagId === 26) {
1888
- if (dropEmptyLinkText(buff, openLinkFragment, state.outputPositions)) {
2803
+ if (dropBlankLink(buff, openLinkFragment, state.outputPositions)) {
2804
+ noteBufferRewrite(state);
2805
+ if (openLinkHeadingBreak) {
2806
+ state.outputPositions?.replace(openLinkFragment - 1, openLinkFragment, []);
2807
+ buff.length--;
2808
+ state.headingBreakPending = true;
2809
+ }
1889
2810
  if (captionFrameCount !== 0) {
1890
2811
  captionBreakRun = openLinkCaptionBreakRun;
1891
2812
  restoreCaptionBreakFlags(captionFrames, openLinkCaptionFlags, captionFrameCount);
@@ -1894,13 +2815,38 @@ function createMarkdownProcessor(options = {}, createStream) {
1894
2815
  state.lastContentCache = buff.at(-1);
1895
2816
  state.lastTextNode = void 0;
1896
2817
  openLinkFragment = -1;
2818
+ restoreQuoteParentBoundary();
1897
2819
  return;
1898
2820
  }
1899
2821
  }
1900
2822
  if (cleanPass && eventType === 1 && tagId === 26 && cleanPass.unwrap(element)) {
2823
+ noteBufferRewrite(state);
1901
2824
  openLinkFragment = -1;
1902
2825
  return;
1903
2826
  }
2827
+ if (eventType === 1 && tagId === 26 && openLinkFragment !== -1 && !handler.literalExit && !insideRawHtmlRegion && !gfmLifecycle.openCodeSpans.length && lastChar === " ") {
2828
+ const bracket = openLinkFragment < -1 ? -openLinkFragment - 2 : openLinkFragment;
2829
+ let removed = 0;
2830
+ for (let index = buff.length - 1; index > bracket; index--) {
2831
+ const fragment = buff[index];
2832
+ let end = fragment.length;
2833
+ while (end > 0 && fragment.charCodeAt(end - 1) === 32) end--;
2834
+ removed += fragment.length - end;
2835
+ if (end === 0) continue;
2836
+ if (removed && !isAsciiWhitespace(fragment.charCodeAt(end - 1))) {
2837
+ trimTrailingSpaces(buff);
2838
+ const cache = state.lastContentCache;
2839
+ if (cache) state.lastContentCache = cache.slice(0, Math.max(0, cache.length - removed));
2840
+ state.pendingInlineWhitespace = true;
2841
+ state.pendingLeadingBlank = false;
2842
+ state.pendingPairSeparator = false;
2843
+ state.pendingDecodedBlank = false;
2844
+ lastBuffEntry = buff.at(-1);
2845
+ lastChar = String.fromCharCode(lastOutputChar(buff));
2846
+ }
2847
+ break;
2848
+ }
2849
+ }
1904
2850
  const res = handler[eventFn]({
1905
2851
  node: element,
1906
2852
  state
@@ -1915,10 +2861,15 @@ function createMarkdownProcessor(options = {}, createStream) {
1915
2861
  if (res._tag === "CodeSpanEnter" && span || res._tag === "CodeSpanExit" && span && span.owner !== element) handlerOutput = void 0;
1916
2862
  else {
1917
2863
  gfmAction = res;
1918
- handlerOutput = consumeGfmAction(res, state, gfmLifecycle);
2864
+ if (res._tag === "BlockquoteExit") closesQuote = state.blockquotes.length > 0;
2865
+ if (res._tag === "CodeSpanEnter" && res.output === " `" && (captionBoundary === 3 || captionFrameCount !== 0 && (captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 2] & CAPTION_OPEN) === 0)) gfmAction = CODE_SPAN_ENTER;
2866
+ handlerOutput = consumeGfmAction(gfmAction, state, gfmLifecycle);
1919
2867
  }
1920
2868
  if (handlerOutput) output = [handlerOutput];
1921
- if (res._tag === "BlockquoteExit") captionBufferChanged = true;
2869
+ if (res._tag === "BlockquoteExit") {
2870
+ captionBufferChanged = true;
2871
+ if (gfmLifecycle.quoteWritten || siblingListQuotes > state.blockquotes.length) siblingListMarker = 0;
2872
+ }
1922
2873
  }
1923
2874
  }
1924
2875
  if (eventType === 0 && (tagId === 32 || tagId === 31) && state.tableRowOpenerPending && state.depthMap[28] <= 1) {
@@ -1928,20 +2879,29 @@ function createMarkdownProcessor(options = {}, createStream) {
1928
2879
  else output = [opener];
1929
2880
  }
1930
2881
  if (emptyTableRow) return;
1931
- if (eventType === 0 && output && handler?.collapsesInnerWhiteSpace && (hasPluginOutput || handler !== tagHandlers[tagId] || !INLINE_MARKER_TYPE[tagId] && tagId !== 26)) element.hasEnterOutput = output.some((fragment) => fragment.length > 0);
1932
- if (captionBreakRun && !(tagId === 106 && eventType === 1) && output) {
2882
+ if (eventType === 0 && output && handler?.collapsesInnerWhiteSpace && (hasPluginOutput || handler.literalEnter)) element.hasEnterOutput = output.some((fragment) => fragment.length > 0);
2883
+ const captionEvent = tagId === 106 && !codeCaption;
2884
+ if (captionBreakRun && !(captionEvent && eventType === 1) && output) {
1933
2885
  flushCaptionBreakRun();
1934
2886
  if (gfmAction?._tag !== "BlockquoteEnter") anchorPendingCaptions(state.buffer.length);
1935
2887
  captionBufferChanged = true;
1936
2888
  }
1937
- const captionEvent = tagId === 106;
1938
2889
  let captionTransition = false;
1939
2890
  if (captionEvent || captionBoundary !== 0 || captionFrameCount !== 0) {
2891
+ if (captionBoundary === 3 && eventType === 0 && output?.[0]?.startsWith("\n\n")) captionBoundary = 2;
2892
+ if (captionBoundary >= 4 && eventType === 0 && !isInlineElement && !openMarkerCount) captionBoundary = 0;
2893
+ const holdsQuoteBoundary = captionBoundary === 3 && tagId === 26 && eventType === 1 && handlerOutput !== void 0 && !handler?.literalExit && !insideRawHtmlRegion;
2894
+ if (holdsQuoteBoundary) captionBoundary = 0;
1940
2895
  const captionEnter = captionEvent && eventType === 0 && !state.depthMap[34];
1941
2896
  const captionExit = captionEvent && eventType === 1 && !state.depthMap[34];
1942
2897
  if (captionEnter) pushCaptionFrame(element, handler);
1943
2898
  let dropBlockquoteOutput = false;
1944
- if (captionBoundary === 1 && eventType === 0 && tagId === 22) {
2899
+ if ((captionBoundary === 1 || captionBoundary === 3) && eventType === 0 && gfmAction?._tag === "BlockquoteEnter") {
2900
+ if (captionBoundary === 3) {
2901
+ let last = lastOutputChar(state.buffer);
2902
+ if (last === -1 && state.lastContentCache) last = state.lastContentCache.charCodeAt(state.lastContentCache.length - 1);
2903
+ keepsQuoteSeparator = last !== -1 && last !== 10;
2904
+ }
1945
2905
  captionBufferChanged = appendCaptionSpacing(captionBoundarySpacing, false) || captionBufferChanged;
1946
2906
  captionTransition = true;
1947
2907
  captionBoundary = 0;
@@ -1949,19 +2909,26 @@ function createMarkdownProcessor(options = {}, createStream) {
1949
2909
  output = void 0;
1950
2910
  handlerOutput = void 0;
1951
2911
  }
2912
+ const literalOutput = eventType === 0 ? handler?.literalEnter : handler?.literalExit;
1952
2913
  let meaningfulOutput = !dropBlockquoteOutput && output?.some(hasNonWhitespace) === true;
2914
+ closesQuoteWrapper = meaningfulOutput && eventType === 1 && isInlineElement && !captionExit && captionBoundary >= 3 && tagId !== 26 && !handler?.literalExit;
2915
+ if (captionBoundary === 5 && meaningfulOutput && eventType === 0) {
2916
+ captionBoundary = 4;
2917
+ quoteTentativeSpacing = void 0;
2918
+ }
1953
2919
  if (meaningfulOutput && handlerOutput !== void 0) {
1954
- const markerType = INLINE_MARKER_TYPE[tagId];
1955
- const literal = eventType === 0 ? handler?.literalEnter : handler?.literalExit;
1956
- if ((markerType || tagId === 26 && eventType === 0) && !literal) {
1957
- if (captionBoundary === 1) {
1958
- captionBufferChanged = appendCaptionSpacing(captionBoundarySpacing, true) || captionBufferChanged;
2920
+ if ((INLINE_MARKER_TYPE[tagId] || tagId === 26 && eventType === 0) && !literalOutput) {
2921
+ if (captionBoundary === 1 || captionBoundary === 3) {
2922
+ const quoteBoundary = captionBoundary === 3;
2923
+ const appended = appendCaptionSpacing(captionBoundarySpacing, true);
2924
+ captionBufferChanged = appended || captionBufferChanged;
1959
2925
  captionTransition = true;
1960
- captionBoundary = 2;
2926
+ captionBoundary = quoteBoundary ? 4 : 2;
2927
+ if (quoteBoundary) quoteTentativeSpacing = appended ? state.buffer.at(-1) : void 0;
1961
2928
  }
1962
2929
  if (eventType === 0) {
2930
+ if (captionFrameCount !== 0 && (captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 2] & CAPTION_OPEN) === 0) captionTransition = true;
1963
2931
  anchorPendingCaptions(state.buffer.length);
1964
- captionTransition = true;
1965
2932
  }
1966
2933
  meaningfulOutput = false;
1967
2934
  }
@@ -1971,6 +2938,7 @@ function createMarkdownProcessor(options = {}, createStream) {
1971
2938
  if (captionExit && captionFrameCount !== 0) {
1972
2939
  const offset = (captionFrameCount - 1) * CAPTION_FRAME_SIZE;
1973
2940
  const opened = (captionFrames[offset + 2] & CAPTION_OPEN) !== 0;
2941
+ const restoresHeadingBreak = !opened && defaultCaptionExit && (captionFrames[offset + 2] & CAPTION_HEADING_BREAK) !== 0;
1974
2942
  if (!opened && defaultCaptionExit) {
1975
2943
  output = void 0;
1976
2944
  handlerOutput = void 0;
@@ -1978,16 +2946,18 @@ function createMarkdownProcessor(options = {}, createStream) {
1978
2946
  if (flushCaptionBreakRun()) captionBufferChanged = true;
1979
2947
  captionBufferChanged = prepareCaptionOutput(false) || captionBufferChanged;
1980
2948
  captionTransition = true;
1981
- consumeCaptionTransition(isInlineElement, tagId);
2949
+ consumeCaptionTransition(isInlineElement && !literalOutput, tagId);
1982
2950
  }
1983
2951
  finishCaptionFrame();
1984
2952
  if (!opened && flushCaptionBreakRun()) captionBufferChanged = true;
2953
+ if (restoresHeadingBreak && buff.length > 0 && !captionExitOpensBlockLine(buff)) state.headingBreakPending = true;
1985
2954
  } else if (meaningfulOutput && captionNeedsPreparation()) {
1986
2955
  captionBufferChanged = prepareCaptionOutput(captionEnter, tagId !== 25) || captionBufferChanged;
1987
2956
  captionTransition = true;
1988
- consumeCaptionTransition(isInlineElement, tagId);
2957
+ consumeCaptionTransition(isInlineElement && !literalOutput, tagId);
1989
2958
  }
1990
2959
  if (meaningfulOutput) commitCaptionFrames();
2960
+ if (holdsQuoteBoundary) captionBoundary = 3;
1991
2961
  }
1992
2962
  if (eventType === 1 && tagId === 25 && !state.depthMap[34] && !isInsideTableCell(state) && !handler?.literalExit && endsAtHardBreak(buff)) {
1993
2963
  trimTrailingSpaces(buff);
@@ -2015,19 +2985,124 @@ function createMarkdownProcessor(options = {}, createStream) {
2015
2985
  if (eventType === 1 && openMarkerCount) {
2016
2986
  const markerType = handlerOutput === void 0 ? 0 : INLINE_MARKER_TYPE[tagId];
2017
2987
  if (markerType && (tagId !== 23 || !state.depthMap[34] && !isInsideRawHtmlBlock(state.depthMap)) && !handler?.literalExit) {
2018
- const idx = dropEmptyMarker(buff, openMarkers[--openMarkerCount], markerType, state.outputPositions);
2019
- if (idx >= 0) {
2020
- resetRetractedCaptionFrames(captionFrames, captionFrameCount, idx);
2021
- state.lastContentCache = idx > 0 ? buff[idx - 1] : void 0;
2022
- return;
2988
+ const slot = --openMarkerCount;
2989
+ const packed = openMarkers[slot];
2990
+ if ((packed & MARKER_TYPE_MASK) === MARKER_TYPE_MASK) {
2991
+ const start = packed >> 3;
2992
+ let index = start;
2993
+ while (index < buff.length && !hasNonWhitespace(buff[index])) index++;
2994
+ if (index === buff.length && (markerType === 1 || markerType === 2 || markerType === 4)) {
2995
+ const owesSeparator = openMarkerFollowsSpace[slot] && buff[start - 1] === " ";
2996
+ const at = owesSeparator ? start - 1 : start;
2997
+ state.outputPositions?.replace(at, buff.length, [handlerOutput]);
2998
+ buff.length = at;
2999
+ buff.push(handlerOutput);
3000
+ noteBufferRewrite(state);
3001
+ state.lastContentCache = handlerOutput;
3002
+ pendingCloser = openMarkerClosers[slot];
3003
+ if (closedMarkerCount && closedMarkers[closedMarkerCount - 1] !== at - 1) closedMarkerCount = 0;
3004
+ closedMarkers[closedMarkerCount++] = at;
3005
+ if (owesSeparator) {
3006
+ state.pendingInlineWhitespace = true;
3007
+ state.pendingLeadingBlank = true;
3008
+ state.pendingPairSeparator = openMarkerSeparatorTrimmed[slot];
3009
+ state.pendingDecodedBlank = false;
3010
+ }
3011
+ return;
3012
+ }
3013
+ } else {
3014
+ const hoisted = markerType <= 4 && buff[packed >> 3]?.charCodeAt(0) === 32;
3015
+ const owned = markerType > 4 && openMarkerFollowsSpace[slot] && buff[packed >> 3]?.charCodeAt(0) === 32;
3016
+ const restoresHeadingBreak = buff[packed >> 3]?.includes("\n");
3017
+ let idx = dropEmptyMarker(buff, packed, markerType, state.outputPositions);
3018
+ if (idx >= 0) {
3019
+ pendingCloser = openMarkerClosers[slot];
3020
+ noteBufferRewrite(state);
3021
+ if (hoisted) {
3022
+ state.pendingInlineWhitespace = true;
3023
+ state.pendingLeadingBlank = true;
3024
+ state.pendingPairSeparator = false;
3025
+ state.pendingDecodedBlank = false;
3026
+ }
3027
+ if (openMarkerFollowsSpace[slot] && (owned || buff[idx - 1] === " ")) {
3028
+ if (!owned) {
3029
+ idx--;
3030
+ state.outputPositions?.replace(idx, buff.length, []);
3031
+ buff.length = idx;
3032
+ }
3033
+ state.pendingInlineWhitespace = true;
3034
+ state.pendingLeadingBlank = true;
3035
+ state.pendingPairSeparator = openMarkerSeparatorTrimmed[slot];
3036
+ state.pendingDecodedBlank = false;
3037
+ }
3038
+ if (restoresHeadingBreak) state.headingBreakPending = true;
3039
+ resetRetractedCaptionFrames(captionFrames, captionFrameCount, idx);
3040
+ state.lastContentCache = idx > 0 ? buff[idx - 1] : void 0;
3041
+ state.droppedPairAt = buff.length;
3042
+ restoreQuoteParentBoundary();
3043
+ if (unmergedSlot === openMarkerCount - 1 && unmergedOpener === buff.length - 1 && openMarkers[unmergedSlot] >> 3 === unmergedOpener && closedMarkerCount && closedMarkers[closedMarkerCount - 1] === unmergedOpener - 1 && buff[unmergedOpener] === buff[unmergedOpener - 1]) {
3044
+ closedMarkerCount--;
3045
+ state.outputPositions?.replace(unmergedOpener - 1, buff.length, []);
3046
+ buff.length = unmergedOpener - 1;
3047
+ noteBufferRewrite(state);
3048
+ state.lastContentCache = buff[buff.length - 1];
3049
+ openMarkers[unmergedSlot] = buff.length << 3 | MARKER_TYPE_MASK;
3050
+ unmergedSlot = -1;
3051
+ }
3052
+ return;
3053
+ }
3054
+ if (markerType <= 4 && dropVerticalTabMarker(buff, packed, markerType, handlerOutput, state.outputPositions)) {
3055
+ noteBufferRewrite(state);
3056
+ state.lastContentCache = buff[buff.length - 1];
3057
+ return;
3058
+ }
2023
3059
  }
2024
3060
  openMarkerCount = 0;
2025
3061
  }
2026
3062
  }
3063
+ if (closesQuoteWrapper) {
3064
+ captionBoundary = 5;
3065
+ quoteTentativeSpacing = void 0;
3066
+ const block = traverseUpToFirstBlockNode(element.parent).at(-1);
3067
+ block.childTextNodeIndex = (block.childTextNodeIndex || 0) + 1;
3068
+ }
2027
3069
  if (tagId === 6 && !state.depthMap[34] && output?.length === 1 && output[0] === "\n" && lastChar === "\n" && secondLastChar === "\n") output = void 0;
3070
+ const rawBlockTag = tagId === 100 || tagId === 101 || tagId === 99 || tagId === 98 || tagId === 2 || tagId === 3;
3071
+ if (rawBlockTag && rawHtmlNeedsBoundary && trackRawHtmlMarkdownContext(buff, bufferScan)) rawHtmlNeedsBoundary = false;
3072
+ if (rawBlockTag && !isInsideTableCell(state) && !state.depthMap[34] && !(eventType === 0 ? handler?.literalEnter : handler?.literalExit) && handlerOutput && (pendingRawHtmlBoundary || blockOpenPrefix(state, void 0) === void 0)) {
3073
+ rawHtmlNeedsBoundary = true;
3074
+ bufferScan[0] = false;
3075
+ bufferScan[1] = buff.length;
3076
+ }
3077
+ const endsRawHtmlBlock = rawBlockTag && eventType === 1 && !insideRawHtmlRegion;
3078
+ if (endsRawHtmlBlock) {
3079
+ pendingRawHtmlBoundary = rawHtmlNeedsBoundary && !handler?.literalExit;
3080
+ rawHtmlNeedsBoundary = false;
3081
+ } else if (rawBlockTag && eventType === 0) pendingRawHtmlBoundary = false;
3082
+ if (eventType === 1 && (tagId === 25 || tagId === 22)) pendingRawHtmlBoundary = false;
3083
+ const voidSpacingAtEnter = isOpenVoidTag(handler, tagId) && !handler?.literalExitHasOutput && !(eventType === 1 && pluginOutput?.some(hasNonWhitespace));
3084
+ let openVoidLines = 0;
3085
+ if (eventType === 0 && voidSpacingAtEnter) {
3086
+ const exitLines = suppressedInPre ? 0 : calculateNewLineConfig(element, state, 1)[1];
3087
+ let enterNewlines = 0;
3088
+ let visible = false;
3089
+ for (let i = (output?.length || 0) - 1; i >= 0 && !visible; i--) {
3090
+ const fragment = output[i];
3091
+ let end = fragment.length;
3092
+ while (end > 0 && fragment.charCodeAt(end - 1) === 10) {
3093
+ end--;
3094
+ enterNewlines++;
3095
+ }
3096
+ visible = end > 0;
3097
+ }
3098
+ const cappedLines = tagId === 13 && state.blockquotes.length > 0 ? Math.min(1, exitLines) : exitLines;
3099
+ const owedLines = Math.max(0, cappedLines - enterNewlines);
3100
+ if (!visible) openVoidLines = owedLines;
3101
+ else if (owedLines > 0) output = [...output, "\n".repeat(owedLines)];
3102
+ }
2028
3103
  const newLineConfig = suppressedInPre ? NO_SPACING : calculateNewLineConfig(node, state, eventType);
2029
3104
  const quoteAtStart = eventType === 0 && state.blockquotes.at(-1)?.fragment === state.buffer.length;
2030
- const configuredNewLines = quoteAtStart || captionEvent || captionTransition ? 0 : eventType === 1 && tagId === 13 && state.blockquotes.length > 0 ? Math.min(1, newLineConfig[eventType] || 0) : newLineConfig[eventType] || 0;
3105
+ const configuredNewLines = quoteAtStart || captionEvent || captionTransition || eventType === 1 && voidSpacingAtEnter ? 0 : eventType === 1 && tagId === 13 && state.blockquotes.length > 0 ? Math.min(1, newLineConfig[eventType] || 0) : openVoidLines ? Math.max(newLineConfig[eventType] || 0, openVoidLines) : newLineConfig[eventType] || 0;
2031
3106
  let measureFromOutputTail = false;
2032
3107
  if (eventType === 1 && gfmAction?._tag === "PreExit" && output) for (let i = output.length - 1; i >= 0; i--) {
2033
3108
  const frag = output[i];
@@ -2038,21 +3113,37 @@ function createMarkdownProcessor(options = {}, createStream) {
2038
3113
  }
2039
3114
  let newLines = Math.max(0, configuredNewLines - (measureFromOutputTail ? 0 : lastNewLines));
2040
3115
  if (newLines > 0 && buff.length === 0 && !hasYieldedContent) newLines = 0;
2041
- if (state.pendingInlineWhitespace) {
3116
+ pendingSpaceFragment = -1;
3117
+ pendingSpaceOwned = false;
3118
+ if (state.pendingInlineWhitespace && !(captionFrameCount !== 0 && (captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 2] & CAPTION_OPEN) === 0 && (captionTransition || captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 3] !== CAPTION_NO_ANCHOR || !output && newLines === 0 && (eventType === 1 || tagId === 49 || tagId === 52 || tagId === 53)))) {
2042
3119
  const firstOutput = output?.[0]?.[0] || "";
3120
+ const opensQuote = eventType === 0 && tagId === 22;
3121
+ const pairOwed = !!state.pendingPairSeparator && !opensQuote;
3122
+ const owed = pairOwed || !!state.pendingDecodedBlank && !opensQuote;
2043
3123
  if (eventType === 0) {
2044
- if (!isInlineElement || tagId === 6 || newLines > 0 || firstOutput === "\n" || firstOutput === "\r") state.pendingInlineWhitespace = false;
3124
+ if (!isInlineElement && (tagId !== 36 || firstOutput) && !owed || newLines > 0 || firstOutput === "\n" || firstOutput === "\r") state.pendingInlineWhitespace = false;
2045
3125
  else if (firstOutput) {
2046
- if (lastChar && !" \n \r".includes(lastChar) && !" \n \r".includes(firstOutput)) {
2047
- state.buffer.push(" ");
2048
- state.lastContentCache = " ";
2049
- lastChar = " ";
3126
+ if (lastChar && !" \n \r".includes(lastChar) && !" \n \r".includes(firstOutput) && !(literalOpeners.length && followsLiteralOpener(state.buffer.length))) {
3127
+ if (openMarkerCount && hoistOpenerSpace()) {
3128
+ if ((openMarkers[openMarkerCount - 1] & MARKER_TYPE_MASK) === MARKER_TYPE_MASK) lastChar = " ";
3129
+ } else {
3130
+ pendingCloser = 0;
3131
+ state.buffer.push(" ");
3132
+ state.lastContentCache = " ";
3133
+ lastChar = " ";
3134
+ pendingSpaceFragment = state.buffer.length - 1;
3135
+ pendingSpaceTrimmed = !state.pendingLeadingBlank || pairOwed;
3136
+ }
3137
+ } else if (firstOutput === " ") {
3138
+ pendingSpaceOwned = true;
3139
+ pendingSpaceTrimmed = !state.pendingLeadingBlank || pairOwed;
2050
3140
  }
2051
3141
  state.pendingInlineWhitespace = false;
2052
3142
  }
2053
- } else if (!isInlineElement || newLines > 0) state.pendingInlineWhitespace = false;
3143
+ } else if (!isInlineElement && !owed || newLines > 0) state.pendingInlineWhitespace = false;
2054
3144
  }
2055
3145
  if (newLines > 0) {
3146
+ pendingCloser = 0;
2056
3147
  if (!buff.length && !captionEvent && !captionTransition) {
2057
3148
  if (output) {
2058
3149
  for (const fragment of output) if (fragment) {
@@ -2060,8 +3151,9 @@ function createMarkdownProcessor(options = {}, createStream) {
2060
3151
  state.lastContentCache = fragment;
2061
3152
  }
2062
3153
  }
2063
- if (gfmAction) commitGfmAction(gfmAction, state, gfmLifecycle, state.buffer.length, element);
2064
- updateListIndent(state, element, eventType);
3154
+ if (gfmAction) commitGfmAction(gfmAction, state, gfmLifecycle, state.buffer.length, element, keepsQuoteSeparator);
3155
+ if (eventType === 1 && (tagId === 24 || tagId === 33)) closeListMarker(element, hasPluginOutput || handler?.literalExit ? output?.join("") : void 0);
3156
+ if (tagId === 25) updateListIndent(state, element, eventType, output, hasPluginOutput);
2065
3157
  return;
2066
3158
  }
2067
3159
  if (lastChar === " " && buff?.length) {
@@ -2070,12 +3162,13 @@ function createMarkdownProcessor(options = {}, createStream) {
2070
3162
  if (!measureFromOutputTail) newLines = Math.max(0, configuredNewLines - newlineRunBefore(buff, buff.length));
2071
3163
  }
2072
3164
  const newlinesStr = "\n".repeat(newLines);
3165
+ if (eventType === 1 || !output) breakAfterLastText = true;
2073
3166
  if (eventType === 0) {
2074
3167
  if (output) output.unshift(newlinesStr);
2075
3168
  else output = [newlinesStr];
2076
3169
  } else if (output) output.push(newlinesStr);
2077
3170
  else output = [newlinesStr];
2078
- } else if (lastFragment && state.lastTextNode?.containsWhitespace && (!!node.parent || isInlineElement) && "value" in state.lastTextNode && typeof state.lastTextNode.value === "string") {
3171
+ } else if (lastFragment && state.lastTextNode?.containsWhitespace && !(breakAfterLastText && !(output && eventType === 1)) && (!!node.parent || isInlineElement) && "value" in state.lastTextNode && typeof state.lastTextNode.value === "string") {
2079
3172
  let parent = node.parent;
2080
3173
  let parentInPre = false;
2081
3174
  while (parent) {
@@ -2088,25 +3181,130 @@ function createMarkdownProcessor(options = {}, createStream) {
2088
3181
  if (!parentInPre || node.parent?.tagId === 34) {
2089
3182
  const collapsesWhiteSpace = node.tagHandler?.collapsesInnerWhiteSpace;
2090
3183
  const hasSpacing = node.tagHandler?.spacing && Array.isArray(node.tagHandler.spacing);
2091
- const isBlockElement = !isInlineElement && !collapsesWhiteSpace && configuredNewLines > 0;
2092
- if (!quoteAtStart && (tagId === 6 && output?.[0]?.endsWith("\n") && !parentInPre || (!isInlineElement || eventType === 1) && !isBlockElement && !(collapsesWhiteSpace && eventType === 0) && !(hasSpacing && eventType === 0))) {
3184
+ const isBlockElement = !isInlineElement && configuredNewLines > 0 && !(eventType === 1 ? node.parent?.tagHandler?.collapsesInnerWhiteSpace : collapsesWhiteSpace);
3185
+ if (!quoteAtStart && !(tagId === 34 && eventType === 1 && isInsideTableCell(state)) && (tagId === 6 && output?.[0]?.endsWith("\n") && !parentInPre || (!isInlineElement || eventType === 1) && !isBlockElement && !(collapsesWhiteSpace && eventType === 0) && !(hasSpacing && eventType === 0))) {
2093
3186
  const originalLength = lastFragment.length;
2094
3187
  const trimmed = trimAsciiWhitespaceEnd(lastFragment);
2095
3188
  if (originalLength - trimmed.length > 0) {
2096
3189
  if (buff?.length && buff.at(-1) === lastFragment) {
2097
- state.outputPositions?.replace(buff.length - 1, buff.length, [trimmed]);
2098
- buff[buff.length - 1] = trimmed;
3190
+ if (trimmed || buff.length < 2 || buff[buff.length - 2] !== "") {
3191
+ state.outputPositions?.replace(buff.length - 1, buff.length, [trimmed]);
3192
+ buff[buff.length - 1] = trimmed;
3193
+ } else {
3194
+ state.outputPositions?.replace(buff.length - 1, buff.length, []);
3195
+ buff.length--;
3196
+ }
3197
+ }
3198
+ if (eventType === 1 && isInlineElement) {
3199
+ state.pendingInlineWhitespace = true;
3200
+ state.pendingLeadingBlank = false;
3201
+ state.pendingPairSeparator = false;
3202
+ state.pendingDecodedBlank = false;
2099
3203
  }
2100
- if (eventType === 1 && isInlineElement) state.pendingInlineWhitespace = true;
2101
3204
  }
2102
3205
  }
2103
3206
  state.lastTextNode = void 0;
2104
3207
  }
2105
3208
  }
2106
- if (!captionTransition && tagId !== 6 && output?.[0]?.[0] && eventType === 0 && !handler?.literalEnter && lastChar && needsSpacing(lastChar, output[0][0], state)) {
3209
+ let linkHeadingBreak = false;
3210
+ if (state.headingBreakPending && eventType === 0) {
3211
+ if (tagId === 25 || captionEvent || output?.[0] && trimLeadingSpaces(output[0]).startsWith("\n")) {
3212
+ state.headingBreakPending = false;
3213
+ if (captionEvent && !state.depthMap[34] && captionFrameCount !== 0) captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 2] |= CAPTION_HEADING_BREAK;
3214
+ } else if (output?.some(hasNonWhitespace)) {
3215
+ state.headingBreakPending = false;
3216
+ const separator = `\n\n${state.listIndent}`;
3217
+ if (tagId === 26 && output[0] === "[") {
3218
+ linkHeadingBreak = true;
3219
+ buff.push(separator);
3220
+ state.lastContentCache = separator;
3221
+ lastChar = " ";
3222
+ } else {
3223
+ const first = output[0];
3224
+ output[0] = `${separator}${trimLeadingSpaces(first)}`;
3225
+ if (handlerOutput === first) handlerOutput = output[0];
3226
+ if (gfmAction?._tag === "CodeSpanEnter") gfmAction = {
3227
+ _tag: "CodeSpanEnter",
3228
+ output: `${separator}${trimLeadingSpaces(gfmAction.output)}`
3229
+ };
3230
+ }
3231
+ }
3232
+ }
3233
+ if (eventType === 0 && tagId >= 7 && tagId <= 12 && state.depthMap[25] && !handler?.literalEnter && !hasPluginOutput && output?.[0]?.startsWith("\n") && buff.length > 0 && !opensBlockLine(buff, buff.length - 1, buff.at(-1).length)) {
3234
+ if (headingKeptInlineInItem(element)) {
3235
+ output[0] = `${"#".repeat(tagId - 7 + 1)} `;
3236
+ handlerOutput = output[0];
3237
+ } else trimTrailingSpaces(buff);
3238
+ }
3239
+ if (eventType === 0 && tagId >= 7 && tagId <= 12 && state.depthMap[25] && !state.depthMap[34] && !isInsideTableCell(state) && !hasPluginOutput && output?.length === 1 && output[0]?.charCodeAt(0) === 35 && (handler?.literalEnterHeading || !handler?.literalEnter && output[0] === `${"#".repeat(tagId - 7 + 1)} `) && captionFrameCount === 0 && !headingKeptInlineInItem(element) && buff.length > 0 && !opensBlockLine(buff, buff.length - 1, buff.at(-1).length)) {
3240
+ trimTrailingSpaces(buff);
3241
+ output[0] = `\n\n${state.listIndent}${output[0]}`;
3242
+ handlerOutput = output[0];
3243
+ }
3244
+ if (!captionTransition && output?.[0]?.[0] && (tagId !== 6 || output[0][0] === "<") && eventType === 0 && !handler?.literalEnter && lastChar && needsMarkdownSpacing(lastChar, output[0][0], openMarkerCount) && !(pendingRawHtmlBoundary && newLines < 2 && !isInsideRawHtmlBlock(state.depthMap))) {
3245
+ pendingCloser = 0;
2107
3246
  state.buffer.push(" ");
2108
3247
  state.lastContentCache = " ";
2109
3248
  }
3249
+ if (eventType === 1 && handlerOutput) {
3250
+ const markerType = INLINE_MARKER_TYPE[tagId];
3251
+ if (markerType && markerType <= 4) {
3252
+ const mark = handlerOutput.charCodeAt(0);
3253
+ const previous = lastOutputChar(buff);
3254
+ if (previous !== mark && isAsciiPunctuation(previous) && !handler?.literalExit && !options.tagOverrides && !captionFrameCount && !insideRawHtmlRegion && !state.depthMap[34] && !state.depthMap[23] && !state.depthMap[46] && !state.depthMap[82] && !state.depthMap[92]) pendingCloser = mark;
3255
+ }
3256
+ }
3257
+ let trailingEmphasisWhitespace = "";
3258
+ if (eventType === 1 && !handler?.literalExit && INLINE_MARKER_TYPE[tagId] >= 1 && INLINE_MARKER_TYPE[tagId] <= 4 && (output?.[0]?.charCodeAt(0) === 42 || output?.[0]?.charCodeAt(0) === 126)) {
3259
+ let firstFragment = buff.length;
3260
+ let firstOffset = 0;
3261
+ let hasVerticalTab = false;
3262
+ for (let index = buff.length - 1; index >= 0; index--) {
3263
+ const fragment = buff[index];
3264
+ let end = fragment.length;
3265
+ while (end > 0) {
3266
+ const code = fragment.charCodeAt(end - 1);
3267
+ if (code !== 11 && !isAsciiWhitespace(code)) break;
3268
+ hasVerticalTab ||= code === 11;
3269
+ end--;
3270
+ }
3271
+ if (end < fragment.length) {
3272
+ firstFragment = index;
3273
+ firstOffset = end;
3274
+ }
3275
+ if (end > 0) break;
3276
+ }
3277
+ if (hasVerticalTab) {
3278
+ for (let index = firstFragment; index < buff.length; index++) {
3279
+ const fragment = buff[index];
3280
+ const end = index === firstFragment ? firstOffset : 0;
3281
+ trailingEmphasisWhitespace += fragment.slice(end);
3282
+ const trimmed = fragment.slice(0, end);
3283
+ state.outputPositions?.replace(index, index + 1, [trimmed]);
3284
+ buff[index] = trimmed;
3285
+ }
3286
+ noteBufferRewrite(state);
3287
+ if (newLines > 0 && output) {
3288
+ output.splice(output.length - 1, 0, trailingEmphasisWhitespace);
3289
+ trailingEmphasisWhitespace = "";
3290
+ }
3291
+ }
3292
+ }
3293
+ if (pendingCloser && output && breaksPendingCloser(output, eventType === 0, pendingCloser)) pendingCloser = 0;
3294
+ if (eventType === 1 && tagId >= 7 && tagId <= 12 && state.depthMap[25] && !state.depthMap[34] && captionFrameCount === 0 && !state.depthMap[26] && !isInsideTableCell(state) && (!handler?.literalEnter || handler.literalEnterHeading) && !headingKeptInlineInItem(element)) {
3295
+ if (handler?.literalEnterHeading) {
3296
+ if (handler.literalExit) escapeTrailingHeadingHashes(state);
3297
+ trimTrailingSpaces(buff);
3298
+ }
3299
+ state.headingBreakPending = true;
3300
+ }
3301
+ if (eventType === 0 && tagId === 6 && !state.depthMap[34] && !handler?.literalEnter && output?.at(-1)?.endsWith("\n") && lastOutputChar(buff) === 32) trimTrailingSpaces(buff);
3302
+ const rawHtmlQuoteBoundary = pendingRawHtmlBoundary && gfmAction?._tag === "BlockquoteEnter";
3303
+ if (rawHtmlQuoteBoundary) finishRawHtmlBlock(`${output?.join("") ?? ""}>`, true);
3304
+ if (pendingRawHtmlBoundary && !endsRawHtmlBlock && output && eventType === 0) {
3305
+ if (newLines >= 2) pendingRawHtmlBoundary = false;
3306
+ else finishRawHtmlBlock(output.join(""), true);
3307
+ }
2110
3308
  let outputStart = state.buffer.length;
2111
3309
  if (output) {
2112
3310
  outputStart = state.buffer.length;
@@ -2115,26 +3313,121 @@ function createMarkdownProcessor(options = {}, createStream) {
2115
3313
  state.lastContentCache = fragment;
2116
3314
  }
2117
3315
  }
2118
- if (gfmAction) commitGfmAction(gfmAction, state, gfmLifecycle, outputStart, element);
3316
+ if (eventType === 0 && handler?.literalEnter && (handler.isInline ?? tagId === -1) && outputStart < buff.length) literalOpeners.push(element.depth, buff.length);
3317
+ if (trailingEmphasisWhitespace) {
3318
+ state.buffer.push(trailingEmphasisWhitespace);
3319
+ state.lastContentCache = trailingEmphasisWhitespace;
3320
+ }
3321
+ if (gfmAction) commitGfmAction(gfmAction, state, gfmLifecycle, outputStart, element, keepsQuoteSeparator, rawHtmlQuoteBoundary);
3322
+ else if (eventType === 0 && (tagId === 23 && handlerOutput === "<code>" || (tagId === 46 || tagId === 82 || tagId === 92) && handlerOutput === "`") && !state.codeText && !handler?.literalEnter) state.codeText = {
3323
+ owner: element,
3324
+ kind: "raw"
3325
+ };
2119
3326
  if (tagId === 25 && !isInsideTableCell(state)) {
2120
- if (eventType === 0) recordItemMarker(state, element.index);
2121
- else resolveItemMarker(state, true);
3327
+ if (eventType === 0) recordItemMarker(state, element.index, handler?.literalEnter ? "" : lastChar);
3328
+ else resolveItemMarker(state, true, -1, openLinkFragment !== -1);
2122
3329
  }
2123
- if (eventType === 0 && tagId === 26 && outputStart < buff.length && buff.at(-1) === "[") openLink(buff.length - 1);
3330
+ if (eventType === 0 && tagId === 26 && outputStart < buff.length && buff.at(-1) === "[") openLink(buff.length - 1, linkHeadingBreak);
2124
3331
  if (cleanPass) {
2125
- if (eventType === 0) cleanPass.enter(element, outputStart);
2126
- else if (handlerOutput) cleanPass.closed(element, outputStart, handlerOutput);
3332
+ if (eventType === 0) cleanPass.enter(element, outputStart, closerBefore);
3333
+ else if (handlerOutput) {
3334
+ cleanPass.closed(element, outputStart, handlerOutput, closerBefore);
3335
+ if (tagId === 26) noteBufferRewrite(state);
3336
+ }
3337
+ }
3338
+ if (eventType === 1 && handlerOutput !== void 0 && !handler?.literalExit && !handler?.literalEnter) {
3339
+ const closedType = INLINE_MARKER_TYPE[tagId];
3340
+ if ((closedType === 1 || closedType === 2 || closedType === 4) && buff[buff.length - 1] === handlerOutput) {
3341
+ let previous = buff.length - 2;
3342
+ while (previous >= 0 && buff[previous] === "") previous--;
3343
+ if (closedMarkerCount && closedMarkers[closedMarkerCount - 1] !== previous) closedMarkerCount = 0;
3344
+ const before = lastOutputChar(buff, buff.length - 1);
3345
+ if (closedMarkerCount && buff[closedMarkers[closedMarkerCount - 1]] === handlerOutput) closedMarkerCount = 0;
3346
+ else if (before !== -1 && before !== 96 && !isAsciiWhitespace(before)) closedMarkers[closedMarkerCount++] = buff.length - 1;
3347
+ }
2127
3348
  }
2128
3349
  if (eventType === 0 && handlerOutput !== void 0 && isInlineElement && !handler?.literalEnter) {
2129
3350
  const markerType = INLINE_MARKER_TYPE[tagId];
2130
- if (markerType && (tagId !== 23 || !state.depthMap[34] && !isInsideRawHtmlBlock(state.depthMap)) && buff[buff.length - 1] === handlerOutput) openMarkers[openMarkerCount++] = buff.length - 1 << 3 | markerType;
2131
- else if (openMarkerCount && !(tagId === 26 && cleanEmptyLinkText) && hasNonWhitespace(handlerOutput)) {
3351
+ if (markerType && (tagId !== 23 || !state.depthMap[34] && !isInsideRawHtmlBlock(state.depthMap)) && buff[buff.length - 1] === handlerOutput) {
3352
+ openMarkerClosers[openMarkerCount] = closerBefore;
3353
+ if (silentMarkerCount > openMarkerCount) silentMarkerCount = openMarkerCount;
3354
+ if (blankMarkerCount > openMarkerCount) blankMarkerCount = 0;
3355
+ let closer = buff.length - 2;
3356
+ while (closer >= 0 && buff[closer] === "") closer--;
3357
+ const merges = (markerType === 1 || markerType === 2 || markerType === 4) && (handlerOutput === "*" || handlerOutput === "**") && !handler?.literalExit && !(state.blockquotes.length && state.blockquotes[state.blockquotes.length - 1].fragment > closer) && !captionNeedsPreparation();
3358
+ const reopened = openMarkerCount ? openMarkers[openMarkerCount - 1] : 0;
3359
+ if (merges && (reopened & MARKER_TYPE_MASK) === MARKER_TYPE_MASK && closer < reopened >> 3 && reopenedDelimiter === handlerOutput && !openMarkerFollowsSpace[openMarkerCount - 1]) {
3360
+ const opener = buff.length - 1;
3361
+ state.outputPositions?.replace(opener, opener, [handlerOutput, handlerOutput]);
3362
+ buff.splice(opener, 0, handlerOutput, handlerOutput);
3363
+ noteBufferRewrite(state);
3364
+ if (closedMarkerCount && closedMarkers[closedMarkerCount - 1] !== closer) closedMarkerCount = 0;
3365
+ closedMarkers[closedMarkerCount++] = opener;
3366
+ unmergedOpener = opener + 1;
3367
+ unmergedSlot = openMarkerCount - 1;
3368
+ openMarkers[unmergedSlot] = unmergedOpener << 3 | reopenedType;
3369
+ openMarkerRunLength[unmergedSlot] = 1;
3370
+ openMarkerFollowsSpace[unmergedSlot] = false;
3371
+ openMarkerSeparatorTrimmed[unmergedSlot] = false;
3372
+ openMarkerRunLength[openMarkerCount] = 2;
3373
+ openMarkerFollowsSpace[openMarkerCount] = false;
3374
+ openMarkerSeparatorTrimmed[openMarkerCount] = false;
3375
+ openMarkers[openMarkerCount++] = buff.length - 1 << 3 | markerType;
3376
+ } else if (merges && closedMarkerCount && closedMarkers[closedMarkerCount - 1] === closer && buff[closer] === handlerOutput && (markerType === 1 ? state.depthMap[14] + state.depthMap[15] + state.depthMap[91] : state.depthMap[16] + state.depthMap[17] + state.depthMap[90] + state.depthMap[106]) < 2) {
3377
+ reopenedDelimiter = handlerOutput;
3378
+ reopenedType = markerType;
3379
+ closedMarkerCount--;
3380
+ state.outputPositions?.replace(closer, buff.length, []);
3381
+ buff.length = closer;
3382
+ noteBufferRewrite(state);
3383
+ state.lastContentCache = buff[buff.length - 1];
3384
+ for (let index = openMarkerCount - 1; index >= 0 && openMarkers[index] >> 3 > buff.length; index--) openMarkers[index] = buff.length << 3 | MARKER_TYPE_MASK;
3385
+ if (unmergedSlot >= openMarkerCount) unmergedSlot = -1;
3386
+ openMarkerRunLength[openMarkerCount] = 1;
3387
+ openMarkerFollowsSpace[openMarkerCount] = false;
3388
+ openMarkerSeparatorTrimmed[openMarkerCount] = false;
3389
+ openMarkers[openMarkerCount++] = buff.length << 3 | MARKER_TYPE_MASK;
3390
+ } else {
3391
+ if (unmergedSlot >= openMarkerCount) unmergedSlot = -1;
3392
+ const previous = openMarkers[openMarkerCount - 1];
3393
+ openMarkerRunLength[openMarkerCount] = openMarkerCount > 0 && markerType <= 4 && (previous & MARKER_TYPE_MASK) <= 4 && previous >> 3 === buff.length - 2 ? openMarkerRunLength[openMarkerCount - 1] + 1 : 1;
3394
+ const followsSpace = pendingSpaceFragment === buff.length - 2 || pendingSpaceOwned && handlerOutput.charCodeAt(0) === 32;
3395
+ openMarkerFollowsSpace[openMarkerCount] = followsSpace;
3396
+ openMarkerSeparatorTrimmed[openMarkerCount] = followsSpace && pendingSpaceTrimmed;
3397
+ openMarkers[openMarkerCount++] = buff.length - 1 << 3 | markerType;
3398
+ }
3399
+ } else if (openMarkerCount && !(tagId === 26 && cleanEmptyLinkText) && hasNonWhitespace(handlerOutput)) {
2132
3400
  openMarkerCount = 0;
2133
3401
  commitCaptionFrames();
2134
3402
  }
2135
- } else if (openMarkerCount && (eventType === 1 && handler?.literalExit || tagId !== -1 && !isInlineElement || output?.some(hasNonWhitespace))) openMarkerCount = 0;
3403
+ } else if (openMarkerCount && (eventType === 1 && handler?.literalExit || tagId !== -1 && !isInlineElement && (output !== void 0 || configuredNewLines > 0) || output?.some(hasNonWhitespace))) openMarkerCount = 0;
3404
+ else if (openMarkerCount && eventType === 1 && tagId !== -1 && !isInlineElement) {
3405
+ if (blankMarkerCount && blankMarkerCount <= openMarkerCount) {
3406
+ const kept = openMarkerCount - blankMarkerCount;
3407
+ for (let i = 0; i < kept; i++) {
3408
+ openMarkers[i] = openMarkers[i + blankMarkerCount];
3409
+ openMarkerClosers[i] = openMarkerClosers[i + blankMarkerCount];
3410
+ openMarkerFollowsSpace[i] = openMarkerFollowsSpace[i + blankMarkerCount];
3411
+ openMarkerSeparatorTrimmed[i] = openMarkerSeparatorTrimmed[i + blankMarkerCount];
3412
+ openMarkerRunLength[i] = openMarkerRunLength[i + blankMarkerCount];
3413
+ }
3414
+ openMarkerCount = kept;
3415
+ blankMarkerCount = 0;
3416
+ }
3417
+ silentMarkerCount = openMarkerCount;
3418
+ }
2136
3419
  if (eventType === 1 && tagId === 26) openLinkFragment = -1;
2137
- updateListIndent(state, element, eventType);
3420
+ if (closesQuote && state.depthMap[25] && !state.depthMap[34] && !insideRawHtmlRegion && !isInsideTableCell(state)) {
3421
+ captionBoundary = 3;
3422
+ captionBoundarySpacing = 2;
3423
+ state.listRulePending = void 0;
3424
+ }
3425
+ if (eventType === 1 && (tagId === 24 || tagId === 33)) closeListMarker(element, hasPluginOutput || handler?.literalExit ? output?.join("") : void 0);
3426
+ if (tagId === 25) updateListIndent(state, element, eventType, output, hasPluginOutput);
3427
+ if (emptyQuoteItemExit) {
3428
+ captionBoundary = 3;
3429
+ captionBoundarySpacing = 2;
3430
+ }
2138
3431
  if (!insideRawHtmlRegion && inRawHtmlRegion) {
2139
3432
  bufferScan[0] = false;
2140
3433
  bufferScan[1] = state.buffer.length;
@@ -2147,7 +3440,8 @@ function createMarkdownProcessor(options = {}, createStream) {
2147
3440
  return cleanPass ? cleanPass.finish(result).markdown : result;
2148
3441
  }
2149
3442
  function getNonQuoteHeldOutputFragment(final = false) {
2150
- let heldFragment = final ? Infinity : Math.min(openMarkerCount ? openMarkers[0] >> 3 : Infinity, gfmLifecycle.openCodeSpans[0]?.fragment ?? Infinity, state.emptyItemFragment ?? Infinity, state.codeFence?.fragment ?? Infinity, openLinkFragment === -1 ? Infinity : openLinkFragment < -1 ? -openLinkFragment - 2 : openLinkFragment);
3443
+ let heldFragment = final ? Infinity : Math.min(openMarkerCount ? openMarkers[0] >> 3 : Infinity, heldClosedMarker(), gfmLifecycle.openCodeSpans[0]?.fragment ?? Infinity, state.emptyItemFragment ?? Infinity, state.codeFence?.fragment ?? Infinity, openLinkFragment === -1 ? Infinity : openLinkFragment < -1 ? -openLinkFragment - 2 : openLinkFragment - Number(openLinkHeadingBreak));
3444
+ if (!final && literalOpeners.length) heldFragment = holdLiteralOpener(heldFragment);
2151
3445
  if (cleanPass && !final) heldFragment = Math.min(heldFragment, cleanPass.held());
2152
3446
  const captionHoldCount = final ? 0 : captionFrameCount;
2153
3447
  for (let index = 0; index < captionHoldCount; index++) {
@@ -2165,13 +3459,22 @@ function createMarkdownProcessor(options = {}, createStream) {
2165
3459
  let heldFragment = getNonQuoteHeldOutputFragment(final);
2166
3460
  const quoteHoldCount = final ? 0 : state.blockquotes.length;
2167
3461
  for (let index = 0; index < quoteHoldCount; index++) {
2168
- const fragment = state.blockquotes[index].fragment;
3462
+ const frame = state.blockquotes[index];
3463
+ const fragment = frame.fragment - frame.itemSeparatorFragments;
2169
3464
  if (fragment < heldFragment) heldFragment = fragment;
2170
3465
  }
2171
3466
  return heldFragment > state.buffer.length ? Infinity : heldFragment;
2172
3467
  }
2173
3468
  const processor = {
2174
3469
  processEvent,
3470
+ skipEvent(event) {
3471
+ if (event.type !== 1) return;
3472
+ if (state.codeText?.owner === event.node) state.codeText = void 0;
3473
+ const span = gfmLifecycle.openCodeSpans.at(-1);
3474
+ if (span?.owner !== event.node) return;
3475
+ gfmLifecycle.openCodeSpans.pop();
3476
+ if (openMarkerCount && openMarkers[openMarkerCount - 1] === (span.fragment << 3 | 5)) openMarkerCount--;
3477
+ },
2175
3478
  getMarkdown,
2176
3479
  state,
2177
3480
  getHeldOutputFragment: cleanPass ? getHeldOutputFragment : void 0,
@@ -2189,6 +3492,20 @@ function createMarkdownProcessor(options = {}, createStream) {
2189
3492
  inRawHtmlRegion: () => inRawHtmlRegion,
2190
3493
  getNonQuoteHeldOutputFragment,
2191
3494
  getHeldOutputFragment,
3495
+ compactPrefix(fragment, retained) {
3496
+ if (!closedMarkerCount || cleanPass && cleanPass.held() !== Infinity || state.outputPositions || state.blockquotes.length || gfmLifecycle.openCodeSpans.length || openLinkFragment !== -1 || captionFrameCount || literalOpeners.length || state.codeFence || state.emptyItemFragment !== void 0) return false;
3497
+ const removed = fragment - 1;
3498
+ state.buffer.splice(0, fragment, retained);
3499
+ for (let index = 0; index < openMarkerCount; index++) openMarkers[index] = openMarkers[index] - (removed << 3);
3500
+ for (let index = 0; index < closedMarkerCount; index++) closedMarkers[index] -= removed;
3501
+ if (unmergedOpener >= fragment) unmergedOpener -= removed;
3502
+ else unmergedOpener = unmergedSlot = -1;
3503
+ pendingSpaceFragment = pendingSpaceFragment >= fragment ? pendingSpaceFragment - removed : -1;
3504
+ captionLineEnd = 0;
3505
+ captionLineFragment = -1;
3506
+ noteBufferRewrite(state);
3507
+ return true;
3508
+ },
2192
3509
  settleItemMarker() {
2193
3510
  let unresolvedCaptionFragment = -1;
2194
3511
  if (state.emptyItemFragment !== void 0 && captionFrames) for (let index = 0; index < captionFrameCount; index++) {