mrkdwn.js 4.0.5 → 6.6.1

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.
Files changed (118) hide show
  1. package/README.md +85 -66
  2. package/dist/ast/ast.d.cts +1 -1
  3. package/dist/ast/ast.d.ts +1 -1
  4. package/dist/{ast-8XCbjRQT.d.cts → ast-CNfTgS0N.d.cts} +35 -35
  5. package/dist/{ast-8XCbjRQT.d.ts → ast-CNfTgS0N.d.ts} +35 -35
  6. package/dist/block/block.cjs +12 -4
  7. package/dist/block/block.d.cts +9 -5
  8. package/dist/block/block.d.ts +9 -5
  9. package/dist/block/block.js +8 -4
  10. package/dist/block/definitions.d.cts +2 -2
  11. package/dist/block/definitions.d.ts +2 -2
  12. package/dist/block/node.d.cts +4 -4
  13. package/dist/block/node.d.ts +4 -4
  14. package/dist/block/table.d.cts +1 -1
  15. package/dist/block/table.d.ts +1 -1
  16. package/dist/codec.cjs +1 -1
  17. package/dist/codec.d.cts +1625 -23
  18. package/dist/codec.d.ts +1625 -23
  19. package/dist/codec.js +2 -2
  20. package/dist/defaults/defaults.d.cts +1 -1
  21. package/dist/defaults/defaults.d.ts +1 -1
  22. package/dist/diagnostics/diagnostics.cjs +17 -7
  23. package/dist/diagnostics/diagnostics.d.cts +2 -2
  24. package/dist/diagnostics/diagnostics.d.ts +2 -2
  25. package/dist/diagnostics/diagnostics.js +17 -8
  26. package/dist/{diagnostics-BWK1iGy7.d.cts → diagnostics-CjfBoW4K.d.cts} +14 -10
  27. package/dist/{diagnostics-BWK1iGy7.d.ts → diagnostics-CjfBoW4K.d.ts} +14 -10
  28. package/dist/emit/emit.cjs +378 -42
  29. package/dist/emit/emit.js +381 -45
  30. package/dist/emit/front-matter.cjs +22 -5
  31. package/dist/emit/front-matter.js +22 -5
  32. package/dist/emit/html-table.cjs +104 -0
  33. package/dist/emit/html-table.d.cts +7 -0
  34. package/dist/emit/html-table.d.ts +7 -0
  35. package/dist/emit/html-table.js +102 -0
  36. package/dist/emit/inline.cjs +69 -26
  37. package/dist/emit/inline.d.cts +2 -12
  38. package/dist/emit/inline.d.ts +2 -12
  39. package/dist/emit/inline.js +68 -27
  40. package/dist/emit/table.cjs +18 -11
  41. package/dist/emit/table.d.cts +3 -2
  42. package/dist/emit/table.d.ts +3 -2
  43. package/dist/emit/table.js +18 -11
  44. package/dist/html/html-table.cjs +243 -0
  45. package/dist/html/html-table.d.cts +5 -0
  46. package/dist/html/html-table.d.ts +5 -0
  47. package/dist/html/html-table.js +242 -0
  48. package/dist/html/render.d.cts +1 -1
  49. package/dist/html/render.d.ts +1 -1
  50. package/dist/image/image.cjs +4 -4
  51. package/dist/image/image.d.cts +1 -1
  52. package/dist/image/image.d.ts +1 -1
  53. package/dist/image/image.js +4 -4
  54. package/dist/{image-C4KYmz_L.d.cts → image-B5L0HpAJ.d.cts} +1 -1
  55. package/dist/{image-DescdRgq.d.cts → image-BtmTG4_a.d.cts} +1 -1
  56. package/dist/{image-DescdRgq.d.ts → image-BtmTG4_a.d.ts} +1 -1
  57. package/dist/{image-Cm3hT5PS.d.ts → image-C390OIB3.d.ts} +1 -1
  58. package/dist/index.cjs +2 -2
  59. package/dist/index.d.cts +4 -4
  60. package/dist/index.d.ts +4 -4
  61. package/dist/index.js +3 -3
  62. package/dist/inline/delimiter.d.cts +2 -2
  63. package/dist/inline/delimiter.d.ts +2 -2
  64. package/dist/inline/inline.d.cts +1 -1
  65. package/dist/inline/inline.d.ts +1 -1
  66. package/dist/inline/link.d.cts +17 -1
  67. package/dist/inline/link.d.ts +17 -1
  68. package/dist/inline/node.d.cts +2 -2
  69. package/dist/inline/node.d.ts +2 -2
  70. package/dist/{inline-CXVQWQnW.d.cts → inline-CnO86zMw.d.cts} +2 -2
  71. package/dist/inline-DCIKQ83j.d.cts +14 -0
  72. package/dist/{inline-B_V7bs5j.d.ts → inline-DItZ-VVw.d.ts} +2 -2
  73. package/dist/inline-INoDAG37.d.ts +14 -0
  74. package/dist/lower/front-matter.cjs +73 -26
  75. package/dist/lower/front-matter.d.cts +2 -1
  76. package/dist/lower/front-matter.d.ts +2 -1
  77. package/dist/lower/front-matter.js +72 -25
  78. package/dist/lower/image.d.cts +1 -1
  79. package/dist/lower/image.d.ts +1 -1
  80. package/dist/lower/inline.cjs +87 -33
  81. package/dist/lower/inline.d.cts +9 -12
  82. package/dist/lower/inline.d.ts +9 -12
  83. package/dist/lower/inline.js +89 -34
  84. package/dist/lower/lower.cjs +143 -113
  85. package/dist/lower/lower.d.cts +8 -1
  86. package/dist/lower/lower.d.ts +8 -1
  87. package/dist/lower/lower.js +144 -115
  88. package/dist/lower/table.cjs +3 -2
  89. package/dist/lower/table.d.cts +1 -1
  90. package/dist/lower/table.d.ts +1 -1
  91. package/dist/lower/table.js +3 -2
  92. package/dist/options/options.d.cts +10 -10
  93. package/dist/options/options.d.ts +10 -10
  94. package/dist/read.cjs +45 -9
  95. package/dist/read.d.cts +3 -3
  96. package/dist/read.d.ts +3 -3
  97. package/dist/read.js +47 -11
  98. package/dist/scan/entity-table.cjs +2125 -2125
  99. package/dist/scan/entity-table.js +2125 -2125
  100. package/dist/shared/line-ending.cjs +7 -0
  101. package/dist/shared/line-ending.d.cts +5 -0
  102. package/dist/shared/line-ending.d.ts +5 -0
  103. package/dist/shared/line-ending.js +5 -0
  104. package/dist/shared/list-id.cjs +11 -3
  105. package/dist/shared/list-id.d.cts +7 -4
  106. package/dist/shared/list-id.d.ts +7 -4
  107. package/dist/shared/list-id.js +11 -4
  108. package/dist/shared/style-constants.cjs +0 -2
  109. package/dist/shared/style-constants.d.cts +1 -2
  110. package/dist/shared/style-constants.d.ts +1 -2
  111. package/dist/shared/style-constants.js +1 -2
  112. package/dist/write.cjs +33 -6
  113. package/dist/write.d.cts +2 -2
  114. package/dist/write.d.ts +2 -2
  115. package/dist/write.js +34 -7
  116. package/package.json +29 -30
  117. package/dist/link-Dv4kxVjk.d.cts +0 -18
  118. package/dist/link-Dv4kxVjk.d.ts +0 -18
