@mdream/js 2.0.2 → 2.1.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, endsAtHardBreak, figcaptionOwnsBlockSpacing, getLanguageFromAttributes, hasNonWhitespace, isCharacterReferenceTail, isDataUrl, isEmptyLinkHref, isInsideHeading, isInsideTableCell, lastOutputChar, listMarkerLineStart, markRenderedChildContent, needsSpacing, noteBufferRewrite, orderedItemNumber, parseUnsignedInteger, 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,20 +30,79 @@ 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;
33
35
  if (isInsideTableCell(state) || isInsideRawHtmlBlock(depthMap) || isInsideHeading(depthMap)) return "<br>";
34
36
  if (depthMap[34] || depthMap[23]) return "\n";
35
- return ` \n${continuationPrefix(node, state.listIndentWidths || [], !state.bufferedBlockquoteDepth)}`;
37
+ return ` \n${state.listIndent ?? ""}`;
36
38
  }
37
39
  const breakHandler = {
38
- enter: ({ node, state }) => renderBreak(node, state),
40
+ enter: ({ state }) => renderBreak(state),
39
41
  isSelfClosing: true,
40
42
  spacing: NO_SPACING,
41
43
  collapsesInnerWhiteSpace: true,
42
44
  isInline: true
43
45
  };
44
- function escapeTrailingHeadingHashes(buffer, positions) {
46
+ const LEAD_GAP = 0;
47
+ const LEAD_DIGITS = 1;
48
+ const LEAD_INDENT = 2;
49
+ function opensBlockLine(buffer, fragment, cursor) {
50
+ let phase = LEAD_GAP;
51
+ let count = 0;
52
+ for (;;) {
53
+ if (cursor === 0) {
54
+ if (--fragment < 0) return phase !== LEAD_DIGITS || count > 0;
55
+ cursor = buffer[fragment].length;
56
+ continue;
57
+ }
58
+ const code = buffer[fragment].charCodeAt(--cursor);
59
+ if (code === 10) return phase !== LEAD_DIGITS || count > 0;
60
+ if (phase === LEAD_DIGITS) {
61
+ if (code >= 48 && code <= 57) {
62
+ if (++count > 9) return false;
63
+ continue;
64
+ }
65
+ if (count === 0) return false;
66
+ phase = LEAD_INDENT;
67
+ }
68
+ if (code === 32) {
69
+ if (phase === LEAD_GAP) count++;
70
+ continue;
71
+ }
72
+ if (phase !== LEAD_GAP || count === 0) return false;
73
+ if (code === 45 || code === 42 || code === 43) phase = LEAD_INDENT;
74
+ else if (code === 46 || code === 41) {
75
+ phase = LEAD_DIGITS;
76
+ count = 0;
77
+ } else return false;
78
+ }
79
+ }
80
+ function markerOpensBlockLine(state, index, marker) {
81
+ const buffer = state.buffer;
82
+ const memo = state.markerLine;
83
+ if (memo && memo.index === index && buffer[index] === memo.entry && buffer[memo.stop] === memo.stopEntry) return memo.opens;
84
+ const opens = opensBlockLine(buffer, index, marker);
85
+ let fragment = index;
86
+ let cursor = marker;
87
+ for (;;) if (cursor === 0) {
88
+ if (fragment === 0) break;
89
+ cursor = buffer[--fragment].length;
90
+ } else if (isLeadChar(buffer[fragment].charCodeAt(cursor - 1))) cursor--;
91
+ else break;
92
+ state.markerLine = {
93
+ index,
94
+ entry: buffer[index],
95
+ stop: fragment,
96
+ stopEntry: buffer[fragment],
97
+ opens
98
+ };
99
+ return opens;
100
+ }
101
+ function isLeadChar(code) {
102
+ return code === 32 || code >= 48 && code <= 57 || code === 45 || code === 42 || code === 43 || code === 46 || code === 41;
103
+ }
104
+ function escapeTrailingHeadingHashes(state) {
105
+ const buffer = state.buffer;
45
106
  let index = buffer.length - 1;
46
107
  while (index >= 0 && buffer[index] === "") index--;
47
108
  if (index < 0) return;
@@ -51,18 +112,37 @@ function escapeTrailingHeadingHashes(buffer, positions) {
51
112
  let run = end;
52
113
  while (run > 0 && entry[run - 1] === "#") run--;
53
114
  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);
115
+ let replacement;
116
+ if (opensBlockLine(buffer, index, run)) {
117
+ let trimmed = entry.length;
118
+ while (trimmed > end && entry.charCodeAt(trimmed - 1) === 32) trimmed--;
119
+ if (trimmed === entry.length) return;
120
+ replacement = entry.slice(0, trimmed);
121
+ state.outputPositions?.replace(index, index + 1, [replacement]);
122
+ } else {
123
+ const previous = buffer[index - 1];
124
+ const before = run > 0 ? entry[run - 1] : previous?.charAt(previous.length - 1);
125
+ if (before !== " " && before !== " " || inPreCodeFence(state)) return;
126
+ replacement = `${entry.slice(0, run)}\\${entry.slice(run)}`;
127
+ state.outputPositions?.replace(index, index + 1, [replacement], (offset) => offset > run ? offset + 1 : offset);
128
+ }
59
129
  buffer[index] = replacement;
130
+ noteBufferRewrite(state);
131
+ if (state.lastContentCache === entry) state.lastContentCache = replacement;
132
+ }
133
+ function inPreCodeFence(state) {
134
+ return !!state.codeFence && !state.fencesUnreliable && !!state.depthMap?.[34];
135
+ }
136
+ function hasInlineAncestor(node) {
137
+ for (let parent = node.parent; parent; parent = parent.parent) if (parent.tagHandler ? parent.tagHandler.isInline === true : parent.tagId === -1) return true;
138
+ return false;
60
139
  }
61
140
  const LINE_FRESH = -1;
62
141
  const LINE_OPEN = 0;
63
142
  const LINE_ROW = 1;
64
143
  const LINE_CONTENT = 2;
65
- function lineStateBeforeRow(buffer) {
144
+ function lineStateBeforeRow(state) {
145
+ const buffer = state.buffer;
66
146
  let fragment = buffer.length - 1;
67
147
  while (fragment >= 0 && buffer[fragment].length === 0) fragment--;
68
148
  if (fragment < 0) return LINE_OPEN;
@@ -89,12 +169,12 @@ function lineStateBeforeRow(buffer) {
89
169
  }
90
170
  }
91
171
  if (firstNonSpace === -1) return LINE_OPEN;
92
- if (firstNonSpace === 124) return LINE_ROW;
93
- return listMarkerLineStart(buffer, markerFragment, markerIndex) ? LINE_OPEN : LINE_CONTENT;
172
+ if (listMarkerLineStart(buffer, markerFragment, markerIndex, pendingMarkerIndent(state))) return LINE_OPEN;
173
+ return firstNonSpace === 124 ? LINE_ROW : LINE_CONTENT;
94
174
  }
95
175
  function rowMarker(state) {
96
176
  const indent = state.listIndent;
97
- const lineState = lineStateBeforeRow(state.buffer);
177
+ const lineState = lineStateBeforeRow(state);
98
178
  if (!indent) return lineState === LINE_ROW ? "\n| " : lineState === LINE_CONTENT ? "\n\n| " : "| ";
99
179
  switch (lineState) {
100
180
  case LINE_ROW: return `\n${indent}| `;
@@ -118,13 +198,20 @@ function cellExit(node, state) {
118
198
  }
119
199
  function handleHeading(depth) {
120
200
  return {
121
- enter: ({ state }) => {
201
+ enter: ({ node, state }) => {
122
202
  if ((state.depthMap?.[26] || 0) > 0 || isInsideTableCell(state)) return `<h${depth}>`;
123
- return `${"#".repeat(depth)} `;
203
+ const heading = `${"#".repeat(depth)} `;
204
+ if (state.listIndent && lastOutputChar(state.buffer) === 10 && state.blockquotes?.at(-1)?.fragment !== state.buffer.length) return `\n${state.listIndent}${heading}`;
205
+ if (state.listIndent && node.parent?.tagId === 25) {
206
+ const prefix = state.listIndent;
207
+ const open = blockOpenPrefix(state, prefix);
208
+ if (open !== void 0) return `${open}${heading}`;
209
+ }
210
+ return heading;
124
211
  },
125
212
  exit: ({ state }) => {
126
213
  if ((state.depthMap?.[26] || 0) > 0 || isInsideTableCell(state)) return `</h${depth}>`;
127
- escapeTrailingHeadingHashes(state.buffer, state.outputPositions);
214
+ escapeTrailingHeadingHashes(state);
128
215
  },
129
216
  collapsesInnerWhiteSpace: true
130
217
  };
@@ -188,11 +275,13 @@ const tagHandlers = {
188
275
  },
189
276
  [52]: {
190
277
  excludesTextNodes: true,
191
- isNonNesting: true
278
+ isNonNesting: true,
279
+ spacing: NO_SPACING
192
280
  },
193
281
  [53]: {
194
282
  isNonNesting: true,
195
- excludesTextNodes: true
283
+ excludesTextNodes: true,
284
+ spacing: NO_SPACING
196
285
  },
197
286
  [5]: {
198
287
  collapsesInnerWhiteSpace: true,
@@ -209,12 +298,13 @@ const tagHandlers = {
209
298
  [13]: {
210
299
  enter: ({ node, state }) => {
211
300
  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}---`;
301
+ if (!state.depthMap?.[25]) return "---";
302
+ const prefix = state.listIndent;
303
+ state.listRulePending = prefix;
304
+ const end = enterOutputEnd(node, state);
305
+ if (state.codeFence?.fragment === end - 1 && state.buffer[end - 1].endsWith("\n")) return `${prefix}***`;
306
+ const open = blockOpenPrefix(state, prefix, end);
307
+ return open === void 0 && prefix ? "***" : `${open ?? ""}---`;
218
308
  },
219
309
  isSelfClosing: true
220
310
  },
@@ -250,7 +340,7 @@ const tagHandlers = {
250
340
  enter: ({ state }) => {
251
341
  return {
252
342
  _tag: "BlockquoteEnter",
253
- output: (state.depthMap?.[25] || 0) > 0 ? "\n" : void 0
343
+ output: (state.depthMap?.[25] || 0) > 0 && !isInsideTableCell(state) ? "\n" : void 0
254
344
  };
255
345
  },
256
346
  exit: () => ({ _tag: "BlockquoteExit" }),
@@ -259,9 +349,10 @@ const tagHandlers = {
259
349
  [34]: {
260
350
  enter: ({ node, state }) => {
261
351
  if (isInsideTableCell(state)) return "<pre>";
352
+ if (!state.preFenceOwnerDepth && !state.preFencePending) state.preFenceInline = hasInlineAncestor(node);
262
353
  return {
263
354
  _tag: "PreEnter",
264
- language: getLanguageFromClass(node.attributes?.class)
355
+ language: getLanguageFromAttributes(node.attributes)
265
356
  };
266
357
  },
267
358
  exit: ({ state }) => {
@@ -274,13 +365,13 @@ const tagHandlers = {
274
365
  if ((state.depthMap?.[34] || 0) > 0) {
275
366
  if (isInsideTableCell(state)) return "<code>";
276
367
  if (state.preFenceOwnerDepth) return;
277
- const language = getLanguageFromClass(node.attributes?.class);
368
+ const language = getLanguageFromAttributes(node.attributes) || state.preFenceLang || "";
278
369
  if ((state.depthMap?.[25] || 0) > 0) {
279
370
  const indent = state.listIndent;
280
371
  return {
281
372
  _tag: "CodeFenceEnter",
282
373
  language,
283
- output: `${blockOpenPrefix(state.buffer, indent) ?? ""}\`\`\`${language}\n`
374
+ output: `${blockOpenPrefix(state, indent) ?? ""}\`\`\`${language}\n`
284
375
  };
285
376
  }
286
377
  return {
@@ -407,9 +498,9 @@ const tagHandlers = {
407
498
  },
408
499
  exit: ({ state }) => isInsideTableCell(state) ? "</table>" : void 0
409
500
  },
410
- [107]: { enter: ({ state }) => {
501
+ [107]: { enter: ({ node, state }) => {
411
502
  if ((state.depthMap?.[25] || 0) === 0 || isInsideTableCell(state)) return void 0;
412
- return blockOpenPrefix(state.buffer, state.listIndent);
503
+ return blockOpenPrefix(state, state.listIndent, enterOutputEnd(node, state));
413
504
  } },
414
505
  [29]: {
415
506
  enter: ({ state }) => {
@@ -480,14 +571,24 @@ const tagHandlers = {
480
571
  collapsesInnerWhiteSpace: true,
481
572
  spacing: NO_SPACING
482
573
  },
483
- [35]: { enter: ({ state }) => {
484
- if ((state.depthMap?.[25] || 0) > 0 && !isInsideTableCell(state)) {
485
- const lastEntry = state.buffer.at(-1);
574
+ [35]: { enter: ({ node, state }) => {
575
+ if ((state.depthMap?.[25] || 0) > 0 && !isInsideTableCell(state) && !state.preFencePending && state.preFenceOpener !== node) {
576
+ const lastEntry = state.buffer[enterOutputEnd(node, state) - 1];
486
577
  const lastChar = lastEntry?.charAt(lastEntry.length - 1) || "";
487
578
  if (lastChar && lastChar !== " " && lastChar !== "\n") return `\n\n${state.listIndent}`;
488
579
  }
489
580
  } },
490
- [36]: {},
581
+ [36]: { enter: ({ state }) => {
582
+ if ((state.depthMap?.[25] || 0) > 0 && !isInsideTableCell(state)) {
583
+ let index = state.buffer.length - 1;
584
+ while (index >= 0 && state.buffer[index] === "") index--;
585
+ const entry = state.buffer[index] || "";
586
+ let marker = entry.length;
587
+ while (marker > 0 && entry.length - marker < 7 && entry.charCodeAt(marker - 1) === 35) marker--;
588
+ const hashes = entry.length - marker;
589
+ if (hashes > 0 && hashes <= 6 && markerOpensBlockLine(state, index, marker)) return `\n\n${state.listIndent}`;
590
+ }
591
+ } },
491
592
  [37]: {
492
593
  collapsesInnerWhiteSpace: true,
493
594
  spacing: NO_SPACING,
@@ -766,6 +867,7 @@ const MARKER_TYPE_MASK = 7;
766
867
  const CAPTION_FRAME_SIZE = 4;
767
868
  const CAPTION_OPEN = 1;
768
869
  const CAPTION_INTERNAL_BREAK = 2;
870
+ const CAPTION_HEADING_BREAK = 4;
769
871
  const CAPTION_DEFAULT_SPACING = -1;
770
872
  const CAPTION_NO_ANCHOR = -1;
771
873
  INLINE_MARKER_TYPE[14] = 1;
@@ -782,9 +884,6 @@ INLINE_MARKER_TYPE[23] = 5;
782
884
  INLINE_MARKER_TYPE[82] = 5;
783
885
  INLINE_MARKER_TYPE[92] = 5;
784
886
  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;
787
- }
788
887
  function newlineRunBefore(buffer, index) {
789
888
  let run = 0;
790
889
  for (let i = index - 1; i >= 0; i--) {
@@ -796,6 +895,20 @@ function newlineRunBefore(buffer, index) {
796
895
  }
797
896
  return run;
798
897
  }
898
+ function crFollowsLineEnding(buffer, index) {
899
+ let skippedCr = false;
900
+ for (let i = index - 1; i >= 0; i--) {
901
+ const fragment = buffer[i];
902
+ for (let j = fragment.length - 1; j >= 0; j--) {
903
+ if (skippedCr) {
904
+ const code = fragment.charCodeAt(j);
905
+ return code === 10 || code === 13;
906
+ }
907
+ skippedCr = true;
908
+ }
909
+ }
910
+ return false;
911
+ }
799
912
  function newlineRunBeforePrefix(buffer, index, prefix) {
800
913
  let fragment = index - 1;
801
914
  let offset = fragment >= 0 ? buffer[fragment].length : 0;
@@ -816,14 +929,19 @@ function newlineRunBeforePrefix(buffer, index, prefix) {
816
929
  run++;
817
930
  }
818
931
  }
819
- function recordItemMarker(state, index) {
820
- if (index !== 0 || newlineRunBefore(state.buffer, state.buffer.length - 1) !== 1) {
932
+ function recordItemMarker(state, index, lastChar) {
933
+ const buffer = state.buffer;
934
+ const marker = buffer.length - 1;
935
+ const run = index === 0 ? newlineRunBefore(buffer, marker) : -1;
936
+ const afterCr = run === 0 && lastChar === "\r";
937
+ if (afterCr ? crFollowsLineEnding(buffer, buffer[marker - 1] === " " ? marker - 1 : marker) : run !== 1) {
821
938
  state.emptyItemFragment = void 0;
822
939
  return;
823
940
  }
824
- state.emptyItemFragment = state.buffer.length - 1;
941
+ state.emptyItemFragment = marker;
942
+ state.emptyItemAfterCr = afterCr;
825
943
  }
826
- function resolveItemMarker(state, atExit, unresolvedCaptionFragment = -1) {
944
+ function resolveItemMarker(state, atExit, unresolvedCaptionFragment = -1, linkOpen = false) {
827
945
  const fragment = state.emptyItemFragment;
828
946
  if (fragment === void 0) return;
829
947
  const buffer = state.buffer;
@@ -839,7 +957,8 @@ function resolveItemMarker(state, atExit, unresolvedCaptionFragment = -1) {
839
957
  }
840
958
  }
841
959
  if (first === -1 && !atExit) return;
842
- if (first === 10 && !atExit) return;
960
+ const lineEnds = first === 10 || first === 13;
961
+ if (lineEnds && !atExit) return;
843
962
  if (!atExit && unresolvedCaptionFragment !== -1) {
844
963
  let captionOpensItem = true;
845
964
  for (let index = fragment + 1; index < unresolvedCaptionFragment; index++) if (hasNonWhitespace(buffer[index])) {
@@ -849,10 +968,19 @@ function resolveItemMarker(state, atExit, unresolvedCaptionFragment = -1) {
849
968
  if (captionOpensItem) return;
850
969
  }
851
970
  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);
971
+ if (first !== -1 && !lineEnds) return;
972
+ const afterCr = state.emptyItemAfterCr;
973
+ if (first === -1 && afterCr && linkOpen) return;
974
+ const spaced = afterCr && buffer[fragment - 1] === " ";
975
+ if (spaced) {
976
+ state.outputPositions?.replace(fragment - 1, fragment, ["\n"]);
977
+ buffer[fragment - 1] = "\n";
978
+ }
979
+ const separator = afterCr && !spaced ? "\n\n" : "\n";
980
+ const replacement = separator + buffer[fragment];
981
+ state.outputPositions?.replace(fragment, fragment + 1, [replacement], (offset) => offset + separator.length);
855
982
  buffer[fragment] = replacement;
983
+ noteBufferRewrite(state);
856
984
  }
857
985
  function updateListIndent(state, element, eventType) {
858
986
  if (element.tagId !== 25) return;
@@ -866,11 +994,6 @@ function updateListIndent(state, element, eventType) {
866
994
  state.listIndent = state.listIndent.slice(0, state.listIndent.length - width);
867
995
  }
868
996
  }
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);
873
- }
874
997
  function shouldAddSpacingBeforeText(lastChar, lastNode, textNode) {
875
998
  if (!lastChar || "\n [>".includes(lastChar)) return false;
876
999
  if (textNode.joinsPrevious || lastNode && (lastNode.tagHandler ? lastNode.tagHandler.isInline : lastNode.tagId === -1)) return false;
@@ -988,18 +1111,18 @@ function lineOpensRawHtmlBlock(buffer, scan) {
988
1111
  scan[3] = buffer.length;
989
1112
  scan[4] = 0;
990
1113
  }
991
- function markdownLineIndent(buffer) {
1114
+ function markdownLineIndent(buffer, structuralIndent) {
992
1115
  let spaces = 0;
993
1116
  for (let fragmentIndex = buffer.length - 1; fragmentIndex >= 0; fragmentIndex--) {
994
1117
  const fragment = buffer[fragmentIndex];
995
1118
  for (let index = fragment.length - 1; index >= 0; index--) {
996
1119
  const code = fragment.charCodeAt(index);
997
- if (code === 10) return spaces;
998
- if (code !== 32 || spaces === 3) return listMarkerLineStart(buffer, fragmentIndex, index) ? 0 : -1;
1120
+ if (code === 10 || code === 13) return Math.max(0, spaces - structuralIndent);
1121
+ if (code !== 32 || spaces === structuralIndent + 3) return listMarkerLineStart(buffer, fragmentIndex, index) ? 0 : -1;
999
1122
  spaces++;
1000
1123
  }
1001
1124
  }
1002
- return spaces;
1125
+ return Math.max(0, spaces - structuralIndent);
1003
1126
  }
1004
1127
  function isMarkdownMarkerWhitespace(code) {
1005
1128
  return code === 0 || code === 9 || code === 10 || code === 13 || code === 32;
@@ -1007,23 +1130,67 @@ function isMarkdownMarkerWhitespace(code) {
1007
1130
  function canStartGfmAngleConstruct(code) {
1008
1131
  return code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 33 || code === 47 || code === 63;
1009
1132
  }
1010
- function isThematicBreak(value, start, marker) {
1011
- let count = 0;
1133
+ function isDashLine(value, start) {
1012
1134
  for (let index = start; index < value.length; index++) {
1013
1135
  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;
1136
+ if (code === 10 || code === 13) break;
1137
+ if (code !== 45 && code !== 32 && code !== 9) return false;
1017
1138
  }
1018
- return count >= 3;
1139
+ return true;
1140
+ }
1141
+ function isEqualsLine(value, start) {
1142
+ let index = start + 1;
1143
+ while (index < value.length && value.charCodeAt(index) === 61) index++;
1144
+ for (; index < value.length; index++) {
1145
+ const code = value.charCodeAt(index);
1146
+ if (code === 10 || code === 13) break;
1147
+ if (code !== 32 && code !== 9) return false;
1148
+ }
1149
+ return true;
1019
1150
  }
1020
1151
  const GFM_TEXT_NATIVE_TRIGGER = /[\\*_~`[<\r\n]/;
1021
- function mayNeedGfmTextEscape(value, buffer, depthMap) {
1152
+ function lineStartDigits(buffer, indent, value) {
1153
+ let lead = 0;
1154
+ while (value.charCodeAt(lead) >= 48 && value.charCodeAt(lead) <= 57) lead++;
1155
+ let one = lead === 0 || value.charCodeAt(lead - 1) === 49;
1156
+ for (let index = 0; one && index < lead - 1; index++) one = value.charCodeAt(index) === 48;
1157
+ let fragment = buffer.length - 1;
1158
+ let offset = fragment >= 0 ? buffer[fragment].length : 0;
1159
+ let digits = 0;
1160
+ let spaces = 0;
1161
+ let newline = false;
1162
+ for (;;) {
1163
+ while (offset === 0 && fragment >= 0) {
1164
+ fragment--;
1165
+ offset = fragment >= 0 ? buffer[fragment].length : 0;
1166
+ }
1167
+ const code = fragment >= 0 ? buffer[fragment].charCodeAt(--offset) : -1;
1168
+ if (newline) return code === -1 || code === 10 || code === 32 || code === 9 || code === 92 ? digits : 0;
1169
+ if (spaces === 0 && code >= 48 && code <= 57) {
1170
+ if (++digits > 9) return 0;
1171
+ one &&= code === (digits === 1 && lead === 0 ? 49 : 48);
1172
+ continue;
1173
+ }
1174
+ if (digits === 0) return 0;
1175
+ if (code === 32) {
1176
+ if (++spaces > indent.length + 3) return 0;
1177
+ continue;
1178
+ }
1179
+ if (code === -1 || code === 10) {
1180
+ if (spaces > 3 && spaces < indent.length) return 0;
1181
+ if (code === -1 || one) return digits;
1182
+ newline = true;
1183
+ continue;
1184
+ }
1185
+ return spaces > 0 && spaces <= 3 && listMarkerLineStart(buffer, fragment, offset) ? digits : 0;
1186
+ }
1187
+ }
1188
+ function mayNeedGfmTextEscape(value, buffer, depthMap, structuralIndent) {
1022
1189
  if (value.search(GFM_TEXT_NATIVE_TRIGGER) !== -1) return true;
1023
1190
  if (depthMap[28] && value.includes("|") || depthMap[26] && value.includes("]") || depthMap[22] && value.includes(">")) return true;
1024
1191
  const first = value.charCodeAt(0);
1025
- if (!" #+->".includes(value[0]) && !(first >= 48 && first <= 57)) return false;
1026
- let lineIndent = markdownLineIndent(buffer);
1192
+ if (!" #+->=".includes(value[0]) && !(first >= 48 && first <= 57)) return false;
1193
+ let lineIndent = markdownLineIndent(buffer, structuralIndent);
1027
1194
  if (lineIndent < 0) return false;
1028
1195
  let index = 0;
1029
1196
  while (index < value.length && lineIndent < 3 && value.charCodeAt(index) === 32) {
@@ -1032,14 +1199,13 @@ function mayNeedGfmTextEscape(value, buffer, depthMap) {
1032
1199
  }
1033
1200
  if (index >= value.length) return false;
1034
1201
  const code = value.charCodeAt(index);
1035
- return "#+->".includes(value[index]) || code >= 48 && code <= 57;
1202
+ return "#+->=".includes(value[index]) || code >= 48 && code <= 57;
1036
1203
  }
1037
- function escapeGfmText(value, buffer, depthMap) {
1204
+ function escapeGfmText(value, buffer, depthMap, structuralIndent, orderedDigits = 0) {
1038
1205
  const inTable = Boolean(depthMap[28]);
1039
1206
  const inLink = Boolean(depthMap[26]);
1040
1207
  const inBlockquote = Boolean(depthMap[22]);
1041
- let lineIndent = markdownLineIndent(buffer);
1042
- let orderedDigits = 0;
1208
+ let lineIndent = markdownLineIndent(buffer, structuralIndent);
1043
1209
  let copiedUntil = 0;
1044
1210
  let escaped = "";
1045
1211
  for (let index = 0; index < value.length; index++) {
@@ -1058,14 +1224,20 @@ function escapeGfmText(value, buffer, depthMap) {
1058
1224
  copiedUntil = index + 1;
1059
1225
  continue;
1060
1226
  }
1227
+ if (code === 13) {
1228
+ lineIndent = 0;
1229
+ orderedDigits = 0;
1230
+ continue;
1231
+ }
1061
1232
  let shouldEscape = "\\*_~`[".includes(character) || code === 93 && inLink || code === 124 && inTable || code === 62 && inBlockquote || code === 60 && canStartGfmAngleConstruct(value.charCodeAt(index + 1));
1062
1233
  if (!shouldEscape && lineIndent >= 0) {
1063
1234
  if (code === 35) {
1064
1235
  let end = index + 1;
1065
1236
  while (end < value.length && value.charCodeAt(end) === 35) end++;
1066
1237
  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);
1238
+ } else if (code === 45 || code === 43) shouldEscape = index + 1 === value.length || isMarkdownMarkerWhitespace(value.charCodeAt(index + 1)) || code === 45 && isDashLine(value, index);
1068
1239
  else if (code === 62) shouldEscape = true;
1240
+ else if (code === 61) shouldEscape = isEqualsLine(value, index);
1069
1241
  } else if (!shouldEscape && orderedDigits > 0 && (code === 46 || code === 41)) shouldEscape = index + 1 === value.length || isMarkdownMarkerWhitespace(value.charCodeAt(index + 1));
1070
1242
  if (shouldEscape) {
1071
1243
  escaped += value.slice(copiedUntil, index);
@@ -1088,23 +1260,25 @@ function escapeGfmText(value, buffer, depthMap) {
1088
1260
  }
1089
1261
  return copiedUntil === 0 ? value : escaped + value.slice(copiedUntil);
1090
1262
  }
1091
- function currentColumn(buffer) {
1263
+ function currentColumn(buffer, limit) {
1092
1264
  let col = 0;
1093
1265
  for (let i = buffer.length - 1; i >= 0; i--) {
1094
1266
  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);
1267
+ for (let j = s.length - 1; j >= 0; j--) {
1268
+ const code = s.charCodeAt(j);
1269
+ if (code === 10) return col;
1270
+ if (takesColumn(code) && ++col >= limit) return col;
1271
+ }
1098
1272
  }
1099
1273
  return col;
1100
1274
  }
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;
1275
+ function takesColumn(code) {
1276
+ return (code & 64512) !== 56320 && code !== 64976 && code !== 64977;
1277
+ }
1278
+ const BLOCK_START_WORD = /^(?:>|`{3}|~{3}|(?:#{1,6}|\+|-+|=+|\*|\*{3,}|_{3,}|0{0,8}1[.)])$)/;
1279
+ function isSetextMarkerRun(word) {
1280
+ const first = word.charCodeAt(0);
1281
+ return first === 45 ? isDashLine(word, 0) : first === 61 && isEqualsLine(word, 0);
1108
1282
  }
1109
1283
  function wrapText(value, col, width, prefix) {
1110
1284
  const leading = value.charCodeAt(0) === 32;
@@ -1121,7 +1295,7 @@ function wrapText(value, col, width, prefix) {
1121
1295
  const word = value.slice(i, next);
1122
1296
  const wordLen = [...word].length;
1123
1297
  const needSpace = first ? leading : true;
1124
- if (needSpace && col > prefixLen && col + 1 + wordLen > width) {
1298
+ if (needSpace && col > prefixLen && col + 1 + wordLen > width && !isSetextMarkerRun(word) && !BLOCK_START_WORD.test(word)) {
1125
1299
  out += `\n${prefix}`;
1126
1300
  col = prefixLen;
1127
1301
  } else if (needSpace) {
@@ -1142,6 +1316,14 @@ function calculateNewLineConfig(node, state, eventType) {
1142
1316
  const depthMap = state.depthMap;
1143
1317
  const tagId = node.tagId;
1144
1318
  if (tagId !== 25 && (depthMap[25] || 0) > 0) return NO_SPACING;
1319
+ 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;
1320
+ if (collapsedByAncestor(node, state, eventType)) return NO_SPACING;
1321
+ if (node.tagHandler?.spacing) return node.tagHandler?.spacing;
1322
+ if (tagId === -1) return NO_SPACING;
1323
+ return DEFAULT_BLOCK_SPACING;
1324
+ }
1325
+ function collapsedByAncestor(node, state, eventType) {
1326
+ const tagId = node.tagId;
1145
1327
  const isBlockElement = tagId !== void 0 && (tagId >= 7 && tagId <= 12 || tagId === 35 || tagId === 36 || tagId === 25 || tagId === 106);
1146
1328
  let currParent = node.parent;
1147
1329
  while (currParent) {
@@ -1154,13 +1336,25 @@ function calculateNewLineConfig(node, state, eventType) {
1154
1336
  currParent = currParent.parent;
1155
1337
  continue;
1156
1338
  }
1157
- return NO_SPACING;
1339
+ return true;
1158
1340
  }
1159
1341
  currParent = currParent.parent;
1160
1342
  }
1161
- if (node.tagHandler?.spacing) return node.tagHandler?.spacing;
1162
- if (tagId === -1) return NO_SPACING;
1163
- return DEFAULT_BLOCK_SPACING;
1343
+ return false;
1344
+ }
1345
+ function headingKeptInlineInItem(heading) {
1346
+ let parent = heading.parent;
1347
+ while (parent) {
1348
+ if (parent.tagId !== 37 && parent.tagHandler?.collapsesInnerWhiteSpace && wrapperWritesDelimiters(parent)) return true;
1349
+ parent = parent.parent;
1350
+ }
1351
+ return false;
1352
+ }
1353
+ function wrapperWritesDelimiters(node) {
1354
+ const handler = node.tagHandler;
1355
+ if (handler?.literalEnter && node.hasEnterOutput || handler?.literalExit && handler.literalExitHasOutput) return true;
1356
+ if (handler?.literalEnter && handler.literalExit && !node.hasEnterOutput && !handler.literalExitHasOutput) return false;
1357
+ return Boolean(INLINE_MARKER_TYPE[node.tagId]);
1164
1358
  }
1165
1359
  function wrapperEmitsInlineMarkdown(node, state) {
1166
1360
  const handler = node.tagHandler;
@@ -1168,15 +1362,21 @@ function wrapperEmitsInlineMarkdown(node, state) {
1168
1362
  const tagId = node.tagId;
1169
1363
  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
1364
  }
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;
1365
+ function trimLeadingSpaces(value) {
1366
+ let start = 0;
1367
+ while (value.charCodeAt(start) === 32) start++;
1368
+ return start === 0 ? value : value.slice(start);
1369
+ }
1370
+ function insideOpenInlineDelimiter(node, state) {
1371
+ const rawHtml = isInsideRawHtmlBlock(state.depthMap);
1372
+ for (let parent = node.parent; parent; parent = parent.parent) {
1373
+ const tagId = parent.tagId;
1374
+ if (parent.tagHandler?.collapsesInnerWhiteSpace && tagId !== 21 && tagId !== 19 && tagId !== 20 && tagId !== 80 && tagId !== 89 && !(rawHtml && tagId === 26) && wrapperEmitsInlineMarkdown(parent, state)) return true;
1175
1375
  }
1176
1376
  return false;
1177
1377
  }
1178
1378
  function isAsciiWhitespace(code) {
1179
- return code === 32 || code >= 9 && code <= 13;
1379
+ return code === 32 || code === 9 || code === 10 || code === 12 || code === 13;
1180
1380
  }
1181
1381
  function trimAsciiWhitespaceEnd(value) {
1182
1382
  let end = value.length;
@@ -1188,6 +1388,23 @@ function dropEmptyMarker(buffer, packed, markerType, positions) {
1188
1388
  if ((packed & MARKER_TYPE_MASK) === markerType && idx < buffer.length) return dropEmptyLinkText(buffer, idx, positions) ? idx : -1;
1189
1389
  return -1;
1190
1390
  }
1391
+ function isVerticalTabRun(value) {
1392
+ for (let i = 0; i < value.length; i++) {
1393
+ const c = value.charCodeAt(i);
1394
+ if (c !== 11 && !isAsciiWhitespace(c)) return false;
1395
+ }
1396
+ return true;
1397
+ }
1398
+ function dropVerticalTabMarker(buffer, packed, markerType, marker, positions) {
1399
+ const idx = packed >> 3;
1400
+ const opener = buffer[idx];
1401
+ if ((packed & MARKER_TYPE_MASK) !== markerType || opener === void 0 || !opener.endsWith(marker)) return false;
1402
+ for (let index = idx + 1; index < buffer.length; index++) if (!isVerticalTabRun(buffer[index])) return false;
1403
+ const kept = opener.slice(0, opener.length - marker.length);
1404
+ positions?.replace(idx, idx + 1, [kept]);
1405
+ buffer[idx] = kept;
1406
+ return true;
1407
+ }
1191
1408
  function resetRetractedCaptionFrames(frames, count, fragment) {
1192
1409
  if (!frames) return;
1193
1410
  for (let index = 0; index < count; index++) {
@@ -1235,9 +1452,10 @@ function maxLineLeadingRun(value, marker, indent) {
1235
1452
  let run = 0;
1236
1453
  while (value.charCodeAt(index + run) === marker) run++;
1237
1454
  if (run > max) max = run;
1238
- const newline = value.indexOf("\n", lineStart);
1239
- if (newline === -1) break;
1240
- lineStart = newline + 1;
1455
+ let lineEnd = index + run;
1456
+ while (lineEnd < value.length && value.charCodeAt(lineEnd) !== 10 && value.charCodeAt(lineEnd) !== 13) lineEnd++;
1457
+ if (lineEnd >= value.length) break;
1458
+ lineStart = lineEnd + 1;
1241
1459
  }
1242
1460
  return max;
1243
1461
  }
@@ -1253,18 +1471,38 @@ function finalizeCodeSpan(state, span) {
1253
1471
  });
1254
1472
  state.buffer.length = span.fragment + 1;
1255
1473
  state.buffer.push(content);
1474
+ noteBufferRewrite(state);
1256
1475
  }
1257
1476
  const delimiter = "`".repeat(Math.max(1, maxBacktickRun(content) + 1));
1258
1477
  const padded = content.startsWith("`") || content.endsWith("`");
1259
1478
  const opening = `${span.prefix}${delimiter}${padded ? " " : ""}`;
1260
1479
  if (state.outputPositions && opening !== state.buffer[span.fragment]) state.outputPositions?.replace(span.fragment, span.fragment + 1, [opening]);
1261
1480
  state.buffer[span.fragment] = opening;
1481
+ noteBufferRewrite(state);
1262
1482
  return `${padded ? " " : ""}${delimiter}`;
1263
1483
  }
1484
+ function hasLiteralTagOverride(overrides) {
1485
+ for (const name in overrides) {
1486
+ const override = overrides[name];
1487
+ if (override && typeof override === "object" && (override.enter !== void 0 || override.exit !== void 0)) return true;
1488
+ }
1489
+ return false;
1490
+ }
1491
+ function notePluginFences(state, output) {
1492
+ if (!state.fencesUnreliable && !state.codeFence && output?.some((part) => part.includes("`") || part.includes("~"))) state.fencesUnreliable = true;
1493
+ }
1494
+ function noteGeneratedFences(state, delimiters) {
1495
+ if (!state.fencesUnreliable && !state.codeFence && (mayOpenFence(delimiters.prefix) || mayOpenFence(delimiters.suffix))) state.fencesUnreliable = true;
1496
+ }
1497
+ function mayOpenFence(delimiter) {
1498
+ return delimiter.includes("`") || delimiter.includes("~~~");
1499
+ }
1264
1500
  function startCodeFence(state, fragment, language, indent) {
1501
+ const markerOffset = state.buffer[fragment].lastIndexOf("```");
1502
+ if (!state.fencesUnreliable && (state.preFenceInline || !opensBlockLine(state.buffer, fragment, markerOffset))) state.fencesUnreliable = true;
1265
1503
  state.codeFence = {
1266
1504
  fragment,
1267
- markerOffset: state.buffer[fragment].lastIndexOf("```"),
1505
+ markerOffset,
1268
1506
  indent,
1269
1507
  language
1270
1508
  };
@@ -1274,14 +1512,17 @@ function finalizeCodeFence(state) {
1274
1512
  const fence = state.codeFence;
1275
1513
  if (!fence) return;
1276
1514
  state.codeFence = void 0;
1515
+ state.preFenceOpener = void 0;
1277
1516
  const marker = fence.language.includes("`") ? "~" : "`";
1278
1517
  const markerCode = marker.charCodeAt(0);
1279
1518
  const content = state.buffer.slice(fence.fragment + 1).join("");
1280
1519
  const delimiter = marker.repeat(Math.max(3, maxLineLeadingRun(content, markerCode, fence.indent) + 1));
1281
- const opening = state.buffer[fence.fragment];
1520
+ let opening = state.buffer[fence.fragment];
1521
+ if (content === "" && fence.indent && opening.endsWith(fence.indent)) opening = opening.slice(0, -fence.indent.length);
1282
1522
  const replacement = `${opening.slice(0, fence.markerOffset)}${delimiter}${opening.slice(fence.markerOffset + 3)}`;
1283
1523
  if (state.outputPositions && replacement !== opening) state.outputPositions?.replace(fence.fragment, fence.fragment + 1, [replacement], (offset) => offset <= fence.markerOffset ? offset : offset + delimiter.length - 3);
1284
1524
  state.buffer[fence.fragment] = replacement;
1525
+ noteBufferRewrite(state);
1285
1526
  return delimiter;
1286
1527
  }
1287
1528
  function stripBlockquoteListIndent(line, listIndent) {
@@ -1353,11 +1594,13 @@ function finalizeBlockquote(state) {
1353
1594
  buffer.push(quoted.slice(start, end));
1354
1595
  if (end < quoted.length) buffer.push(quoted.slice(end));
1355
1596
  state.lastContentCache = buffer.at(-1);
1597
+ noteBufferRewrite(state);
1356
1598
  return;
1357
1599
  }
1358
1600
  state.outputPositions?.replace(frame.fragment, buffer.length, [quoted], mapPosition);
1359
1601
  buffer.splice(frame.fragment, buffer.length - frame.fragment, quoted);
1360
1602
  state.lastContentCache = quoted;
1603
+ noteBufferRewrite(state);
1361
1604
  }
1362
1605
  function collapseNestedBlockquoteSeparator(buffer, positions) {
1363
1606
  if (newlineRunBefore(buffer, buffer.length) < 2) return;
@@ -1368,9 +1611,10 @@ function collapseNestedBlockquoteSeparator(buffer, positions) {
1368
1611
  }
1369
1612
  function flushPreFence(state) {
1370
1613
  state.preFencePending = false;
1614
+ state.headingBreakPending = false;
1371
1615
  state.preFenceOwnerDepth = state.preFencePendingDepth;
1372
1616
  const lang = state.preFenceLang || "";
1373
- const fence = (state.depthMap[25] || 0) > 0 ? `${blockOpenPrefix(state.buffer, state.listIndent) ?? ""}\`\`\`${lang}\n${state.listIndent}` : `\`\`\`${lang}\n`;
1617
+ const fence = (state.depthMap[25] || 0) > 0 ? `${blockOpenPrefix(state, state.listIndent) ?? ""}\`\`\`${lang}\n${state.listIndent}` : `\`\`\`${lang}\n`;
1374
1618
  state.buffer.push(fence);
1375
1619
  startCodeFence(state, state.buffer.length - 1, lang, state.listIndent);
1376
1620
  state.lastContentCache = fence;
@@ -1386,6 +1630,7 @@ function consumePendingPreChild(state, node, eventType, beforeFlush) {
1386
1630
  else if (element.tagId !== 34 && element.tagId !== 106 && !suppressesFormattingInPre(element.tagId)) {
1387
1631
  beforeFlush();
1388
1632
  flushPreFence(state);
1633
+ state.preFenceOpener = element;
1389
1634
  }
1390
1635
  return false;
1391
1636
  }
@@ -1411,9 +1656,13 @@ function consumeGfmAction(action, state, lifecycle) {
1411
1656
  return;
1412
1657
  case "PreExit": {
1413
1658
  const depth = state.depthMap[34] + 1;
1414
- if (state.preFencePendingDepth === depth) state.preFencePending = false;
1659
+ if (state.preFencePendingDepth === depth) {
1660
+ state.preFencePending = false;
1661
+ state.preFenceLang = "";
1662
+ }
1415
1663
  if (state.preFenceOwnerDepth !== depth) return void 0;
1416
1664
  state.preFenceOwnerDepth = 0;
1665
+ state.preFenceLang = "";
1417
1666
  state.lastTextNode = void 0;
1418
1667
  const indent = state.listIndent;
1419
1668
  const output = (state.depthMap[25] || 0) > 0 ? `\n${indent}\`\`\`\n\n${indent}` : `\n\`\`\``;
@@ -1431,14 +1680,18 @@ function consumeGfmAction(action, state, lifecycle) {
1431
1680
  return action.output;
1432
1681
  }
1433
1682
  }
1434
- function commitGfmAction(action, state, lifecycle, outputStart, owner) {
1683
+ function commitGfmAction(action, state, lifecycle, outputStart, owner, keepsQuoteSeparator, rawHtmlQuoteBoundary = false) {
1435
1684
  switch (action._tag) {
1436
1685
  case "BlockquoteEnter": {
1437
- if (state.blockquotes.length > 0) collapseNestedBlockquoteSeparator(state.buffer, state.outputPositions);
1686
+ if (state.blockquotes.length > 0 && !keepsQuoteSeparator && (!rawHtmlQuoteBoundary || newlineRunBefore(state.buffer, state.buffer.length) > 2)) {
1687
+ collapseNestedBlockquoteSeparator(state.buffer, state.outputPositions);
1688
+ for (const frame of state.blockquotes) frame.fragment = Math.min(frame.fragment, state.buffer.length);
1689
+ noteBufferRewrite(state);
1690
+ }
1438
1691
  const before = lastOutputChar(state.buffer);
1439
1692
  state.blockquotes.push({
1440
1693
  fragment: state.buffer.length,
1441
- listIndent: state.listIndent,
1694
+ listIndent: isInsideTableCell(state) ? "" : state.listIndent,
1442
1695
  followsWhitespace: before === -1 ? state.lastContentCache !== void 0 && isAsciiWhitespace(state.lastContentCache.charCodeAt(state.lastContentCache.length - 1)) : isAsciiWhitespace(before)
1443
1696
  });
1444
1697
  state.bufferedBlockquoteDepth = state.blockquotes.length;
@@ -1452,7 +1705,12 @@ function commitGfmAction(action, state, lifecycle, outputStart, owner) {
1452
1705
  });
1453
1706
  break;
1454
1707
  case "CodeFenceEnter": {
1455
- const fenceFragment = state.buffer.findIndex((fragment, index) => index >= outputStart && fragment.includes("```"));
1708
+ const buffer = state.buffer;
1709
+ let fenceFragment = -1;
1710
+ for (let index = outputStart; index < buffer.length; index++) if (buffer[index].includes("```")) {
1711
+ fenceFragment = index;
1712
+ break;
1713
+ }
1456
1714
  if (fenceFragment < 0) throw new Error("code fence opener missing from output");
1457
1715
  startCodeFence(state, fenceFragment, action.language, state.listIndent);
1458
1716
  break;
@@ -1472,13 +1730,17 @@ function createMarkdownProcessor(options = {}, createStream) {
1472
1730
  blockquotes: [],
1473
1731
  bufferedBlockquoteDepth: 0,
1474
1732
  emptyItemFragment: void 0,
1733
+ headingBreakPending: false,
1734
+ emptyItemAfterCr: false,
1475
1735
  tableRenderedTable: false,
1476
1736
  tableCurrentRowCells: 0,
1477
1737
  tableColumnAlignments: [],
1478
1738
  tableHeaderCells: 0,
1479
1739
  preFencePending: false,
1480
1740
  preFencePendingDepth: 0,
1481
- preFenceOwnerDepth: 0
1741
+ preFenceOwnerDepth: 0,
1742
+ fencesUnreliable: hasLiteralTagOverride(options.tagOverrides),
1743
+ preFenceOpener: void 0
1482
1744
  };
1483
1745
  const bufferScan = [
1484
1746
  false,
@@ -1490,15 +1752,24 @@ function createMarkdownProcessor(options = {}, createStream) {
1490
1752
  0
1491
1753
  ];
1492
1754
  let inRawHtmlRegion = false;
1755
+ let rawHtmlNeedsBoundary = false;
1756
+ let pendingRawHtmlBoundary = false;
1493
1757
  const openMarkers = [];
1494
1758
  let openMarkerCount = 0;
1495
1759
  let captionFrames;
1496
1760
  let captionFrameCount = 0;
1497
1761
  let captionBoundary = 0;
1762
+ let quoteTentativeSpacing;
1498
1763
  let captionBoundarySpacing = 0;
1499
1764
  let captionBreakRun = 0;
1765
+ let captionLineEnd = 0;
1766
+ let captionLineTail = "";
1767
+ let captionLineFragment = -1;
1768
+ let captionLineHead = "";
1769
+ let captionLineOpens = false;
1500
1770
  const gfmLifecycle = { openCodeSpans: [] };
1501
1771
  let openLinkFragment = -1;
1772
+ let openLinkHeadingBreak = false;
1502
1773
  let openLinkCaptionBreakRun = 0;
1503
1774
  let openLinkCaptionFlags;
1504
1775
  const clean = options.clean;
@@ -1510,7 +1781,8 @@ function createMarkdownProcessor(options = {}, createStream) {
1510
1781
  function captionNeedsPreparation() {
1511
1782
  return captionBoundary !== 0 || captionFrameCount !== 0 && (captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 2] & CAPTION_OPEN) === 0;
1512
1783
  }
1513
- function openLink(fragment) {
1784
+ function openLink(fragment, headingBreak) {
1785
+ openLinkHeadingBreak = headingBreak;
1514
1786
  if (!cleanEmptyLinkText) {
1515
1787
  openLinkFragment = -fragment - 2;
1516
1788
  return;
@@ -1546,7 +1818,7 @@ function createMarkdownProcessor(options = {}, createStream) {
1546
1818
  if (spacing === 0) return "";
1547
1819
  if (spacing === CAPTION_DEFAULT_SPACING) spacing = DEFAULT_BLOCK_SPACING[0];
1548
1820
  const indent = includeListIndent ? state.listIndent : "";
1549
- const blockPrefix = blockOpenPrefix(state.buffer, indent, beforeFragment);
1821
+ const blockPrefix = blockOpenPrefix(state, indent, beforeFragment);
1550
1822
  const trailingNewLines = newlineRunBeforePrefix(state.buffer, beforeFragment, indent);
1551
1823
  if (blockPrefix === void 0 && trailingNewLines === 0) return "";
1552
1824
  const missingNewLines = Math.max(0, spacing - trailingNewLines);
@@ -1554,12 +1826,13 @@ function createMarkdownProcessor(options = {}, createStream) {
1554
1826
  if (!prefix) return "";
1555
1827
  const lastIndex = beforeFragment - 1;
1556
1828
  const last = state.buffer[lastIndex];
1557
- if (prefix.charCodeAt(0) === 10 && last?.endsWith(" ")) {
1829
+ if (captionBoundary !== 3 && captionBoundary !== 4 && prefix.charCodeAt(0) === 10 && last?.endsWith(" ")) {
1558
1830
  const trimmed = last.slice(0, -1);
1559
1831
  state.outputPositions?.replace(lastIndex, lastIndex + 1, [trimmed]);
1560
1832
  state.buffer[lastIndex] = trimmed;
1561
1833
  if (state.lastContentCache === last) state.lastContentCache = trimmed;
1562
1834
  state.lastTextNode = void 0;
1835
+ noteBufferRewrite(state);
1563
1836
  }
1564
1837
  return prefix;
1565
1838
  }
@@ -1571,9 +1844,21 @@ function createMarkdownProcessor(options = {}, createStream) {
1571
1844
  state.pendingInlineWhitespace = false;
1572
1845
  return true;
1573
1846
  }
1847
+ function restoreQuoteParentBoundary() {
1848
+ if (captionBoundary === 4 && quoteTentativeSpacing && state.buffer.at(-1) === quoteTentativeSpacing) {
1849
+ const index = state.buffer.length - 1;
1850
+ state.outputPositions?.replace(index, index + 1, []);
1851
+ state.buffer.pop();
1852
+ state.lastContentCache = state.buffer.at(-1);
1853
+ state.lastTextNode = void 0;
1854
+ noteBufferRewrite(state);
1855
+ captionBoundary = 3;
1856
+ quoteTentativeSpacing = void 0;
1857
+ }
1858
+ }
1574
1859
  function prepareCaptionOutput(explicitTop, includeBoundaryListIndent = true) {
1575
1860
  let changed = false;
1576
- if (captionBoundary === 1) changed = appendCaptionSpacing(captionBoundarySpacing, includeBoundaryListIndent);
1861
+ if (captionBoundary === 1 || captionBoundary === 3) changed = appendCaptionSpacing(captionBoundarySpacing, includeBoundaryListIndent);
1577
1862
  const frames = captionFrames;
1578
1863
  if (frames) for (let index = 0; index < captionFrameCount; index++) {
1579
1864
  const offset = index * CAPTION_FRAME_SIZE;
@@ -1593,6 +1878,7 @@ function createMarkdownProcessor(options = {}, createStream) {
1593
1878
  const replacement = opening + anchored;
1594
1879
  state.outputPositions?.replace(beforeFragment, beforeFragment + 1, [replacement], (offset) => offset + opening.length);
1595
1880
  state.buffer[beforeFragment] = replacement;
1881
+ noteBufferRewrite(state);
1596
1882
  const codeSpan = gfmLifecycle.openCodeSpans.at(-1);
1597
1883
  if (codeSpan?.fragment === beforeFragment) codeSpan.prefix = opening + codeSpan.prefix;
1598
1884
  if (state.lastContentCache === anchored) state.lastContentCache = replacement;
@@ -1621,7 +1907,11 @@ function createMarkdownProcessor(options = {}, createStream) {
1621
1907
  }
1622
1908
  }
1623
1909
  function consumeCaptionTransition(isInlineElement, tagId) {
1624
- captionBoundary = isInlineElement && tagId !== 27 && tagId !== 6 ? 2 : 0;
1910
+ if (!isInlineElement || tagId === 27 || tagId === 6) captionBoundary = 0;
1911
+ else if (captionBoundary === 3) {
1912
+ captionBoundary = 4;
1913
+ quoteTentativeSpacing = void 0;
1914
+ } else if (captionBoundary < 4) captionBoundary = 2;
1625
1915
  }
1626
1916
  function anchorPendingCaptions(fragment) {
1627
1917
  const frames = captionFrames;
@@ -1651,10 +1941,12 @@ function createMarkdownProcessor(options = {}, createStream) {
1651
1941
  state.outputPositions?.replace(index, state.buffer.length, [value.slice(0, end)]);
1652
1942
  state.buffer[index] = value.slice(0, end);
1653
1943
  state.buffer.length = index + 1;
1944
+ noteBufferRewrite(state);
1654
1945
  break;
1655
1946
  }
1656
1947
  state.outputPositions?.replace(index, state.buffer.length, []);
1657
1948
  state.buffer.length = index;
1949
+ noteBufferRewrite(state);
1658
1950
  }
1659
1951
  const output = ` \n${state.listIndent}`.repeat(captionBreakRun);
1660
1952
  captionBreakRun = 0;
@@ -1679,15 +1971,85 @@ function createMarkdownProcessor(options = {}, createStream) {
1679
1971
  state.buffer.length = anchor;
1680
1972
  state.lastContentCache = state.buffer.at(-1);
1681
1973
  state.lastTextNode = void 0;
1682
- } else if (captionBreakRun !== 0 && captionFrameCount === 0) captionBoundary = 2;
1974
+ noteBufferRewrite(state);
1975
+ restoreQuoteParentBoundary();
1976
+ } else if (captionBreakRun !== 0 && captionFrameCount === 0 && captionBoundary < 3) captionBoundary = 2;
1977
+ }
1978
+ function captionExitOpensBlockLine(buff) {
1979
+ let fragment = buff.length - 1;
1980
+ let cursor = buff[fragment].length;
1981
+ let runFragment = -1;
1982
+ let runCursor = 0;
1983
+ for (;;) {
1984
+ if (fragment === captionLineEnd - 1 && cursor === buff[fragment].length && captionLineFragment >= 0 && buff[fragment] === captionLineTail && buff[captionLineFragment] === captionLineHead) {
1985
+ captionLineEnd = buff.length;
1986
+ captionLineTail = buff[captionLineEnd - 1];
1987
+ return captionLineOpens;
1988
+ }
1989
+ if (cursor === 0) {
1990
+ if (fragment === 0) break;
1991
+ cursor = buff[--fragment].length;
1992
+ continue;
1993
+ }
1994
+ if (buff[fragment].charCodeAt(cursor - 1) !== 32) break;
1995
+ runFragment = fragment;
1996
+ runCursor = --cursor;
1997
+ }
1998
+ captionLineEnd = buff.length;
1999
+ captionLineTail = buff[captionLineEnd - 1];
2000
+ captionLineFragment = runFragment;
2001
+ captionLineHead = runFragment < 0 ? "" : buff[runFragment];
2002
+ captionLineOpens = runFragment < 0 ? opensBlockLine(buff, buff.length - 1, buff.at(-1).length) : opensBlockLine(buff, runFragment, runCursor + 1);
2003
+ return captionLineOpens;
2004
+ }
2005
+ function finishRawHtmlBlock(value, generated = false) {
2006
+ if (!pendingRawHtmlBoundary || isInsideRawHtmlBlock(state.depthMap) || !hasNonWhitespace(value)) return;
2007
+ pendingRawHtmlBoundary = false;
2008
+ let leadingNewlines = 0;
2009
+ if (generated) for (let i = 0; i < value.length; i++) {
2010
+ const code = value.charCodeAt(i);
2011
+ if (code === 10) leadingNewlines++;
2012
+ else if (code !== 32 && code !== 9 && code !== 13) break;
2013
+ }
2014
+ let newlines = leadingNewlines;
2015
+ let scanning = true;
2016
+ for (let i = state.buffer.length - 1; i >= 0 && scanning; i--) {
2017
+ const fragment = state.buffer[i];
2018
+ for (let j = fragment.length - 1; j >= 0; j--) {
2019
+ const code = fragment.charCodeAt(j);
2020
+ if (code === 10) {
2021
+ if (++newlines === 2) return;
2022
+ } else if (code !== 32 && code !== 9 && code !== 13) {
2023
+ scanning = false;
2024
+ break;
2025
+ }
2026
+ }
2027
+ }
2028
+ const separator = "\n".repeat(Math.max(0, 2 - newlines)) + (leadingNewlines ? "" : state.listIndent);
2029
+ state.buffer.push(separator);
2030
+ state.lastContentCache = separator;
2031
+ state.lastTextNode = void 0;
1683
2032
  }
1684
2033
  function processTextNode(textNode, lastNode, lastChar) {
2034
+ if (pendingRawHtmlBoundary) {
2035
+ finishRawHtmlBlock(textNode.value);
2036
+ if (!pendingRawHtmlBoundary) {
2037
+ const value = textNode.value;
2038
+ let start = 0;
2039
+ while (start < value.length) {
2040
+ const code = value.charCodeAt(start);
2041
+ if (code !== 32 && code !== 9 && code !== 10 && code !== 13) break;
2042
+ start++;
2043
+ }
2044
+ if (start !== 0) textNode.value = value.slice(start);
2045
+ }
2046
+ }
1685
2047
  if (textNode.trimsAtLineStart) trimTextAtLineStart(textNode, state.buffer);
1686
2048
  if (textNode.value) {
1687
2049
  if (textNode.excludedFromMarkdown) return;
1688
2050
  const ownsCaptionSpace = captionNeedsPreparation();
1689
2051
  if (ownsCaptionSpace) {
1690
- if (textNode.value.charCodeAt(0) === 32) textNode.value = textNode.value.slice(1);
2052
+ if (captionBoundary !== 5 && textNode.value.charCodeAt(0) === 32) textNode.value = textNode.value.slice(1);
1691
2053
  if (!hasNonWhitespace(textNode.value)) return;
1692
2054
  flushCaptionBreakRun();
1693
2055
  prepareCaptionOutput(false);
@@ -1716,11 +2078,18 @@ function createMarkdownProcessor(options = {}, createStream) {
1716
2078
  while (parent && parent !== rawHtmlLink) parent = parent.parent;
1717
2079
  textNode.value = escapeRawHtmlText(textNode.value, state.depthMap, rawHtmlLink !== void 0 && parent === rawHtmlLink);
1718
2080
  }
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}`;
2081
+ const last = lastChar.charCodeAt(0);
2082
+ const first = last >= 48 && last <= 57 ? textNode.value.charCodeAt(0) : 0;
2083
+ const orderedDigits = (first >= 48 && first <= 57 || first === 46 || first === 41) && !textNode.generatedMarkdown?.prefix ? lineStartDigits(state.buffer, state.listIndent, textNode.value) : 0;
2084
+ if (!state.depthMap[34] && !state.depthMap[23] && (!insideRawHtmlBlock || rawHtmlMarkdown) && (orderedDigits > 0 || 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);
2085
+ if (textNode.generatedMarkdown && textNode.value) {
2086
+ noteGeneratedFences(state, textNode.generatedMarkdown);
2087
+ textNode.value = `${textNode.generatedMarkdown.prefix}${textNode.value}${textNode.generatedMarkdown.suffix}`;
2088
+ }
1721
2089
  const wrapWidth = state.options?.wrapWidth;
1722
2090
  if (wrapWidth && canWrapHere(state.depthMap)) {
1723
- const wrapped = wrapText(textNode.value, currentColumn(state.buffer), wrapWidth, continuationPrefix(textNode, state.listIndentWidths, state.blockquotes.length === 0));
2091
+ const column = currentColumn(state.buffer, Math.max(wrapWidth, state.listIndent.length + 1));
2092
+ const wrapped = wrapText(textNode.value, column, wrapWidth, state.listIndent);
1724
2093
  state.buffer.push(wrapped);
1725
2094
  state.lastContentCache = wrapped;
1726
2095
  } else {
@@ -1731,15 +2100,35 @@ function createMarkdownProcessor(options = {}, createStream) {
1731
2100
  const hasVisibleText = textNode.containsWhitespace === false || hasNonWhitespace(textNode.value);
1732
2101
  if (openLinkFragment >= 0 && hasVisibleText) openLinkFragment = -openLinkFragment - 2;
1733
2102
  if (openMarkerCount && hasVisibleText) {
1734
- openMarkerCount = 0;
2103
+ const first = textNode.value.charCodeAt(0);
2104
+ if (first !== 11 && !isAsciiWhitespace(first) || (openMarkers[openMarkerCount - 1] & MARKER_TYPE_MASK) > 4 || !isVerticalTabRun(textNode.value)) openMarkerCount = 0;
1735
2105
  commitCaptionFrames();
1736
2106
  }
1737
2107
  }
1738
2108
  }
1739
2109
  state.lastTextNode = textNode;
1740
2110
  }
2111
+ function settleHeadingBreakAtEvent(node, eventType) {
2112
+ if (node.type === 2 && eventType === 0) {
2113
+ const textNode = node;
2114
+ if (textNode.excludedFromMarkdown || !hasNonWhitespace(textNode.value)) return true;
2115
+ const separator = `\n\n${state.listIndent}`;
2116
+ state.buffer.push(separator);
2117
+ state.lastContentCache = separator;
2118
+ state.headingBreakPending = false;
2119
+ if (!state.depthMap[34]) {
2120
+ const value = textNode.value;
2121
+ let start = 0;
2122
+ let code = value.charCodeAt(0);
2123
+ while (code === 32 || code === 9 || code === 10 || code === 12 || code === 13) code = value.charCodeAt(++start);
2124
+ if (start !== 0) textNode.value = value.slice(start);
2125
+ }
2126
+ } else if (node.type === 1 && eventType === 1 && node.tagId === 25) state.headingBreakPending = false;
2127
+ return false;
2128
+ }
1741
2129
  function processEvent(event) {
1742
2130
  const { type: eventType, node } = event;
2131
+ if (pendingRawHtmlBoundary && eventType === 0 && node.type === 1 && node.tagId === 34 && !node.tagHandler?.literalEnter) pendingRawHtmlBoundary = false;
1743
2132
  state.depth = node.depth;
1744
2133
  if (node.type === 1 ? node.excludedFromMarkdown : node.parent?.excludedFromMarkdown) return;
1745
2134
  if (state.tableRowOpenerPending && state.depthMap[28] <= 1) {
@@ -1754,16 +2143,17 @@ function createMarkdownProcessor(options = {}, createStream) {
1754
2143
  }
1755
2144
  }
1756
2145
  if (state.listRulePending !== void 0) {
1757
- const isVisibleText = node.type === 2 && eventType === 0 && hasNonWhitespace(node.value);
2146
+ const isVisibleText = node.type === 2 && eventType === 0 && !node.excludedFromMarkdown && hasNonWhitespace(node.value);
1758
2147
  const opensVisibleElement = node.type === 1 && eventType === 0 && !node.tagHandler?.excludesTextNodes;
1759
2148
  if (isVisibleText || opensVisibleElement) {
1760
- const separator = blockOpenPrefix(state.buffer, state.listRulePending);
2149
+ const separator = `\n\n${state.listRulePending}`;
1761
2150
  state.buffer.push(separator);
1762
2151
  state.lastContentCache = separator;
1763
2152
  state.listRulePending = void 0;
1764
2153
  } else if (node.type === 1 && eventType === 1 && node.tagId === 25) state.listRulePending = void 0;
1765
2154
  else if (node.type === 2) return;
1766
2155
  }
2156
+ if (state.headingBreakPending && settleHeadingBreakAtEvent(node, eventType)) return;
1767
2157
  const lastNode = state.lastNode;
1768
2158
  state.lastNode = event.node;
1769
2159
  const buff = state.buffer;
@@ -1779,10 +2169,14 @@ function createMarkdownProcessor(options = {}, createStream) {
1779
2169
  const pendingElement = node;
1780
2170
  const pendingHandler = pendingElement.tagHandler;
1781
2171
  const literalOverride = eventType === 0 ? pendingHandler?.literalEnter : pendingHandler?.literalExit;
1782
- if (literalOverride && codeOwnsPendingPreFence(state, pendingElement)) state.preFenceLang = getLanguageFromClass(pendingElement.attributes?.class);
2172
+ if (literalOverride && codeOwnsPendingPreFence(state, pendingElement)) {
2173
+ const language = getLanguageFromAttributes(pendingElement.attributes);
2174
+ if (language) state.preFenceLang = language;
2175
+ }
1783
2176
  if (pendingElement.pluginOutput?.length || literalOverride) {
1784
2177
  preparePendingPreFence();
1785
2178
  flushPreFence(state);
2179
+ notePluginFences(state, pendingElement.pluginOutput);
1786
2180
  } else if (consumePendingPreChild(state, node, eventType, preparePendingPreFence)) return;
1787
2181
  } else if (consumePendingPreChild(state, node, eventType, preparePendingPreFence)) return;
1788
2182
  }
@@ -1801,12 +2195,17 @@ function createMarkdownProcessor(options = {}, createStream) {
1801
2195
  const handler = node.tagHandler;
1802
2196
  const tagId = element.tagId;
1803
2197
  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)) {
2198
+ if (captionBoundary >= 3 && tagId === 25) {
2199
+ restoreQuoteParentBoundary();
2200
+ captionBoundary = 0;
2201
+ }
2202
+ if (eventType === 0 && state.depthMap[25] && !insideRawHtmlRegion && (tagId === 35 || tagId === 36 || tagId === 34 || tagId === 28 || tagId === 13 && !state.listIndent) && !handler?.literalEnter && endsAtHardBreak(buff)) {
1805
2203
  trimTrailingSpaces(buff);
1806
2204
  const separator = tagId === 35 || tagId === 36 ? `\n${state.listIndent}` : "\n";
1807
2205
  buff.push(separator);
1808
2206
  state.lastContentCache = separator;
1809
2207
  state.lastTextNode = void 0;
2208
+ state.headingBreakPending = false;
1810
2209
  lastBuffEntry = separator;
1811
2210
  lastChar = separator.charAt(separator.length - 1);
1812
2211
  }
@@ -1817,8 +2216,9 @@ function createMarkdownProcessor(options = {}, createStream) {
1817
2216
  }
1818
2217
  if (eventType === 0 && handler === breakHandler && !element.pluginOutput?.length) {
1819
2218
  const inPre = state.depthMap[34] !== 0;
1820
- let breakOutput = renderBreak(element, state);
2219
+ let breakOutput = renderBreak(state);
1821
2220
  if (captionBoundary !== 0 || captionFrameCount !== 0) {
2221
+ if (captionBoundary === 5) captionBoundary = 4;
1822
2222
  const pendingCaption = captionFrameCount !== 0 && (captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 2] & CAPTION_OPEN) === 0;
1823
2223
  if (!inPre && breakOutput && !hasNonWhitespace(breakOutput) && buff.length === 0 && !hasYieldedContent && state.blockquotes.length === 0 && pendingCaption) breakOutput = void 0;
1824
2224
  if (breakOutput && hasNonWhitespace(breakOutput) && captionNeedsPreparation()) {
@@ -1830,7 +2230,23 @@ function createMarkdownProcessor(options = {}, createStream) {
1830
2230
  lastChar = lastBuffEntry?.charAt(lastBuffEntry.length - 1) || "";
1831
2231
  }
1832
2232
  }
1833
- if (state.pendingInlineWhitespace) state.pendingInlineWhitespace = false;
2233
+ if (state.pendingInlineWhitespace) {
2234
+ state.pendingInlineWhitespace = false;
2235
+ if (breakOutput?.charCodeAt(0) === 60) {
2236
+ const last = lastOutputChar(buff);
2237
+ if (last !== -1 && last !== 32 && last !== 10 && last !== 9 && last !== 13) {
2238
+ buff.push(" ");
2239
+ state.lastContentCache = " ";
2240
+ }
2241
+ }
2242
+ }
2243
+ if (state.headingBreakPending && breakOutput) {
2244
+ if (breakOutput.includes("\n")) state.headingBreakPending = false;
2245
+ else if (hasNonWhitespace(breakOutput)) {
2246
+ state.headingBreakPending = false;
2247
+ breakOutput = `\n\n${state.listIndent}${breakOutput}`;
2248
+ }
2249
+ }
1834
2250
  const lastFragment = state.lastContentCache;
1835
2251
  const lastTextNode = state.lastTextNode;
1836
2252
  if (lastFragment && lastTextNode?.containsWhitespace && typeof lastTextNode.value === "string") {
@@ -1854,6 +2270,7 @@ function createMarkdownProcessor(options = {}, createStream) {
1854
2270
  state.lastTextNode = void 0;
1855
2271
  }
1856
2272
  }
2273
+ if (!inPre && breakOutput?.endsWith("\n") && lastOutputChar(buff) === 32) trimTrailingSpaces(buff);
1857
2274
  const pendingCaption = captionFrameCount !== 0 && (captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 2] & CAPTION_OPEN) === 0;
1858
2275
  if (breakOutput && pendingCaption && !hasNonWhitespace(breakOutput)) {
1859
2276
  for (let index = 0; index < captionFrameCount; index++) {
@@ -1862,6 +2279,7 @@ function createMarkdownProcessor(options = {}, createStream) {
1862
2279
  }
1863
2280
  captionBreakRun++;
1864
2281
  } else if (breakOutput) {
2282
+ if (breakOutput.charCodeAt(0) === 60 && lastOutputChar(buff) === 124) buff.push(" ");
1865
2283
  buff.push(breakOutput);
1866
2284
  state.lastContentCache = breakOutput;
1867
2285
  if (openMarkerCount && hasNonWhitespace(breakOutput)) openMarkerCount = 0;
@@ -1871,21 +2289,31 @@ function createMarkdownProcessor(options = {}, createStream) {
1871
2289
  let output;
1872
2290
  const hasPluginOutput = !!element.pluginOutput?.length;
1873
2291
  if (hasPluginOutput) {
2292
+ notePluginFences(state, element.pluginOutput);
1874
2293
  output = element.pluginOutput;
1875
2294
  element.pluginOutput = void 0;
1876
2295
  }
1877
2296
  let captionBufferChanged = false;
1878
2297
  const eventFn = eventType === 0 ? "enter" : "exit";
1879
2298
  const isInlineElement = handler ? handler.isInline === true : tagId === -1;
2299
+ let closesQuote = false;
2300
+ let closesQuoteWrapper = false;
2301
+ let keepsQuoteSeparator = false;
1880
2302
  let gfmAction;
1881
2303
  let handlerOutput;
1882
2304
  const suppressedInPre = (state.depthMap[34] || 0) > 0 && suppressesFormattingInPre(tagId) && !(eventType === 0 ? handler?.literalEnter : handler?.literalExit);
1883
2305
  const emptyTableRow = eventType === 1 && tagId === 30 && state.tableRowOpenerPending && !output && !handler?.literalExit;
1884
2306
  if (eventType === 1 && (handler?.literalExit || output) && gfmLifecycle.openCodeSpans.at(-1)?.owner === element) gfmLifecycle.openCodeSpans.pop();
1885
2307
  if (cleanPass && eventType === 1) cleanPass.exit(element);
1886
- if (!output && !suppressedInPre && handler?.[eventFn]) {
2308
+ if (!output && !suppressedInPre && handler?.[eventFn] && (tagId !== 36 || state.depthMap[25] || handler[eventFn] !== tagHandlers[36].enter)) {
1887
2309
  if (openLinkFragment >= 0 && eventType === 1 && tagId === 26) {
1888
2310
  if (dropEmptyLinkText(buff, openLinkFragment, state.outputPositions)) {
2311
+ noteBufferRewrite(state);
2312
+ if (openLinkHeadingBreak) {
2313
+ state.outputPositions?.replace(openLinkFragment - 1, openLinkFragment, []);
2314
+ buff.length--;
2315
+ state.headingBreakPending = true;
2316
+ }
1889
2317
  if (captionFrameCount !== 0) {
1890
2318
  captionBreakRun = openLinkCaptionBreakRun;
1891
2319
  restoreCaptionBreakFlags(captionFrames, openLinkCaptionFlags, captionFrameCount);
@@ -1894,13 +2322,35 @@ function createMarkdownProcessor(options = {}, createStream) {
1894
2322
  state.lastContentCache = buff.at(-1);
1895
2323
  state.lastTextNode = void 0;
1896
2324
  openLinkFragment = -1;
2325
+ restoreQuoteParentBoundary();
1897
2326
  return;
1898
2327
  }
1899
2328
  }
1900
2329
  if (cleanPass && eventType === 1 && tagId === 26 && cleanPass.unwrap(element)) {
2330
+ noteBufferRewrite(state);
1901
2331
  openLinkFragment = -1;
1902
2332
  return;
1903
2333
  }
2334
+ if (eventType === 1 && tagId === 26 && openLinkFragment !== -1 && !handler.literalExit && !insideRawHtmlRegion && !gfmLifecycle.openCodeSpans.length && lastChar === " ") {
2335
+ const bracket = openLinkFragment < -1 ? -openLinkFragment - 2 : openLinkFragment;
2336
+ let removed = 0;
2337
+ for (let index = buff.length - 1; index > bracket; index--) {
2338
+ const fragment = buff[index];
2339
+ let end = fragment.length;
2340
+ while (end > 0 && fragment.charCodeAt(end - 1) === 32) end--;
2341
+ removed += fragment.length - end;
2342
+ if (end === 0) continue;
2343
+ if (removed && !isAsciiWhitespace(fragment.charCodeAt(end - 1))) {
2344
+ trimTrailingSpaces(buff);
2345
+ const cache = state.lastContentCache;
2346
+ if (cache) state.lastContentCache = cache.slice(0, Math.max(0, cache.length - removed));
2347
+ state.pendingInlineWhitespace = true;
2348
+ lastBuffEntry = buff.at(-1);
2349
+ lastChar = String.fromCharCode(lastOutputChar(buff));
2350
+ }
2351
+ break;
2352
+ }
2353
+ }
1904
2354
  const res = handler[eventFn]({
1905
2355
  node: element,
1906
2356
  state
@@ -1915,6 +2365,8 @@ function createMarkdownProcessor(options = {}, createStream) {
1915
2365
  if (res._tag === "CodeSpanEnter" && span || res._tag === "CodeSpanExit" && span && span.owner !== element) handlerOutput = void 0;
1916
2366
  else {
1917
2367
  gfmAction = res;
2368
+ if (res._tag === "BlockquoteExit") closesQuote = state.blockquotes.length > 0;
2369
+ if (res._tag === "CodeSpanEnter" && captionBoundary === 3 && res.output === " `") res.output = "`";
1918
2370
  handlerOutput = consumeGfmAction(res, state, gfmLifecycle);
1919
2371
  }
1920
2372
  if (handlerOutput) output = [handlerOutput];
@@ -1937,11 +2389,20 @@ function createMarkdownProcessor(options = {}, createStream) {
1937
2389
  const captionEvent = tagId === 106;
1938
2390
  let captionTransition = false;
1939
2391
  if (captionEvent || captionBoundary !== 0 || captionFrameCount !== 0) {
2392
+ if (captionBoundary === 3 && eventType === 0 && output?.[0]?.startsWith("\n\n")) captionBoundary = 2;
2393
+ if (captionBoundary >= 4 && eventType === 0 && !isInlineElement && !openMarkerCount) captionBoundary = 0;
2394
+ const holdsQuoteBoundary = captionBoundary === 3 && tagId === 26 && eventType === 1 && handlerOutput !== void 0 && !handler?.literalExit && !insideRawHtmlRegion;
2395
+ if (holdsQuoteBoundary) captionBoundary = 0;
1940
2396
  const captionEnter = captionEvent && eventType === 0 && !state.depthMap[34];
1941
2397
  const captionExit = captionEvent && eventType === 1 && !state.depthMap[34];
1942
2398
  if (captionEnter) pushCaptionFrame(element, handler);
1943
2399
  let dropBlockquoteOutput = false;
1944
- if (captionBoundary === 1 && eventType === 0 && tagId === 22) {
2400
+ if ((captionBoundary === 1 || captionBoundary === 3) && eventType === 0 && gfmAction?._tag === "BlockquoteEnter") {
2401
+ if (captionBoundary === 3) {
2402
+ let last = lastOutputChar(state.buffer);
2403
+ if (last === -1 && state.lastContentCache) last = state.lastContentCache.charCodeAt(state.lastContentCache.length - 1);
2404
+ keepsQuoteSeparator = last !== -1 && last !== 10;
2405
+ }
1945
2406
  captionBufferChanged = appendCaptionSpacing(captionBoundarySpacing, false) || captionBufferChanged;
1946
2407
  captionTransition = true;
1947
2408
  captionBoundary = 0;
@@ -1949,19 +2410,26 @@ function createMarkdownProcessor(options = {}, createStream) {
1949
2410
  output = void 0;
1950
2411
  handlerOutput = void 0;
1951
2412
  }
2413
+ const literalOutput = eventType === 0 ? handler?.literalEnter : handler?.literalExit;
1952
2414
  let meaningfulOutput = !dropBlockquoteOutput && output?.some(hasNonWhitespace) === true;
2415
+ closesQuoteWrapper = meaningfulOutput && eventType === 1 && isInlineElement && !captionExit && captionBoundary >= 3 && tagId !== 26 && !handler?.literalExit;
2416
+ if (captionBoundary === 5 && meaningfulOutput && eventType === 0) {
2417
+ captionBoundary = 4;
2418
+ quoteTentativeSpacing = void 0;
2419
+ }
1953
2420
  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;
2421
+ if ((INLINE_MARKER_TYPE[tagId] || tagId === 26 && eventType === 0) && !literalOutput) {
2422
+ if (captionBoundary === 1 || captionBoundary === 3) {
2423
+ const quoteBoundary = captionBoundary === 3;
2424
+ const appended = appendCaptionSpacing(captionBoundarySpacing, true);
2425
+ captionBufferChanged = appended || captionBufferChanged;
1959
2426
  captionTransition = true;
1960
- captionBoundary = 2;
2427
+ captionBoundary = quoteBoundary ? 4 : 2;
2428
+ if (quoteBoundary) quoteTentativeSpacing = appended ? state.buffer.at(-1) : void 0;
1961
2429
  }
1962
2430
  if (eventType === 0) {
2431
+ if (captionFrameCount !== 0 && (captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 2] & CAPTION_OPEN) === 0) captionTransition = true;
1963
2432
  anchorPendingCaptions(state.buffer.length);
1964
- captionTransition = true;
1965
2433
  }
1966
2434
  meaningfulOutput = false;
1967
2435
  }
@@ -1971,6 +2439,7 @@ function createMarkdownProcessor(options = {}, createStream) {
1971
2439
  if (captionExit && captionFrameCount !== 0) {
1972
2440
  const offset = (captionFrameCount - 1) * CAPTION_FRAME_SIZE;
1973
2441
  const opened = (captionFrames[offset + 2] & CAPTION_OPEN) !== 0;
2442
+ const restoresHeadingBreak = !opened && defaultCaptionExit && (captionFrames[offset + 2] & CAPTION_HEADING_BREAK) !== 0;
1974
2443
  if (!opened && defaultCaptionExit) {
1975
2444
  output = void 0;
1976
2445
  handlerOutput = void 0;
@@ -1978,16 +2447,18 @@ function createMarkdownProcessor(options = {}, createStream) {
1978
2447
  if (flushCaptionBreakRun()) captionBufferChanged = true;
1979
2448
  captionBufferChanged = prepareCaptionOutput(false) || captionBufferChanged;
1980
2449
  captionTransition = true;
1981
- consumeCaptionTransition(isInlineElement, tagId);
2450
+ consumeCaptionTransition(isInlineElement && !literalOutput, tagId);
1982
2451
  }
1983
2452
  finishCaptionFrame();
1984
2453
  if (!opened && flushCaptionBreakRun()) captionBufferChanged = true;
2454
+ if (restoresHeadingBreak && buff.length > 0 && !captionExitOpensBlockLine(buff)) state.headingBreakPending = true;
1985
2455
  } else if (meaningfulOutput && captionNeedsPreparation()) {
1986
2456
  captionBufferChanged = prepareCaptionOutput(captionEnter, tagId !== 25) || captionBufferChanged;
1987
2457
  captionTransition = true;
1988
- consumeCaptionTransition(isInlineElement, tagId);
2458
+ consumeCaptionTransition(isInlineElement && !literalOutput, tagId);
1989
2459
  }
1990
2460
  if (meaningfulOutput) commitCaptionFrames();
2461
+ if (holdsQuoteBoundary) captionBoundary = 3;
1991
2462
  }
1992
2463
  if (eventType === 1 && tagId === 25 && !state.depthMap[34] && !isInsideTableCell(state) && !handler?.literalExit && endsAtHardBreak(buff)) {
1993
2464
  trimTrailingSpaces(buff);
@@ -2015,16 +2486,45 @@ function createMarkdownProcessor(options = {}, createStream) {
2015
2486
  if (eventType === 1 && openMarkerCount) {
2016
2487
  const markerType = handlerOutput === void 0 ? 0 : INLINE_MARKER_TYPE[tagId];
2017
2488
  if (markerType && (tagId !== 23 || !state.depthMap[34] && !isInsideRawHtmlBlock(state.depthMap)) && !handler?.literalExit) {
2018
- const idx = dropEmptyMarker(buff, openMarkers[--openMarkerCount], markerType, state.outputPositions);
2489
+ const packed = openMarkers[--openMarkerCount];
2490
+ const restoresHeadingBreak = buff[packed >> 3]?.includes("\n");
2491
+ const idx = dropEmptyMarker(buff, packed, markerType, state.outputPositions);
2019
2492
  if (idx >= 0) {
2493
+ noteBufferRewrite(state);
2494
+ if (restoresHeadingBreak) state.headingBreakPending = true;
2020
2495
  resetRetractedCaptionFrames(captionFrames, captionFrameCount, idx);
2021
2496
  state.lastContentCache = idx > 0 ? buff[idx - 1] : void 0;
2497
+ restoreQuoteParentBoundary();
2498
+ return;
2499
+ }
2500
+ if (markerType <= 4 && dropVerticalTabMarker(buff, packed, markerType, handlerOutput, state.outputPositions)) {
2501
+ noteBufferRewrite(state);
2502
+ state.lastContentCache = buff[buff.length - 1];
2022
2503
  return;
2023
2504
  }
2024
2505
  openMarkerCount = 0;
2025
2506
  }
2026
2507
  }
2508
+ if (closesQuoteWrapper) {
2509
+ captionBoundary = 5;
2510
+ quoteTentativeSpacing = void 0;
2511
+ const block = traverseUpToFirstBlockNode(element.parent).at(-1);
2512
+ block.childTextNodeIndex = (block.childTextNodeIndex || 0) + 1;
2513
+ }
2027
2514
  if (tagId === 6 && !state.depthMap[34] && output?.length === 1 && output[0] === "\n" && lastChar === "\n" && secondLastChar === "\n") output = void 0;
2515
+ const rawBlockTag = tagId === 100 || tagId === 101 || tagId === 99 || tagId === 98 || tagId === 2 || tagId === 3;
2516
+ if (rawBlockTag && rawHtmlNeedsBoundary && trackRawHtmlMarkdownContext(buff, bufferScan)) rawHtmlNeedsBoundary = false;
2517
+ if (rawBlockTag && !isInsideTableCell(state) && !state.depthMap[34] && !(eventType === 0 ? handler?.literalEnter : handler?.literalExit) && handlerOutput && (pendingRawHtmlBoundary || blockOpenPrefix(state, void 0) === void 0)) {
2518
+ rawHtmlNeedsBoundary = true;
2519
+ bufferScan[0] = false;
2520
+ bufferScan[1] = buff.length;
2521
+ }
2522
+ const endsRawHtmlBlock = rawBlockTag && eventType === 1 && !insideRawHtmlRegion;
2523
+ if (endsRawHtmlBlock) {
2524
+ pendingRawHtmlBoundary = rawHtmlNeedsBoundary && !handler?.literalExit;
2525
+ rawHtmlNeedsBoundary = false;
2526
+ } else if (rawBlockTag && eventType === 0) pendingRawHtmlBoundary = false;
2527
+ if (eventType === 1 && (tagId === 25 || tagId === 22)) pendingRawHtmlBoundary = false;
2028
2528
  const newLineConfig = suppressedInPre ? NO_SPACING : calculateNewLineConfig(node, state, eventType);
2029
2529
  const quoteAtStart = eventType === 0 && state.blockquotes.at(-1)?.fragment === state.buffer.length;
2030
2530
  const configuredNewLines = quoteAtStart || captionEvent || captionTransition ? 0 : eventType === 1 && tagId === 13 && state.blockquotes.length > 0 ? Math.min(1, newLineConfig[eventType] || 0) : newLineConfig[eventType] || 0;
@@ -2041,7 +2541,7 @@ function createMarkdownProcessor(options = {}, createStream) {
2041
2541
  if (state.pendingInlineWhitespace) {
2042
2542
  const firstOutput = output?.[0]?.[0] || "";
2043
2543
  if (eventType === 0) {
2044
- if (!isInlineElement || tagId === 6 || newLines > 0 || firstOutput === "\n" || firstOutput === "\r") state.pendingInlineWhitespace = false;
2544
+ if (!isInlineElement || newLines > 0 || firstOutput === "\n" || firstOutput === "\r") state.pendingInlineWhitespace = false;
2045
2545
  else if (firstOutput) {
2046
2546
  if (lastChar && !" \n \r".includes(lastChar) && !" \n \r".includes(firstOutput)) {
2047
2547
  state.buffer.push(" ");
@@ -2060,7 +2560,7 @@ function createMarkdownProcessor(options = {}, createStream) {
2060
2560
  state.lastContentCache = fragment;
2061
2561
  }
2062
2562
  }
2063
- if (gfmAction) commitGfmAction(gfmAction, state, gfmLifecycle, state.buffer.length, element);
2563
+ if (gfmAction) commitGfmAction(gfmAction, state, gfmLifecycle, state.buffer.length, element, keepsQuoteSeparator);
2064
2564
  updateListIndent(state, element, eventType);
2065
2565
  return;
2066
2566
  }
@@ -2089,13 +2589,18 @@ function createMarkdownProcessor(options = {}, createStream) {
2089
2589
  const collapsesWhiteSpace = node.tagHandler?.collapsesInnerWhiteSpace;
2090
2590
  const hasSpacing = node.tagHandler?.spacing && Array.isArray(node.tagHandler.spacing);
2091
2591
  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))) {
2592
+ 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
2593
  const originalLength = lastFragment.length;
2094
2594
  const trimmed = trimAsciiWhitespaceEnd(lastFragment);
2095
2595
  if (originalLength - trimmed.length > 0) {
2096
2596
  if (buff?.length && buff.at(-1) === lastFragment) {
2097
- state.outputPositions?.replace(buff.length - 1, buff.length, [trimmed]);
2098
- buff[buff.length - 1] = trimmed;
2597
+ if (trimmed || buff.length < 2 || buff[buff.length - 2] !== "") {
2598
+ state.outputPositions?.replace(buff.length - 1, buff.length, [trimmed]);
2599
+ buff[buff.length - 1] = trimmed;
2600
+ } else {
2601
+ state.outputPositions?.replace(buff.length - 1, buff.length, []);
2602
+ buff.length--;
2603
+ }
2099
2604
  }
2100
2605
  if (eventType === 1 && isInlineElement) state.pendingInlineWhitespace = true;
2101
2606
  }
@@ -2103,10 +2608,95 @@ function createMarkdownProcessor(options = {}, createStream) {
2103
2608
  state.lastTextNode = void 0;
2104
2609
  }
2105
2610
  }
2106
- if (!captionTransition && tagId !== 6 && output?.[0]?.[0] && eventType === 0 && !handler?.literalEnter && lastChar && needsSpacing(lastChar, output[0][0], state)) {
2611
+ let linkHeadingBreak = false;
2612
+ if (state.headingBreakPending && eventType === 0) {
2613
+ if (tagId === 25 || tagId === 106 || output?.[0] && trimLeadingSpaces(output[0]).startsWith("\n")) {
2614
+ state.headingBreakPending = false;
2615
+ if (tagId === 106 && !state.depthMap[34] && captionFrameCount !== 0) captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 2] |= CAPTION_HEADING_BREAK;
2616
+ } else if (output?.some(hasNonWhitespace)) {
2617
+ state.headingBreakPending = false;
2618
+ const separator = `\n\n${state.listIndent}`;
2619
+ if (tagId === 26 && output[0] === "[") {
2620
+ linkHeadingBreak = true;
2621
+ buff.push(separator);
2622
+ state.lastContentCache = separator;
2623
+ lastChar = " ";
2624
+ } else {
2625
+ const first = output[0];
2626
+ output[0] = `${separator}${trimLeadingSpaces(first)}`;
2627
+ if (handlerOutput === first) handlerOutput = output[0];
2628
+ if (gfmAction?._tag === "CodeSpanEnter") gfmAction = {
2629
+ _tag: "CodeSpanEnter",
2630
+ output: `${separator}${trimLeadingSpaces(gfmAction.output)}`
2631
+ };
2632
+ }
2633
+ }
2634
+ }
2635
+ 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)) {
2636
+ if (headingKeptInlineInItem(element)) {
2637
+ output[0] = `${"#".repeat(tagId - 7 + 1)} `;
2638
+ handlerOutput = output[0];
2639
+ } else trimTrailingSpaces(buff);
2640
+ }
2641
+ 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)) {
2642
+ trimTrailingSpaces(buff);
2643
+ output[0] = `\n\n${state.listIndent}${output[0]}`;
2644
+ handlerOutput = output[0];
2645
+ }
2646
+ if (!captionTransition && output?.[0]?.[0] && eventType === 0 && !handler?.literalEnter && lastChar && needsSpacing(lastChar, output[0][0])) {
2107
2647
  state.buffer.push(" ");
2108
2648
  state.lastContentCache = " ";
2109
2649
  }
2650
+ let trailingEmphasisWhitespace = "";
2651
+ 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)) {
2652
+ let firstFragment = buff.length;
2653
+ let firstOffset = 0;
2654
+ let hasVerticalTab = false;
2655
+ for (let index = buff.length - 1; index >= 0; index--) {
2656
+ const fragment = buff[index];
2657
+ let end = fragment.length;
2658
+ while (end > 0) {
2659
+ const code = fragment.charCodeAt(end - 1);
2660
+ if (code !== 11 && !isAsciiWhitespace(code)) break;
2661
+ hasVerticalTab ||= code === 11;
2662
+ end--;
2663
+ }
2664
+ if (end < fragment.length) {
2665
+ firstFragment = index;
2666
+ firstOffset = end;
2667
+ }
2668
+ if (end > 0) break;
2669
+ }
2670
+ if (hasVerticalTab) {
2671
+ for (let index = firstFragment; index < buff.length; index++) {
2672
+ const fragment = buff[index];
2673
+ const end = index === firstFragment ? firstOffset : 0;
2674
+ trailingEmphasisWhitespace += fragment.slice(end);
2675
+ const trimmed = fragment.slice(0, end);
2676
+ state.outputPositions?.replace(index, index + 1, [trimmed]);
2677
+ buff[index] = trimmed;
2678
+ }
2679
+ noteBufferRewrite(state);
2680
+ if (newLines > 0 && output) {
2681
+ output.splice(output.length - 1, 0, trailingEmphasisWhitespace);
2682
+ trailingEmphasisWhitespace = "";
2683
+ }
2684
+ }
2685
+ }
2686
+ 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)) {
2687
+ if (handler?.literalEnterHeading) {
2688
+ if (handler.literalExit) escapeTrailingHeadingHashes(state);
2689
+ trimTrailingSpaces(buff);
2690
+ }
2691
+ state.headingBreakPending = true;
2692
+ }
2693
+ if (eventType === 0 && tagId === 6 && !state.depthMap[34] && !handler?.literalEnter && output?.at(-1)?.endsWith("\n") && lastOutputChar(buff) === 32) trimTrailingSpaces(buff);
2694
+ const rawHtmlQuoteBoundary = pendingRawHtmlBoundary && gfmAction?._tag === "BlockquoteEnter";
2695
+ if (rawHtmlQuoteBoundary) finishRawHtmlBlock(`${output?.join("") ?? ""}>`, true);
2696
+ if (pendingRawHtmlBoundary && !endsRawHtmlBlock && output) {
2697
+ if (newLines >= 2) pendingRawHtmlBoundary = false;
2698
+ else finishRawHtmlBlock(output.join(""), true);
2699
+ }
2110
2700
  let outputStart = state.buffer.length;
2111
2701
  if (output) {
2112
2702
  outputStart = state.buffer.length;
@@ -2115,15 +2705,22 @@ function createMarkdownProcessor(options = {}, createStream) {
2115
2705
  state.lastContentCache = fragment;
2116
2706
  }
2117
2707
  }
2118
- if (gfmAction) commitGfmAction(gfmAction, state, gfmLifecycle, outputStart, element);
2708
+ if (trailingEmphasisWhitespace) {
2709
+ state.buffer.push(trailingEmphasisWhitespace);
2710
+ state.lastContentCache = trailingEmphasisWhitespace;
2711
+ }
2712
+ if (gfmAction) commitGfmAction(gfmAction, state, gfmLifecycle, outputStart, element, keepsQuoteSeparator, rawHtmlQuoteBoundary);
2119
2713
  if (tagId === 25 && !isInsideTableCell(state)) {
2120
- if (eventType === 0) recordItemMarker(state, element.index);
2121
- else resolveItemMarker(state, true);
2714
+ if (eventType === 0) recordItemMarker(state, element.index, handler?.literalEnter ? "" : lastChar);
2715
+ else resolveItemMarker(state, true, -1, openLinkFragment !== -1);
2122
2716
  }
2123
- if (eventType === 0 && tagId === 26 && outputStart < buff.length && buff.at(-1) === "[") openLink(buff.length - 1);
2717
+ if (eventType === 0 && tagId === 26 && outputStart < buff.length && buff.at(-1) === "[") openLink(buff.length - 1, linkHeadingBreak);
2124
2718
  if (cleanPass) {
2125
2719
  if (eventType === 0) cleanPass.enter(element, outputStart);
2126
- else if (handlerOutput) cleanPass.closed(element, outputStart, handlerOutput);
2720
+ else if (handlerOutput) {
2721
+ cleanPass.closed(element, outputStart, handlerOutput);
2722
+ if (tagId === 26) noteBufferRewrite(state);
2723
+ }
2127
2724
  }
2128
2725
  if (eventType === 0 && handlerOutput !== void 0 && isInlineElement && !handler?.literalEnter) {
2129
2726
  const markerType = INLINE_MARKER_TYPE[tagId];
@@ -2134,6 +2731,11 @@ function createMarkdownProcessor(options = {}, createStream) {
2134
2731
  }
2135
2732
  } else if (openMarkerCount && (eventType === 1 && handler?.literalExit || tagId !== -1 && !isInlineElement || output?.some(hasNonWhitespace))) openMarkerCount = 0;
2136
2733
  if (eventType === 1 && tagId === 26) openLinkFragment = -1;
2734
+ if (closesQuote && state.depthMap[25] && !state.depthMap[34] && !insideRawHtmlRegion && !isInsideTableCell(state)) {
2735
+ captionBoundary = 3;
2736
+ captionBoundarySpacing = 2;
2737
+ state.listRulePending = void 0;
2738
+ }
2137
2739
  updateListIndent(state, element, eventType);
2138
2740
  if (!insideRawHtmlRegion && inRawHtmlRegion) {
2139
2741
  bufferScan[0] = false;
@@ -2147,7 +2749,7 @@ function createMarkdownProcessor(options = {}, createStream) {
2147
2749
  return cleanPass ? cleanPass.finish(result).markdown : result;
2148
2750
  }
2149
2751
  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);
2752
+ 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 - Number(openLinkHeadingBreak));
2151
2753
  if (cleanPass && !final) heldFragment = Math.min(heldFragment, cleanPass.held());
2152
2754
  const captionHoldCount = final ? 0 : captionFrameCount;
2153
2755
  for (let index = 0; index < captionHoldCount; index++) {