package/dist/emit/emit.js CHANGED
@@ -1,21 +1,31 @@
1
1
  import { isValidFootnoteLabel } from "../inline/footnote.js";
2
2
  import "../defaults/defaults.js";
3
- import { MarkdownDiagnosticCodes, MarkdownUnbalancedConstructMarkersError, MarkdownUnsupportedDocumentKindError, NOOP_MARKDOWN_DIAGNOSTIC_SINK } from "../diagnostics/diagnostics.js";
4
- import { parseListNumId } from "../shared/list-id.js";
3
+ import { MarkdownDiagnosticCodes, MarkdownInvalidRunConstructExtentError, MarkdownUnbalancedConstructMarkersError, MarkdownUnsupportedDocumentKindError, NOOP_MARKDOWN_DIAGNOSTIC_SINK } from "../diagnostics/diagnostics.js";
4
+ import { matchHtmlBlockStart } from "../html/html.js";
5
+ import { ESCAPED_HARD_BREAK_PATTERN, LINE_ENDING_PATTERN } from "../shared/line-ending.js";
6
+ import "../scan/scan.js";
7
+ import { LineCursor } from "../block/line.js";
8
+ import { parseListMarker } from "../block/list.js";
9
+ import { parseTableDelimiterRow, splitTableRow } from "../block/table.js";
10
+ import { ATX_MARKER_PATTERN, CODE_FENCE_PATTERN, MATH_BLOCK_MARKER_PATTERN, THEMATIC_BREAK_PATTERN } from "../block/block.js";
5
11
  import { CODE_BLOCK_STYLE_ID, HORIZONTAL_RULE_STYLE_ID, HTML_PREFORMATTED_STYLE_ID, MATH_BLOCK_STYLE_ID, QUOTE_STYLE_ID, parseHeadingStyleId } from "../shared/style-constants.js";
12
+ import { parseListNumId } from "../shared/list-id.js";
6
13
  import { emitFrontMatter } from "./front-matter.js";
7
- import { emitRuns } from "./inline.js";
14
+ import { emitRuns, escapeLinkDestination, escapeMarkdownText, renderLinkTitle } from "./inline.js";
8
15
  import { emitImage } from "./image.js";
9
16
  import { emitTable } from "./table.js";
10
- import { clampHeadingLevel, findConstructMarkerImbalance } from "document-schema.js";
17
+ import { clampHeadingLevel, findConstructMarkerImbalance, findRunConstructFault } from "document-schema.js";
11
18
  //#region src/emit/emit.ts
19
+ function isDataUri(destination) {
20
+ return destination.startsWith("data:");
21
+ }
12
22
  const MAX_SETEXT_LEVEL = 2;
13
23
  const SETEXT_LEVEL_1_CHAR = "=";
14
24
  const SETEXT_LEVEL_2_CHAR = "-";
15
25
  const MIN_SETEXT_UNDERLINE_LENGTH = 1;
16
26
  function renderSetextHeading(level, text) {
17
27
  const underlineChar = level === 1 ? SETEXT_LEVEL_1_CHAR : SETEXT_LEVEL_2_CHAR;
18
- const firstLine = text.split("\n")[0] ?? "";
28
+ const firstLine = text.split(LINE_ENDING_PATTERN)[0] ?? "";
19
29
  return `${text}\n${underlineChar.repeat(Math.max(MIN_SETEXT_UNDERLINE_LENGTH, firstLine.length))}`;
20
30
  }
21
31
  const MIN_CODE_FENCE_LENGTH = 3;
@@ -42,6 +52,84 @@ function isQuotableStyle(styleId) {
42
52
  if (styleId === void 0) return false;
43
53
  return QUOTABLE_STYLE_IDS.has(styleId) || parseHeadingStyleId(styleId) !== void 0;
44
54
  }
55
+ function terminatesCleanly(styleId) {
56
+ if (styleId === void 0 || styleId === "Quote" || styleId === "HTMLPreformatted") return false;
57
+ return styleId === "CodeBlock" || styleId === "MathBlock" || styleId === "HorizontalRule" || parseHeadingStyleId(styleId) !== void 0;
58
+ }
59
+ const BLANK_OR_WHITESPACE_ONLY_LINE = /^[ \t]*$/;
60
+ function firstContentLineIndex(text) {
61
+ return text.split(LINE_ENDING_PATTERN).findIndex((line) => !BLANK_OR_WHITESPACE_ONLY_LINE.test(line));
62
+ }
63
+ function leadingIndentColumns(line) {
64
+ let column = 0;
65
+ for (const char of line) if (char === " ") column += 1;
66
+ else if (char === " ") column += 4 - column % 4;
67
+ else break;
68
+ return column;
69
+ }
70
+ const MAX_LEADING_BLANK_LINES_FOR_SETEXT = 1;
71
+ function interruptsSetextParagraph(line, atBlockStart) {
72
+ const cursor = new LineCursor(line);
73
+ if (cursor.indented) return false;
74
+ if (cursor.peekNextNonspace() === ">") return true;
75
+ const rest = cursor.restFromNextNonspace();
76
+ if (ATX_MARKER_PATTERN.test(rest) || CODE_FENCE_PATTERN.test(rest) || THEMATIC_BREAK_PATTERN.test(rest) || MATH_BLOCK_MARKER_PATTERN.test(rest) || matchHtmlBlockStart(rest, !atBlockStart) !== void 0) return true;
77
+ return parseListMarker(cursor, !atBlockStart) !== void 0;
78
+ }
79
+ function tableDelimiterRowPromotesPrecedingLine(line, precedingLine) {
80
+ const cursor = new LineCursor(line);
81
+ if (cursor.indented) return false;
82
+ return parseTableDelimiterRow(cursor.restFromNextNonspace())?.length === splitTableRow(precedingLine).length;
83
+ }
84
+ function unsafeSetextBreakReason(text) {
85
+ let sawContentLine = false;
86
+ let leadingBlankLines = 0;
87
+ let precedingLine = "";
88
+ for (const line of text.split(LINE_ENDING_PATTERN)) {
89
+ const isBlank = BLANK_OR_WHITESPACE_ONLY_LINE.test(line);
90
+ if (!sawContentLine) {
91
+ if (isBlank) {
92
+ leadingBlankLines += 1;
93
+ if (leadingBlankLines > MAX_LEADING_BLANK_LINES_FOR_SETEXT) return "blank-line";
94
+ continue;
95
+ }
96
+ sawContentLine = true;
97
+ if (leadingIndentColumns(line) >= 4) return "leading-indentation";
98
+ if (interruptsSetextParagraph(line, true)) return "interrupting-line";
99
+ precedingLine = line;
100
+ continue;
101
+ }
102
+ if (isBlank) return "blank-line";
103
+ if (interruptsSetextParagraph(line, false) || tableDelimiterRowPromotesPrecedingLine(line, precedingLine)) return "interrupting-line";
104
+ precedingLine = line;
105
+ }
106
+ return sawContentLine ? void 0 : "blank-line";
107
+ }
108
+ function embedsUnsafeBreakForSetext(text) {
109
+ return unsafeSetextBreakReason(text) !== void 0;
110
+ }
111
+ function unsafeSetextDiagnosticMessage(level, reason, embedsLineBreak) {
112
+ const hazard = reason === "leading-indentation" ? `the line that would become the setext heading's own first line of text opens with 4 or more columns of space/tab indentation -- setext's own grammar (spec 0.31.2) requires the first line to have "not more than 3 spaces of indentation", so promoting would read that line back as an indented code block instead of heading text` : reason === "interrupting-line" ? `a line of the heading's own text -- including possibly its first -- would itself be interpretable as a code fence, ATX heading, block quote, thematic break, list item, HTML block, math block, or GFM table delimiter row -- setext's own grammar (spec 0.31.2) requires every one of the heading's lines to instead read as ordinary paragraph text, so promoting would read that line back as the start of a fresh, unrelated block (or, for a table delimiter row, a conversion of the line before it) rather than more of the heading` : `promoting would leave the setext underline with no heading text of its own to attach to -- either a blank line immediately before it (a trailing break), a blank line in the middle of the heading's own text (a genuinely interior break), or the heading's own rendered text being entirely blank to begin with -- setext's own grammar requires "one or more lines of text, not interrupted by a blank line"`;
113
+ return embedsLineBreak ? `a level ${String(level)} heading's own content contains a line break, but ${hazard}; ATX collapses the break to a single space instead of promoting into a corrupt reparse` : `the effective WriteMarkdownOptions.headingStyle is 'setext' (an explicit caller choice -- a break-free heading only reaches this path when requested outright), but ${hazard}; rendered as ATX instead of promoting into a corrupt reparse`;
114
+ }
115
+ function willRenderAsSetext(paragraph, level, context) {
116
+ if (level > MAX_SETEXT_LEVEL) return false;
117
+ const text = emitRuns(paragraph.runs, {
118
+ sink: NOOP_MARKDOWN_DIAGNOSTIC_SINK,
119
+ emphasisMarker: context.emphasisMarker
120
+ }, paragraph.constructs);
121
+ if (embedsUnsafeBreakForSetext(text)) return false;
122
+ return context.headingStyle === "setext" || LINE_ENDING_PATTERN.test(text);
123
+ }
124
+ function canInterruptOpenParagraph(paragraph, context) {
125
+ const styleId = paragraph.styleId;
126
+ if (styleId === void 0 || styleId === "Quote" || styleId === "HTMLPreformatted") return false;
127
+ if (styleId === "CodeBlock" || styleId === "MathBlock") return true;
128
+ if (styleId === "HorizontalRule") return context.thematicBreakChar !== SETEXT_LEVEL_2_CHAR;
129
+ const headingLevel = parseHeadingStyleId(styleId);
130
+ if (headingLevel !== void 0) return !willRenderAsSetext(paragraph, clampHeadingLevel(headingLevel), context);
131
+ return false;
132
+ }
45
133
  function quoteDepthOf(paragraph) {
46
134
  if (paragraph.indentLeftPt === void 0 || paragraph.indentLeftPt <= 0) return 0;
47
135
  return Math.max(1, Math.round(paragraph.indentLeftPt / 36));
@@ -51,9 +139,12 @@ function renderParagraphBody(paragraph, context) {
51
139
  if (paragraph.styleId === "CodeBlock") {
52
140
  const literal = paragraph.runs.map((run) => run.text).join("");
53
141
  const fence = codeFenceFor(literal, context.codeFenceChar);
54
- return literal.length === 0 ? `${fence}\n${fence}` : `${fence}\n${literal}\n${fence}`;
142
+ const remainder = paragraph.source?.format === "markdown" ? paragraph.source.xml : void 0;
143
+ const info = [paragraph.codeLanguage, remainder].filter((part) => part !== void 0 && part.length > 0).join(" ");
144
+ const opening = info.length > 0 ? `${fence} ${info}` : fence;
145
+ return literal.length === 0 ? `${opening}\n${fence}` : `${opening}\n${literal}\n${fence}`;
55
146
  }
56
- if (paragraph.styleId === "HTMLPreformatted") return paragraph.runs.map((run) => run.text).join("");
147
+ if (paragraph.styleId === "HTMLPreformatted") return paragraph.source?.format === "markdown" ? paragraph.source.xml : paragraph.runs.map((run) => run.text).join("");
57
148
  if (paragraph.styleId === "MathBlock") return `$$\n${paragraph.runs.map((run) => run.text).join("")}\n$$`;
58
149
  const headingLevel = paragraph.styleId === void 0 ? void 0 : parseHeadingStyleId(paragraph.styleId);
59
150
  if (headingLevel !== void 0) {
@@ -63,15 +154,46 @@ function renderParagraphBody(paragraph, context) {
63
154
  severity: "info",
64
155
  message: `heading level ${String(headingLevel)} exceeds ATX's own six-"#" ceiling and is clamped to ${String(level)}`
65
156
  });
66
- const text = emitRuns(paragraph.runs, context);
67
- if (context.headingStyle === "setext" && level <= MAX_SETEXT_LEVEL) return renderSetextHeading(level, text);
157
+ const text = emitRuns(paragraph.runs, context, paragraph.constructs);
158
+ const embedsLineBreak = LINE_ENDING_PATTERN.test(text);
159
+ const unsafeSetextReason = unsafeSetextBreakReason(text);
160
+ const unsafeForSetext = unsafeSetextReason !== void 0;
161
+ const setextRequested = context.headingStyle === "setext" || embedsLineBreak;
162
+ if (setextRequested && level <= MAX_SETEXT_LEVEL && !unsafeForSetext) {
163
+ if (context.headingStyle !== "setext") {
164
+ const leadingBreakAbsorbed = firstContentLineIndex(text) > 0;
165
+ context.sink({
166
+ code: MarkdownDiagnosticCodes.HEADING_STYLE_OVERRIDDEN_FOR_LINE_BREAK,
167
+ severity: "info",
168
+ message: leadingBreakAbsorbed ? `the effective WriteMarkdownOptions.headingStyle is 'atx' (its own default, or an explicit caller choice), but this level ${String(level)} heading's own content contains a line break ATX has no way to hold -- rendered as setext instead, though the heading's own leading blank line is absorbed as ordinary space ahead of it on read-back rather than reproduced inside it` : `the effective WriteMarkdownOptions.headingStyle is 'atx' (its own default, or an explicit caller choice), but this level ${String(level)} heading's own content contains a line break ATX has no way to hold -- rendered as setext instead so the break survives`
169
+ });
170
+ }
171
+ return renderSetextHeading(level, text);
172
+ }
173
+ if (setextRequested && level <= MAX_SETEXT_LEVEL && unsafeForSetext) {
174
+ context.sink({
175
+ code: MarkdownDiagnosticCodes.HEADING_LINE_BREAK_UNSAFE_FOR_SETEXT,
176
+ severity: "info",
177
+ message: unsafeSetextDiagnosticMessage(level, unsafeSetextReason, embedsLineBreak)
178
+ });
179
+ if (embedsLineBreak) return `${"#".repeat(level)} ${text.replace(ESCAPED_HARD_BREAK_PATTERN, " ").split(LINE_ENDING_PATTERN).join(" ")}`;
180
+ return `${"#".repeat(level)} ${text}`;
181
+ }
182
+ if (embedsLineBreak) {
183
+ context.sink({
184
+ code: MarkdownDiagnosticCodes.HEADING_LINE_BREAK_COLLAPSED,
185
+ severity: "info",
186
+ message: `a level ${String(level)} heading's own content contains a line break; only setext's own level-1/2 grammar can hold one, so ATX collapses it to a single space`
187
+ });
188
+ return `${"#".repeat(level)} ${text.replace(ESCAPED_HARD_BREAK_PATTERN, " ").split(LINE_ENDING_PATTERN).join(" ")}`;
189
+ }
68
190
  return `${"#".repeat(level)} ${text}`;
69
191
  }
70
- return emitRuns(paragraph.runs, context);
192
+ return emitRuns(paragraph.runs, context, paragraph.constructs);
71
193
  }
72
194
  function renderParagraph(paragraph, context) {
73
195
  const body = renderParagraphBody(paragraph, context);
74
- const depth = quoteDepthOf(paragraph);
196
+ const depth = context.divisionDepth > 0 ? 0 : quoteDepthOf(paragraph);
75
197
  if (depth === 0) return body;
76
198
  if (!isQuotableStyle(paragraph.styleId)) {
77
199
  context.sink({
@@ -89,8 +211,13 @@ function renderTopLevelBlock(block, context) {
89
211
  case "paragraph": return renderParagraph(block, context);
90
212
  case "table": return emitTable(block, context);
91
213
  case "image": return emitImage(block, context.embedImages);
92
- case "pageBreak":
93
- case "embeddedObject": return "";
214
+ case "embeddedObject":
215
+ if (block.objectKind === "formula" && block.document.kind === "formula" && block.document.formula.presentation !== void 0) {
216
+ const latex = block.document.formula.presentation.latex;
217
+ return latex.length === 0 ? "$$\n$$" : `$$\n${latex}\n$$`;
218
+ }
219
+ return "";
220
+ case "pageBreak": return "";
94
221
  }
95
222
  }
96
223
  function listInfoFor(numId, context) {
@@ -116,16 +243,9 @@ function listInfoFor(numId, context) {
116
243
  }
117
244
  return info;
118
245
  }
119
- function checkboxPrefixFor(item) {
120
- const first = item.runs[0];
121
- if (first === void 0) return;
122
- if (first.text.startsWith(`☒ `)) return "[x] ";
123
- if (first.text.startsWith(`☐ `)) return "[ ] ";
124
- }
125
- function stripCheckboxRun(item, checkboxPrefix) {
126
- if (checkboxPrefix === void 0) return item;
246
+ function stripCheckboxRun(item) {
127
247
  const first = item.runs[0];
128
- const glyphPrefix = checkboxPrefix === "[x] " ? `☒ ` : `☐ `;
248
+ const glyphPrefix = first?.text.startsWith(`☒ `) ? `☒ ` : `☐ `;
129
249
  if (!first?.text.startsWith(glyphPrefix)) return item;
130
250
  const strippedText = first.text.slice(glyphPrefix.length);
131
251
  const runs = strippedText.length === 0 ? item.runs.slice(1) : [{
@@ -137,49 +257,191 @@ function stripCheckboxRun(item, checkboxPrefix) {
137
257
  runs
138
258
  };
139
259
  }
140
- function renderListItemMarker(numId, info, item, context) {
141
- const checkboxText = (info?.task === true ? checkboxPrefixFor(item) : void 0) ?? "";
260
+ function toEmitItem(item) {
261
+ return item.kind === "paragraph" ? { block: item.block } : item.item;
262
+ }
263
+ function firstBlockCheckbox(first, taskNumId) {
264
+ if (first.list.checked !== void 0) return {
265
+ checkboxText: first.list.checked ? "[x] " : "[ ] ",
266
+ stripGlyph: false
267
+ };
268
+ if (!taskNumId || first.kind !== "paragraph") return {
269
+ checkboxText: "",
270
+ stripGlyph: false
271
+ };
272
+ const leading = first.block.runs[0]?.text ?? "";
273
+ if (leading.startsWith(`☒ `)) return {
274
+ checkboxText: "[x] ",
275
+ stripGlyph: true
276
+ };
277
+ if (leading.startsWith(`☐ `)) return {
278
+ checkboxText: "[ ] ",
279
+ stripGlyph: true
280
+ };
281
+ return {
282
+ checkboxText: "",
283
+ stripGlyph: false
284
+ };
285
+ }
286
+ function renderListItemMarker(numId, info, glyph, checkboxText, context) {
142
287
  if (info?.type === "ordered" && numId !== void 0) {
143
288
  const next = context.orderedCounters.get(numId) ?? info.start ?? 1;
144
289
  context.orderedCounters.set(numId, next + 1);
145
- const bare = `${String(next)}${context.orderedDelimiter} `;
290
+ const bare = `${String(next)}${glyph} `;
146
291
  return {
147
292
  full: `${bare}${checkboxText}`,
148
293
  bareLength: bare.length
149
294
  };
150
295
  }
151
- const bare = `${context.bulletMarker} `;
296
+ const bare = `${glyph} `;
152
297
  return {
153
298
  full: `${bare}${checkboxText}`,
154
299
  bareLength: bare.length
155
300
  };
156
301
  }
302
+ const BULLET_GLYPH_CANDIDATES = [
303
+ "-",
304
+ "+",
305
+ "*"
306
+ ];
307
+ const ORDERED_GLYPH_CANDIDATES = [".", ")"];
308
+ function resolveListGlyph(numId, type, previousSibling, context) {
309
+ const cached = context.resolvedListGlyphs.get(numId);
310
+ if (cached !== void 0) return cached;
311
+ const defaultGlyph = type === "ordered" ? context.orderedDelimiter : context.bulletMarker;
312
+ const glyph = previousSibling?.type === type && previousSibling.glyph === defaultGlyph ? (type === "ordered" ? ORDERED_GLYPH_CANDIDATES : BULLET_GLYPH_CANDIDATES).find((candidate) => candidate !== defaultGlyph) ?? defaultGlyph : defaultGlyph;
313
+ context.resolvedListGlyphs.set(numId, glyph);
314
+ return glyph;
315
+ }
316
+ function consumeSameItemRun(items, from, level, itemId) {
317
+ let end = from;
318
+ while (end < items.length) {
319
+ const candidate = items[end];
320
+ if (candidate?.list.level !== level || candidate.list.itemId !== itemId) break;
321
+ end += 1;
322
+ }
323
+ return end;
324
+ }
325
+ function collectListItem(items, start, level, itemId) {
326
+ const segments = [];
327
+ let index = start;
328
+ const ownEnd = itemId === void 0 ? index + 1 : consumeSameItemRun(items, index, level, itemId);
329
+ segments.push({
330
+ kind: "own",
331
+ blocks: items.slice(index, ownEnd)
332
+ });
333
+ index = ownEnd;
334
+ for (;;) {
335
+ let nestedEnd = index;
336
+ while (nestedEnd < items.length) {
337
+ const candidateLevel = items[nestedEnd]?.list.level;
338
+ if (candidateLevel === void 0 || candidateLevel <= level) break;
339
+ nestedEnd += 1;
340
+ }
341
+ if (nestedEnd === index) break;
342
+ segments.push({
343
+ kind: "nested",
344
+ blocks: items.slice(index, nestedEnd)
345
+ });
346
+ index = nestedEnd;
347
+ if (itemId === void 0) break;
348
+ const resumedEnd = consumeSameItemRun(items, index, level, itemId);
349
+ if (resumedEnd === index) break;
350
+ segments.push({
351
+ kind: "own",
352
+ blocks: items.slice(index, resumedEnd)
353
+ });
354
+ index = resumedEnd;
355
+ }
356
+ return {
357
+ segments,
358
+ next: index
359
+ };
360
+ }
361
+ function emitItemCanInterrupt(item, context) {
362
+ if (!isConstructItem(item)) return item.block.kind === "paragraph" ? canInterruptOpenParagraph(item.block, context) : true;
363
+ if (isMaterialisedDivision(item)) return true;
364
+ const first = item.children[0];
365
+ return first === void 0 ? true : emitItemCanInterrupt(first, context);
366
+ }
367
+ function lastStyleIdOf(item) {
368
+ if (isConstructItem(item)) {
369
+ const last = item.children[item.children.length - 1];
370
+ return last === void 0 ? void 0 : lastStyleIdOf(last);
371
+ }
372
+ return item.block.kind === "paragraph" ? item.block.styleId : void 0;
373
+ }
374
+ function regionItemCanInterrupt(item, context) {
375
+ return emitItemCanInterrupt(toEmitItem(item), context);
376
+ }
377
+ function lastStyleIdOfRegionItem(item) {
378
+ return lastStyleIdOf(toEmitItem(item));
379
+ }
380
+ function listRegionItemBody(item, context, stripGlyph) {
381
+ if (item.kind === "paragraph") return renderParagraphBody(stripGlyph ? stripCheckboxRun(item.block) : item.block, context);
382
+ const previousEnclosingItemId = context.enclosingItemId;
383
+ context.enclosingItemId = item.list.itemId;
384
+ const body = renderConstruct(item.item, context);
385
+ context.enclosingItemId = previousEnclosingItemId;
386
+ return body;
387
+ }
388
+ function requiresBlankLineBefore(next, previousStyleId, context) {
389
+ if (previousStyleId === "HTMLPreformatted") return true;
390
+ return !terminatesCleanly(previousStyleId) && !regionItemCanInterrupt(next, context);
391
+ }
157
392
  function renderListRegion(items, context) {
158
393
  const parts = [];
159
394
  let index = 0;
395
+ let previousSibling;
160
396
  while (index < items.length) {
161
397
  const item = items[index];
162
- if (item?.list === void 0) break;
163
- const { numId, level } = item.list;
398
+ if (item === void 0) break;
399
+ const { numId, level, itemId } = item.list;
164
400
  const info = listInfoFor(numId, context);
165
- let lookahead = index + 1;
166
- while (lookahead < items.length && (items[lookahead]?.list?.level ?? -1) > level) lookahead += 1;
167
- const nestedItems = items.slice(index + 1, lookahead);
168
- const checkboxPrefix = info?.task === true ? checkboxPrefixFor(item) : void 0;
169
- const marker = renderListItemMarker(numId, info, item, context);
170
- const bodyLines = renderParagraphBody(stripCheckboxRun(item, checkboxPrefix), context).split("\n");
401
+ const loose = info?.loose === true;
402
+ const type = info?.type ?? "bullet";
403
+ const glyph = numId === void 0 ? type === "ordered" ? context.orderedDelimiter : context.bulletMarker : resolveListGlyph(numId, type, previousSibling, context);
404
+ if (numId !== void 0) previousSibling = {
405
+ numId,
406
+ type,
407
+ glyph
408
+ };
409
+ const { segments, next } = collectListItem(items, index, level, itemId);
410
+ const first = segments[0]?.blocks[0];
411
+ if (first === void 0) break;
412
+ const { checkboxText, stripGlyph } = firstBlockCheckbox(first, info?.task === true);
413
+ const marker = renderListItemMarker(numId, info, glyph, checkboxText, context);
171
414
  const indent = " ".repeat(marker.bareLength);
172
- const [firstLine = "", ...restLines] = bodyLines;
173
- let text = [`${marker.full}${firstLine}`, ...restLines.map((line) => `${indent}${line}`)].join("\n");
174
- if (nestedItems.length > 0) {
175
- const nested = renderListRegion(nestedItems, context).split("\n").map((line) => line.length === 0 ? line : `${indent}${line}`).join("\n");
176
- text += `\n${nested}`;
415
+ let text = "";
416
+ let renderedFirstLine = false;
417
+ let previousStyleId;
418
+ for (const segment of segments) {
419
+ if (segment.kind === "nested") {
420
+ const nested = renderListRegion(segment.blocks, context).split("\n").map((line) => line.length === 0 ? line : `${indent}${line}`).join("\n");
421
+ text += `\n${nested}`;
422
+ const lastNested = segment.blocks[segment.blocks.length - 1];
423
+ previousStyleId = lastNested === void 0 ? void 0 : lastStyleIdOfRegionItem(lastNested);
424
+ continue;
425
+ }
426
+ for (const block of segment.blocks) {
427
+ if (!renderedFirstLine) {
428
+ const [firstLine = "", ...restLines] = listRegionItemBody(block, context, stripGlyph).split("\n");
429
+ text = [`${marker.full}${firstLine}`, ...restLines.map((line) => `${indent}${line}`)].join("\n");
430
+ renderedFirstLine = true;
431
+ previousStyleId = lastStyleIdOfRegionItem(block);
432
+ continue;
433
+ }
434
+ const rendered = listRegionItemBody(block, context, false).split("\n").map((line) => line.length === 0 ? line : `${indent}${line}`).join("\n");
435
+ const blank = loose || requiresBlankLineBefore(block, previousStyleId, context);
436
+ text += blank ? `\n\n${rendered}` : `\n${rendered}`;
437
+ previousStyleId = lastStyleIdOfRegionItem(block);
438
+ }
177
439
  }
178
440
  parts.push({
179
441
  numId,
180
442
  text
181
443
  });
182
- index = lookahead;
444
+ index = next;
183
445
  }
184
446
  let out = "";
185
447
  for (const [partIndex, part] of parts.entries()) {
@@ -196,6 +458,12 @@ function renderListRegion(items, context) {
196
458
  function isConstructItem(item) {
197
459
  return "descriptor" in item;
198
460
  }
461
+ function isMaterialisedDivision(item) {
462
+ return item.descriptor.kind === "division" && item.children.every((child) => {
463
+ if (isConstructItem(child)) return true;
464
+ return child.block.kind !== "paragraph" || child.block.indentLeftPt !== void 0 && child.block.indentLeftPt >= 36;
465
+ });
466
+ }
199
467
  function groupConstructItems(blocks, start) {
200
468
  const items = [];
201
469
  let index = start;
@@ -232,9 +500,9 @@ function renderFootnoteDefinition(name, body) {
232
500
  return [`${marker} ${firstLine}`, ...restLines.map((line) => line.length === 0 ? line : `${indent}${line}`)].join("\n");
233
501
  }
234
502
  function renderConstruct(item, context) {
235
- const body = renderItems(item.children, context);
236
503
  const { descriptor } = item;
237
504
  if (descriptor.kind === "anchor" && descriptor.anchorType === "footnote") {
505
+ const body = renderItems(item.children, context);
238
506
  if (isValidFootnoteLabel(descriptor.name)) return renderFootnoteDefinition(descriptor.name, body);
239
507
  context.sink({
240
508
  code: MarkdownDiagnosticCodes.CONSTRUCT_UNREPRESENTED,
@@ -243,6 +511,20 @@ function renderConstruct(item, context) {
243
511
  });
244
512
  return body;
245
513
  }
514
+ if (descriptor.kind === "division") {
515
+ if (isMaterialisedDivision(item)) {
516
+ context.divisionDepth += 1;
517
+ const body = renderItems(item.children, context);
518
+ context.divisionDepth -= 1;
519
+ return body.split("\n").map((line) => line.length === 0 ? ">" : `> ${line}`).join("\n");
520
+ }
521
+ }
522
+ if (descriptor.kind === "link" && descriptor.target.kind === "external") {
523
+ const onlyChild = item.children.length === 1 && !isConstructItem(item.children[0]) ? item.children[0].block : void 0;
524
+ if (onlyChild?.kind === "image" && !isDataUri(descriptor.target.uri)) return `![${escapeMarkdownText(onlyChild.altText ?? "")}](${escapeLinkDestination(descriptor.target.uri)}${descriptor.title === void 0 ? "" : ` "${renderLinkTitle(descriptor.title)}"`})`;
525
+ if (onlyChild?.kind === "image" && isDataUri(descriptor.target.uri) && !context.embedImages) return emitImage(onlyChild, false);
526
+ }
527
+ const body = renderItems(item.children, context);
246
528
  const detail = descriptor.kind === "anchor" ? `${descriptor.kind} (${descriptor.anchorType})` : descriptor.kind;
247
529
  context.sink({
248
530
  code: MarkdownDiagnosticCodes.CONSTRUCT_UNREPRESENTED,
@@ -251,6 +533,18 @@ function renderConstruct(item, context) {
251
533
  });
252
534
  return body;
253
535
  }
536
+ function constructCarriesListItemId(item, itemId) {
537
+ return item.children.some((child) => {
538
+ if (isConstructItem(child)) return constructCarriesListItemId(child, itemId);
539
+ if (child.block.kind !== "paragraph") return false;
540
+ const list = child.block.list;
541
+ if (list?.itemId === itemId) return true;
542
+ return list?.numId !== void 0 && parseListNumId(list.numId)?.ownerItemId === itemId;
543
+ });
544
+ }
545
+ function isInheritedListMembership(list, context) {
546
+ return list.itemId !== void 0 && list.itemId === context.enclosingItemId;
547
+ }
254
548
  function renderItems(items, context) {
255
549
  const parts = [];
256
550
  let index = 0;
@@ -263,11 +557,40 @@ function renderItems(items, context) {
263
557
  index += 1;
264
558
  continue;
265
559
  }
266
- if (item.block.kind === "paragraph" && item.block.list !== void 0) {
560
+ if (item.block.kind === "paragraph" && item.block.list !== void 0 && !isInheritedListMembership(item.block.list, context)) {
267
561
  const region = [];
268
562
  let end = index;
269
- for (let candidate = items[end]; candidate !== void 0 && !isConstructItem(candidate) && candidate.block.kind === "paragraph" && candidate.block.list !== void 0; candidate = items[end]) {
270
- region.push(candidate.block);
563
+ const openMemberships = [];
564
+ for (;;) {
565
+ const candidate = items[end];
566
+ if (candidate === void 0) break;
567
+ if (isConstructItem(candidate)) {
568
+ let matched;
569
+ for (let i = openMemberships.length - 1; i >= 0; i -= 1) {
570
+ const membership = openMemberships[i];
571
+ if (membership.itemId !== void 0 && constructCarriesListItemId(candidate, membership.itemId)) {
572
+ matched = membership;
573
+ break;
574
+ }
575
+ }
576
+ if (matched === void 0) break;
577
+ region.push({
578
+ kind: "construct",
579
+ item: candidate,
580
+ list: matched
581
+ });
582
+ end += 1;
583
+ continue;
584
+ }
585
+ if (candidate.block.kind !== "paragraph" || candidate.block.list === void 0 || isInheritedListMembership(candidate.block.list, context)) break;
586
+ const list = candidate.block.list;
587
+ while (openMemberships.length > 0 && openMemberships[openMemberships.length - 1].level >= list.level) openMemberships.pop();
588
+ openMemberships.push(list);
589
+ region.push({
590
+ kind: "paragraph",
591
+ block: candidate.block,
592
+ list
593
+ });
271
594
  end += 1;
272
595
  }
273
596
  parts.push(renderListRegion(region, context));
@@ -283,8 +606,18 @@ function renderItems(items, context) {
283
606
  function emitBlocks(blocks, context) {
284
607
  const imbalance = findConstructMarkerImbalance(blocks);
285
608
  if (imbalance !== void 0) throw new MarkdownUnbalancedConstructMarkersError(imbalance.kind, imbalance.index);
609
+ validateRunConstructExtents(blocks);
286
610
  return renderItems(groupConstructItems(blocks, 0).items, context);
287
611
  }
612
+ function validateRunConstructExtents(blocks) {
613
+ for (const block of blocks) {
614
+ if (block.kind === "paragraph" && block.constructs !== void 0) {
615
+ const fault = findRunConstructFault(block);
616
+ if (fault !== void 0) throw new MarkdownInvalidRunConstructExtentError(fault.kind, fault.index);
617
+ }
618
+ if (block.kind === "table") for (const row of block.rows) for (const cell of row.cells) validateRunConstructExtents(cell.blocks);
619
+ }
620
+ }
288
621
  function emitMarkdown(document, options = {}) {
289
622
  if (document.kind !== "wordprocessing") throw new MarkdownUnsupportedDocumentKindError(document.kind);
290
623
  const context = {
@@ -297,8 +630,11 @@ function emitMarkdown(document, options = {}) {
297
630
  headingStyle: options.headingStyle ?? "atx",
298
631
  embedImages: options.images ?? true,
299
632
  orderedCounters: /* @__PURE__ */ new Map(),
633
+ resolvedListGlyphs: /* @__PURE__ */ new Map(),
300
634
  reportedFallbackNumIds: /* @__PURE__ */ new Set(),
301
- reportedAbsentNumIdFallback: false
635
+ reportedAbsentNumIdFallback: false,
636
+ divisionDepth: 0,
637
+ enclosingItemId: void 0
302
638
  };
303
639
  const body = document.sections.map((section) => emitBlocks(section.blocks, context)).join("\n\n");
304
640
  const frontMatter = options.frontMatter === true ? emitFrontMatter(document.metadata) : void 0;
@@ -5,13 +5,30 @@ function emitScalar(value) {
5
5
  if (!NEEDS_QUOTING_PATTERN.test(value) && value.trim() === value && value.length > 0) return value;
6
6
  return `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`;
7
7
  }
8
+ const STRING_FIELD_ENTRIES = [
9
+ ["title", (metadata) => metadata.title],
10
+ ["author", (metadata) => metadata.author],
11
+ ["subject", (metadata) => metadata.subject],
12
+ ["creator", (metadata) => metadata.creator],
13
+ ["date", (metadata) => metadata.createdIso],
14
+ ["modified", (metadata) => metadata.modifiedIso],
15
+ ["lastPrinted", (metadata) => metadata.lastPrintedIso],
16
+ ["language", (metadata) => metadata.language],
17
+ ["publisher", (metadata) => metadata.publisher],
18
+ ["contributor", (metadata) => metadata.contributor],
19
+ ["rights", (metadata) => metadata.rights],
20
+ ["identifier", (metadata) => metadata.identifier],
21
+ ["comments", (metadata) => metadata.comments],
22
+ ["company", (metadata) => metadata.company],
23
+ ["manager", (metadata) => metadata.manager]
24
+ ];
8
25
  function emitFrontMatter(metadata) {
9
26
  const lines = [];
10
- if (metadata.title !== void 0) lines.push(`title: ${emitScalar(metadata.title)}`);
11
- if (metadata.author !== void 0) lines.push(`author: ${emitScalar(metadata.author)}`);
12
- if (metadata.subject !== void 0) lines.push(`subject: ${emitScalar(metadata.subject)}`);
13
- if (metadata.creator !== void 0) lines.push(`creator: ${emitScalar(metadata.creator)}`);
14
- if (metadata.createdIso !== void 0) lines.push(`date: ${emitScalar(metadata.createdIso)}`);
27
+ for (const [key, accessor] of STRING_FIELD_ENTRIES) {
28
+ const value = accessor(metadata);
29
+ if (value !== void 0) lines.push(`${key}: ${emitScalar(value)}`);
30
+ }
31
+ if (metadata.direction !== void 0) lines.push(`direction: ${metadata.direction}`);
15
32
  if (metadata.keywords !== void 0 && metadata.keywords.length > 0) lines.push(`keywords: [${metadata.keywords.map((keyword) => emitScalar(keyword)).join(", ")}]`);
16
33
  if (lines.length === 0) return;
17
34
  return [
@@ -4,13 +4,30 @@ function emitScalar(value) {
4
4
  if (!NEEDS_QUOTING_PATTERN.test(value) && value.trim() === value && value.length > 0) return value;
5
5
  return `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`;
6
6
  }
7
+ const STRING_FIELD_ENTRIES = [
8
+ ["title", (metadata) => metadata.title],
9
+ ["author", (metadata) => metadata.author],
10
+ ["subject", (metadata) => metadata.subject],
11
+ ["creator", (metadata) => metadata.creator],
12
+ ["date", (metadata) => metadata.createdIso],
13
+ ["modified", (metadata) => metadata.modifiedIso],
14
+ ["lastPrinted", (metadata) => metadata.lastPrintedIso],
15
+ ["language", (metadata) => metadata.language],
16
+ ["publisher", (metadata) => metadata.publisher],
17
+ ["contributor", (metadata) => metadata.contributor],
18
+ ["rights", (metadata) => metadata.rights],
19
+ ["identifier", (metadata) => metadata.identifier],
20
+ ["comments", (metadata) => metadata.comments],
21
+ ["company", (metadata) => metadata.company],
22
+ ["manager", (metadata) => metadata.manager]
23
+ ];
7
24
  function emitFrontMatter(metadata) {
8
25
  const lines = [];
9
- if (metadata.title !== void 0) lines.push(`title: ${emitScalar(metadata.title)}`);
10
- if (metadata.author !== void 0) lines.push(`author: ${emitScalar(metadata.author)}`);
11
- if (metadata.subject !== void 0) lines.push(`subject: ${emitScalar(metadata.subject)}`);
12
- if (metadata.creator !== void 0) lines.push(`creator: ${emitScalar(metadata.creator)}`);
13
- if (metadata.createdIso !== void 0) lines.push(`date: ${emitScalar(metadata.createdIso)}`);
26
+ for (const [key, accessor] of STRING_FIELD_ENTRIES) {
27
+ const value = accessor(metadata);
28
+ if (value !== void 0) lines.push(`${key}: ${emitScalar(value)}`);
29
+ }
30
+ if (metadata.direction !== void 0) lines.push(`direction: ${metadata.direction}`);
14
31
  if (metadata.keywords !== void 0 && metadata.keywords.length > 0) lines.push(`keywords: [${metadata.keywords.map((keyword) => emitScalar(keyword)).join(", ")}]`);
15
32
  if (lines.length === 0) return;
16
33
  return [