@drghaliasri/butex 8.0.3 → 8.1.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.
package/dist/document.js CHANGED
@@ -47,6 +47,8 @@ __export(public_exports, {
47
47
  arabicXeLatexPreamblePkg: () => arabicXeLatexPreamblePkg,
48
48
  bibliographyEntryBody: () => bibliographyEntryBody,
49
49
  bibliographyEntryLatex: () => bibliographyEntryLatex,
50
+ bookContentTargets: () => bookContentTargets,
51
+ bookContextReferences: () => bookContextReferences,
50
52
  butexBasmalaDisplayLatex: () => butexBasmalaDisplayLatex,
51
53
  butexBasmalaDisplayTex: () => butexBasmalaDisplayTex,
52
54
  butexBasmalaTitlingPreamble: () => butexBasmalaTitlingPreamble,
@@ -59,7 +61,9 @@ __export(public_exports, {
59
61
  clearDocumentImageAsset: () => clearDocumentImageAsset,
60
62
  cloneDocumentMeta: () => cloneDocumentMeta,
61
63
  cloneDocumentNode: () => cloneDocumentNode,
64
+ collectDocumentKeyLabels: () => collectDocumentKeyLabels,
62
65
  collectDocumentLabels: () => collectDocumentLabels,
66
+ collectDocumentReferenceTargets: () => collectDocumentReferenceTargets,
63
67
  createDocumentHistory: () => createDocumentHistory,
64
68
  createEmptyArabicEquationSession: () => createEmptyArabicEquationSession,
65
69
  createEmptyDocument: () => createEmptyDocument,
@@ -70,6 +74,7 @@ __export(public_exports, {
70
74
  detectInlineSpans: () => detectInlineSpans,
71
75
  detectMathSpans: () => detectMathSpans,
72
76
  diffDocument: () => diffDocument,
77
+ documentContentLatex: () => documentContentLatex2,
73
78
  documentHasAbstract: () => documentHasAbstract,
74
79
  documentHasMaketitle: () => documentHasMaketitle,
75
80
  documentHasTitleStack: () => documentHasTitleStack,
@@ -86,6 +91,7 @@ __export(public_exports, {
86
91
  fillDocumentMetaGaps: () => fillDocumentMetaGaps,
87
92
  findFirstInlineField: () => findFirstInlineField,
88
93
  formatBibliographyNumber: () => formatBibliographyNumber,
94
+ formatBookReferenceLabel: () => formatBookReferenceLabel,
89
95
  formatCiteLabel: () => formatCiteLabel,
90
96
  formatFloatCaptionPreview: () => formatFloatCaptionPreview,
91
97
  formatFloatCaptionTitle: () => formatFloatCaptionTitle,
@@ -97,6 +103,8 @@ __export(public_exports, {
97
103
  getDocumentReferences: () => getDocumentReferences,
98
104
  hasXeLatexUnsupportedEmoji: () => hasXeLatexUnsupportedEmoji,
99
105
  hijriMonthLabel: () => hijriMonthLabel,
106
+ implicitHeadingReferenceKey: () => implicitHeadingReferenceKey,
107
+ implicitReferenceKey: () => implicitReferenceKey,
100
108
  inlineFieldLatex: () => inlineFieldLatex,
101
109
  insertCiteTokenAtCaret: () => insertCiteTokenAtCaret,
102
110
  insertDocumentBlockAfter: () => insertDocumentBlockAfter,
@@ -105,6 +113,8 @@ __export(public_exports, {
105
113
  insertRefTokenAtCaret: () => insertRefTokenAtCaret,
106
114
  isDocumentValid: () => isDocumentValid,
107
115
  isDuplicateDocumentKey: () => isDuplicateDocumentKey,
116
+ isNumberedEquation: () => isNumberedEquation,
117
+ isNumberedFloat: () => isNumberedFloat,
108
118
  isValidDocumentKey: () => isValidDocumentKey,
109
119
  labelNumberMap: () => labelNumberMap,
110
120
  mathNodeFromArabicSession: () => mathNodeFromArabicSession,
@@ -148,6 +158,7 @@ __export(public_exports, {
148
158
  toggleBlockInSelection: () => toggleBlockInSelection,
149
159
  toggleTextTokenStyle: () => toggleTextTokenStyle,
150
160
  updateCiteTokenKeys: () => updateCiteTokenKeys,
161
+ updateDocumentHeadingLabel: () => updateDocumentHeadingLabel,
151
162
  updateDocumentImageAsset: () => updateDocumentImageAsset,
152
163
  updateDocumentImageMeta: () => updateDocumentImageMeta,
153
164
  updateDocumentImageValue: () => updateDocumentImageValue,
@@ -1015,82 +1026,91 @@ function refTokenLatex(keys, refCommand) {
1015
1026
  const command = refCommand === "eqref" ? "\\eqref" : "\\ref";
1016
1027
  return `${command}{${keys.join(",")}}`;
1017
1028
  }
1018
- function collectDocumentLabels(document2) {
1019
- const entries = [];
1029
+ function implicitObjectKey(kind, ownerId, unitId) {
1030
+ const hex = (value) => Array.from(new TextEncoder().encode(value), (byte) => byte.toString(16).padStart(2, "0")).join("");
1031
+ const scope = unitId === void 0 ? "a" : "u" + hex(unitId);
1032
+ return kind + ":butex-auto-" + scope + "-" + hex(ownerId);
1033
+ }
1034
+ function implicitReferenceKey(kind, ownerId, unitId) {
1035
+ return implicitObjectKey(kind, ownerId, unitId);
1036
+ }
1037
+ function implicitHeadingReferenceKey(kind, ownerId, unitId) {
1038
+ return implicitObjectKey(kind, ownerId, unitId);
1039
+ }
1040
+ function supportsSingleEquationNumbering(token) {
1041
+ return token.display && (token.opening === "\\[" || token.opening === String.fromCharCode(36, 36) || token.opening === "\\begin{equation}" || token.opening === "\\begin{equation*}");
1042
+ }
1043
+ function isNumberedEquation(token) {
1044
+ if (!supportsSingleEquationNumbering(token)) return false;
1045
+ if (typeof token.numbered === "boolean") return token.numbered;
1046
+ return token.opening === "\\begin{equation}" || Boolean(token.labelEnabled) && Boolean(token.label?.trim());
1047
+ }
1048
+ function isNumberedFloat(block) {
1049
+ return block.captionEnabled && block.caption.trim().length > 0 || block.labelEnabled && block.label.trim().length > 0;
1050
+ }
1051
+ function collectDocumentReferenceTargets(document2) {
1052
+ const targets = [];
1020
1053
  const counters = { fig: 0, tab: 0, eq: 0 };
1021
- function pushEqFromField(tokens) {
1022
- for (const token of tokens) {
1023
- if (token.kind !== "math") {
1024
- continue;
1025
- }
1026
- if (token.display && token.labelEnabled && token.label && token.label.trim().length > 0) {
1027
- counters.eq += 1;
1028
- entries.push({
1029
- key: token.label.trim(),
1030
- kind: "eq",
1031
- caption: "",
1032
- ownerId: token.id,
1033
- number: counters.eq
1034
- });
1054
+ function append(kind, ownerId, caption, numbered, manualKey = "") {
1055
+ if (numbered) counters[kind] += 1;
1056
+ targets.push({
1057
+ key: implicitReferenceKey(kind, ownerId),
1058
+ kind,
1059
+ ownerId,
1060
+ caption,
1061
+ number: numbered ? counters[kind] : null,
1062
+ ...manualKey.trim() ? { manualKey: manualKey.trim() } : {}
1063
+ });
1064
+ }
1065
+ function visitField(field) {
1066
+ for (const token of field.tokens) {
1067
+ if (token.kind === "math" && supportsSingleEquationNumbering(token)) {
1068
+ append("eq", token.id, "", isNumberedEquation(token), token.labelEnabled ? token.label ?? "" : "");
1035
1069
  }
1036
1070
  }
1037
1071
  }
1038
1072
  function walk(blocks) {
1039
1073
  for (const block of blocks) {
1040
- if (block.kind === "image") {
1041
- if (block.labelEnabled && block.label.trim().length > 0) {
1042
- counters.fig += 1;
1043
- entries.push({
1044
- key: block.label.trim(),
1045
- kind: "fig",
1046
- caption: block.captionEnabled ? block.caption : "",
1047
- ownerId: block.id,
1048
- number: counters.fig
1049
- });
1050
- }
1051
- if (block.captionEnabled) {
1052
- pushEqFromField(block.captionField.tokens);
1053
- }
1054
- }
1055
- if (block.kind === "table") {
1056
- if (block.labelEnabled && block.label.trim().length > 0) {
1057
- counters.tab += 1;
1058
- entries.push({
1059
- key: block.label.trim(),
1060
- kind: "tab",
1061
- caption: block.captionEnabled ? block.caption : "",
1062
- ownerId: block.id,
1063
- number: counters.tab
1064
- });
1065
- }
1066
- if (block.captionEnabled) {
1067
- pushEqFromField(block.captionField.tokens);
1068
- }
1069
- for (const row of block.rows) {
1070
- for (const cell of row) {
1071
- pushEqFromField(cell.tokens);
1072
- }
1074
+ if (block.kind === "image" || block.kind === "table") {
1075
+ append(
1076
+ block.kind === "image" ? "fig" : "tab",
1077
+ block.id,
1078
+ block.captionEnabled ? block.caption : "",
1079
+ isNumberedFloat(block),
1080
+ block.labelEnabled ? block.label : ""
1081
+ );
1082
+ if (block.captionEnabled) visitField(block.captionField);
1083
+ if (block.kind === "table") {
1084
+ for (const row of block.rows) for (const cell of row) visitField(cell);
1073
1085
  }
1074
- }
1075
- if (block.kind === "textBlock") {
1076
- pushEqFromField(block.field.tokens);
1077
- }
1078
- if (block.kind === "list") {
1086
+ } else if (block.kind === "textBlock") {
1087
+ visitField(block.field);
1088
+ } else if (block.kind === "list") {
1079
1089
  for (const item of block.items) {
1080
- pushEqFromField(item.field.tokens);
1090
+ visitField(item.field);
1081
1091
  walk(item.blocks);
1082
1092
  }
1083
1093
  }
1084
1094
  }
1085
1095
  }
1086
1096
  walk(document2.blocks);
1087
- return entries;
1097
+ return targets;
1098
+ }
1099
+ function collectDocumentLabels(document2) {
1100
+ return collectDocumentReferenceTargets(document2).filter((target) => target.number !== null && Boolean(target.manualKey)).map(({ manualKey, kind, caption, ownerId, number }) => ({ key: manualKey, kind, caption, ownerId, number }));
1101
+ }
1102
+ function collectDocumentKeyLabels(document2) {
1103
+ return collectDocumentReferenceTargets(document2).filter((target) => target.number !== null).flatMap((target) => [
1104
+ { key: target.key, ownerId: target.ownerId },
1105
+ ...target.manualKey && target.manualKey !== target.key ? [{ key: target.manualKey, ownerId: target.ownerId }] : []
1106
+ ]);
1088
1107
  }
1089
1108
  function labelNumberMap(document2) {
1090
1109
  const map = /* @__PURE__ */ new Map();
1091
- for (const entry of collectDocumentLabels(document2)) {
1092
- if (!map.has(entry.key)) {
1093
- map.set(entry.key, { kind: entry.kind, number: entry.number });
1110
+ for (const target of collectDocumentReferenceTargets(document2)) {
1111
+ if (target.number === null) continue;
1112
+ for (const key of [target.key, target.manualKey]) {
1113
+ if (key && !map.has(key)) map.set(key, { kind: target.kind, number: target.number });
1094
1114
  }
1095
1115
  }
1096
1116
  return map;
@@ -1144,8 +1164,12 @@ function stripDisplayMathDelimiters(source) {
1144
1164
  if (trimmed.startsWith("$$") && trimmed.endsWith("$$")) {
1145
1165
  return trimmed.slice(2, -2).trim();
1146
1166
  }
1147
- if (trimmed.startsWith("\\begin{equation}") && trimmed.endsWith("\\end{equation}")) {
1148
- return trimmed.slice("\\begin{equation}".length, -"\\end{equation}".length).trim();
1167
+ for (const environment of ["equation", "equation*"]) {
1168
+ const opening = `\\begin{${environment}}`;
1169
+ const closing = `\\end{${environment}}`;
1170
+ if (trimmed.startsWith(opening) && trimmed.endsWith(closing)) {
1171
+ return trimmed.slice(opening.length, -closing.length).trim();
1172
+ }
1149
1173
  }
1150
1174
  return trimmed;
1151
1175
  }
@@ -1538,7 +1562,8 @@ function createInlineField(value = "", mathObjects = [], options = {}, path = "$
1538
1562
  editable: true,
1539
1563
  sourceOwner: structuredMathJson.source_owner === "editor" ? "editor" : "imported-structured",
1540
1564
  ...typeof structuredMathJson.label_enabled === "boolean" ? { labelEnabled: structuredMathJson.label_enabled } : {},
1541
- ...typeof structuredMathJson.label === "string" ? { label: structuredMathJson.label } : {}
1565
+ ...typeof structuredMathJson.label === "string" ? { label: structuredMathJson.label } : {},
1566
+ ...typeof structuredMathJson.numbered === "boolean" ? { numbered: structuredMathJson.numbered } : {}
1542
1567
  });
1543
1568
  } else {
1544
1569
  tokens.push({
@@ -1553,7 +1578,8 @@ function createInlineField(value = "", mathObjects = [], options = {}, path = "$
1553
1578
  reason: "\u0647\u0630\u0647 \u0627\u0644\u0645\u0639\u0627\u062F\u0644\u0629 \u0645\u062D\u0641\u0648\u0638\u0629 \u0643\u0646\u0635 \u062E\u0627\u0645 \u0641\u0642\u0637 \u062D\u0627\u0644\u064A\u0627",
1554
1579
  sourceOwner: "raw",
1555
1580
  ...mathJson?.node_type === "RawMathObject" && typeof mathJson.label_enabled === "boolean" ? { labelEnabled: mathJson.label_enabled } : {},
1556
- ...mathJson?.node_type === "RawMathObject" && typeof mathJson.label === "string" ? { label: mathJson.label } : {}
1581
+ ...mathJson?.node_type === "RawMathObject" && typeof mathJson.label === "string" ? { label: mathJson.label } : {},
1582
+ ...mathJson?.node_type === "RawMathObject" && typeof mathJson.numbered === "boolean" ? { numbered: mathJson.numbered } : {}
1557
1583
  });
1558
1584
  }
1559
1585
  index = span.end;
@@ -1650,6 +1676,7 @@ function parseTextBlock(json, options, path, diagnostics, identities) {
1650
1676
  identities
1651
1677
  ),
1652
1678
  ...metadataFromJson(json.metadata),
1679
+ ...typeof json.label === "string" && json.command !== "\\paragraph" ? { label: json.label } : {},
1653
1680
  ...json.centered === true ? { centered: true } : {}
1654
1681
  };
1655
1682
  }
@@ -5607,6 +5634,9 @@ function replaceMathTokenFromSession(document2, tokenId, session, opening, closi
5607
5634
  if (current.label !== void 0) {
5608
5635
  replaced.label = current.label;
5609
5636
  }
5637
+ if (current.numbered !== void 0) {
5638
+ replaced.numbered = current.numbered;
5639
+ }
5610
5640
  field.tokens[index] = replaced;
5611
5641
  return true;
5612
5642
  });
@@ -5643,6 +5673,24 @@ function updateDocumentTextBlockCentered(document2, blockId, centered) {
5643
5673
  visit(next.blocks);
5644
5674
  return next;
5645
5675
  }
5676
+ function updateDocumentHeadingLabel(document2, blockId, label) {
5677
+ const next = cloneDocument(document2);
5678
+ function visit(blocks) {
5679
+ for (const block of blocks) {
5680
+ if (block.id === blockId && block.kind === "textBlock" && block.command !== "\\paragraph") {
5681
+ if (label.trim()) block.label = label.trim();
5682
+ else delete block.label;
5683
+ return true;
5684
+ }
5685
+ if (block.kind === "list") {
5686
+ for (const item of block.items) if (visit(item.blocks)) return true;
5687
+ }
5688
+ }
5689
+ return false;
5690
+ }
5691
+ visit(next.blocks);
5692
+ return next;
5693
+ }
5646
5694
  function removeDocumentBlockById(document2, blockId) {
5647
5695
  const next = cloneDocument(document2);
5648
5696
  next.blocks = next.blocks.filter((block) => block.id !== blockId);
@@ -5831,6 +5879,9 @@ function updateMathTokenLabel(document2, tokenId, patch) {
5831
5879
  if (typeof patch.label === "string") {
5832
5880
  token.label = patch.label;
5833
5881
  }
5882
+ if (typeof patch.numbered === "boolean") {
5883
+ token.numbered = patch.numbered;
5884
+ }
5834
5885
  return true;
5835
5886
  });
5836
5887
  return next;
@@ -6139,7 +6190,7 @@ function normalizedNewFloatLabel(document2, label) {
6139
6190
  if (!normalized) return "";
6140
6191
  const error = documentKeyError(normalized, {
6141
6192
  references: document2.references,
6142
- labels: collectDocumentLabels(document2)
6193
+ labels: collectDocumentKeyLabels(document2)
6143
6194
  });
6144
6195
  if (error === "duplicate") {
6145
6196
  throw new DocumentCommandError("duplicate_key", "Float label is already in use");
@@ -6583,7 +6634,7 @@ function validateReferenceKey(document2, key, excludeReferenceId) {
6583
6634
  const normalized = normalizeDocumentKey(key);
6584
6635
  const error = documentKeyError(normalized, {
6585
6636
  references: document2.references,
6586
- labels: collectDocumentLabels(document2),
6637
+ labels: collectDocumentKeyLabels(document2),
6587
6638
  ...excludeReferenceId ? { excludeReferenceId } : {}
6588
6639
  });
6589
6640
  if (error === "duplicate") {
@@ -6805,6 +6856,17 @@ function parseToken(value) {
6805
6856
  throw new DocumentCommandError("invalid_inline_token", "Unsupported inline token kind");
6806
6857
  }
6807
6858
  function parseInlineCommand(value) {
6859
+ if (value.op === "set_equation_numbering") {
6860
+ if (typeof value.numbered !== "boolean") {
6861
+ throw new DocumentCommandError("invalid_command", "numbered must be boolean");
6862
+ }
6863
+ return {
6864
+ op: "set_equation_numbering",
6865
+ field_id: requireString2(value.field_id, "field_id", false).trim(),
6866
+ token_id: requireString2(value.token_id, "token_id", false).trim(),
6867
+ numbered: value.numbered
6868
+ };
6869
+ }
6808
6870
  if (value.op === "insert_inline_token") {
6809
6871
  return {
6810
6872
  op: value.op,
@@ -6858,7 +6920,8 @@ function liveToken(input, id) {
6858
6920
  editable: true,
6859
6921
  sourceOwner: mathObject.source_owner === "editor" ? "editor" : "imported-structured",
6860
6922
  ...mathObject.label_enabled !== void 0 ? { labelEnabled: mathObject.label_enabled } : {},
6861
- ...mathObject.label !== void 0 ? { label: mathObject.label } : {}
6923
+ ...mathObject.label !== void 0 ? { label: mathObject.label } : {},
6924
+ ...mathObject.numbered !== void 0 ? { numbered: mathObject.numbered } : {}
6862
6925
  };
6863
6926
  }
6864
6927
  function insertionIndex(tokens, anchor) {
@@ -6880,6 +6943,17 @@ function applyInlineCommand(document2, command) {
6880
6943
  if (!field) {
6881
6944
  throw new DocumentCommandError("field_not_found", "Inline field was not found");
6882
6945
  }
6946
+ if (command.op === "set_equation_numbering") {
6947
+ const token = field.tokens.find((entry) => entry.id === command.token_id);
6948
+ if (!token || token.kind !== "math") {
6949
+ throw new DocumentCommandError("token_not_found", "Equation token was not found");
6950
+ }
6951
+ if (!supportsSingleEquationNumbering(token)) {
6952
+ throw new DocumentCommandError("invalid_inline_token", "Only a single display equation can be numbered");
6953
+ }
6954
+ token.numbered = command.numbered;
6955
+ return;
6956
+ }
6883
6957
  if (command.op === "insert_inline_token") {
6884
6958
  const index2 = insertionIndex(field.tokens, command.anchor);
6885
6959
  field.tokens.splice(index2, 0, liveToken(command.token, newTokenId(document2, command.token.kind)));
@@ -7232,12 +7306,13 @@ function serializeField(field) {
7232
7306
  }
7233
7307
  value += token.source;
7234
7308
  if (!token.math || token.sourceOwner === "raw") {
7235
- if (token.labelEnabled !== void 0 || token.label !== void 0) {
7309
+ if (token.labelEnabled !== void 0 || token.label !== void 0 || token.numbered !== void 0) {
7236
7310
  hasPersistedMath = true;
7237
7311
  mathObjects.push({
7238
7312
  node_type: "RawMathObject",
7239
7313
  ...token.labelEnabled !== void 0 ? { label_enabled: token.labelEnabled } : {},
7240
- ...token.label !== void 0 ? { label: token.label } : {}
7314
+ ...token.label !== void 0 ? { label: token.label } : {},
7315
+ ...token.numbered !== void 0 ? { numbered: token.numbered } : {}
7241
7316
  });
7242
7317
  } else {
7243
7318
  mathObjects.push(null);
@@ -7250,7 +7325,8 @@ function serializeField(field) {
7250
7325
  ...token.sourceSide ? { source_side: token.sourceSide } : {},
7251
7326
  source_owner: token.sourceOwner,
7252
7327
  ...token.labelEnabled !== void 0 ? { label_enabled: token.labelEnabled } : {},
7253
- ...token.label !== void 0 ? { label: token.label } : {}
7328
+ ...token.label !== void 0 ? { label: token.label } : {},
7329
+ ...token.numbered !== void 0 ? { numbered: token.numbered } : {}
7254
7330
  });
7255
7331
  }
7256
7332
  return { value, formats, mathObjects, hasPersistedMath, inlineIds: inlineIdsFromField(field) };
@@ -7290,6 +7366,7 @@ function blockJson(block) {
7290
7366
  id: block.id,
7291
7367
  command: block.command,
7292
7368
  ...fieldJson(block.field),
7369
+ ...block.command !== "\\paragraph" && block.label ? { label: block.label } : {},
7293
7370
  ...block.metadata ? { metadata: { ...block.metadata } } : {},
7294
7371
  ...block.command === "\\paragraph" ? { centered: block.centered === true } : {}
7295
7372
  };
@@ -7383,7 +7460,7 @@ function toDocumentJson(document2) {
7383
7460
 
7384
7461
  // src/document/jsonCommands.ts
7385
7462
  function isInlineCommand(command) {
7386
- return command.op === "insert_inline_token" || command.op === "replace_inline_token" || command.op === "remove_inline_token";
7463
+ return command.op === "insert_inline_token" || command.op === "replace_inline_token" || command.op === "remove_inline_token" || command.op === "set_equation_numbering";
7387
7464
  }
7388
7465
  function isListCommand(command) {
7389
7466
  return command.op === "insert_list" || command.op === "insert_list_item" || command.op === "replace_list_item" || command.op === "remove_list_item" || command.op === "move_list_item";
@@ -7418,6 +7495,13 @@ function parseBasicCommand(value) {
7418
7495
  text: requireString2(value.text, "text")
7419
7496
  };
7420
7497
  }
7498
+ if (value.op === "set_heading_label") {
7499
+ return {
7500
+ op: value.op,
7501
+ block_id: requireString2(value.block_id, "block_id", false).trim(),
7502
+ label: value.label === null ? null : requireString2(value.label, "label")
7503
+ };
7504
+ }
7421
7505
  if (value.op === "remove_block") {
7422
7506
  return { op: value.op, block_id: requireString2(value.block_id, "block_id", false).trim() };
7423
7507
  }
@@ -7498,7 +7582,7 @@ function parseCommand2(value) {
7498
7582
  if (!isObject3(value) || typeof value.op !== "string") {
7499
7583
  throw new DocumentCommandError("invalid_command", "command requires an op");
7500
7584
  }
7501
- if (value.op === "insert_inline_token" || value.op === "replace_inline_token" || value.op === "remove_inline_token") {
7585
+ if (value.op === "insert_inline_token" || value.op === "replace_inline_token" || value.op === "remove_inline_token" || value.op === "set_equation_numbering") {
7502
7586
  return parseInlineCommand(value);
7503
7587
  }
7504
7588
  if (value.op === "insert_list" || value.op === "insert_list_item" || value.op === "replace_list_item" || value.op === "remove_list_item" || value.op === "move_list_item") {
@@ -7510,7 +7594,7 @@ function parseCommand2(value) {
7510
7594
  if (value.op === "update_document_meta" || value.op === "insert_reference" || value.op === "update_reference" || value.op === "remove_reference" || value.op === "move_reference") {
7511
7595
  return parseArticleCommand(value);
7512
7596
  }
7513
- if (value.op === "insert_text_block" || value.op === "replace_text_block" || value.op === "remove_block" || value.op === "move_block" || value.op === "insert_figure" || value.op === "update_figure" || value.op === "update_float_meta" || value.op === "insert_bibliography") {
7597
+ if (value.op === "insert_text_block" || value.op === "replace_text_block" || value.op === "set_heading_label" || value.op === "remove_block" || value.op === "move_block" || value.op === "insert_figure" || value.op === "update_figure" || value.op === "update_float_meta" || value.op === "insert_bibliography") {
7514
7598
  return parseBasicCommand(value);
7515
7599
  }
7516
7600
  throw new DocumentCommandError("invalid_command", "Unsupported document command");
@@ -7555,6 +7639,20 @@ function applyBasicCommand(document2, command) {
7555
7639
  replacePlainField(document2, block2.field, command.text);
7556
7640
  return;
7557
7641
  }
7642
+ if (command.op === "set_heading_label") {
7643
+ const block2 = document2.blocks.find((entry) => entry.id === command.block_id);
7644
+ if (!block2) throw new DocumentCommandError("block_not_found", "Heading was not found");
7645
+ if (block2.kind !== "textBlock" || block2.command === "\\paragraph") {
7646
+ throw new DocumentCommandError("block_kind_mismatch", "Target is not a heading");
7647
+ }
7648
+ const key = command.label?.trim() ?? "";
7649
+ if (key && documentKeyError(key, { references: document2.references, labels: collectDocumentKeyLabels(document2), excludeOwnerId: block2.id })) {
7650
+ throw new DocumentCommandError("invalid_command", "Heading label is invalid or duplicated");
7651
+ }
7652
+ if (key) block2.label = key;
7653
+ else delete block2.label;
7654
+ return;
7655
+ }
7558
7656
  if (command.op === "remove_block") {
7559
7657
  const index = document2.blocks.findIndex((block2) => block2.id === command.block_id);
7560
7658
  if (index < 0) {
@@ -7632,7 +7730,7 @@ function applyBasicCommand(document2, command) {
7632
7730
  if (label2 !== void 0 && label2.length > 0) {
7633
7731
  const keyError = documentKeyError(label2, {
7634
7732
  references: document2.references,
7635
- labels: collectDocumentLabels(document2),
7733
+ labels: collectDocumentKeyLabels(document2),
7636
7734
  excludeOwnerId: block2.id
7637
7735
  });
7638
7736
  if (keyError === "duplicate") {
@@ -7887,7 +7985,7 @@ function getDocumentReferences(document2) {
7887
7985
  function getDocumentReferenceIndex(document2) {
7888
7986
  const referenceKeys = new Set(document2.references.map((reference) => reference.key));
7889
7987
  const labelEntries = collectDocumentLabels(document2);
7890
- const labelKeys = new Set(labelEntries.map((entry) => entry.key));
7988
+ const labelKeys = new Set(labelNumberMap(document2).keys());
7891
7989
  const citations = [];
7892
7990
  const crossReferences = [];
7893
7991
  const tokenLocations = /* @__PURE__ */ new Map();
@@ -7970,6 +8068,14 @@ function getDocumentReferenceIndex(document2) {
7970
8068
  citations,
7971
8069
  cross_references: crossReferences,
7972
8070
  labels,
8071
+ reference_targets: collectDocumentReferenceTargets(document2).map((target) => ({
8072
+ key: target.key,
8073
+ kind: target.kind,
8074
+ caption: target.caption,
8075
+ number: target.number,
8076
+ ...target.kind === "eq" ? { token_id: target.ownerId } : { block_id: target.ownerId },
8077
+ ...target.manualKey ? { manual_key: target.manualKey } : {}
8078
+ })),
7973
8079
  unresolved: {
7974
8080
  citation_keys: unresolvedCitationKeys,
7975
8081
  cross_reference_keys: unresolvedCrossReferenceKeys
@@ -8274,7 +8380,7 @@ function refTokenLatexForDocument(token, labelKinds, previousToken) {
8274
8380
  }
8275
8381
  return `${semanticRefPrefix(kind)}~${reference}`;
8276
8382
  }
8277
- function tokenLatex(token, labelKinds, previousToken) {
8383
+ function tokenLatex(token, labelKinds, previousToken, unitId) {
8278
8384
  if (token.kind === "text") {
8279
8385
  return styledTextLatex(token.text, token.style);
8280
8386
  }
@@ -8284,12 +8390,15 @@ function tokenLatex(token, labelKinds, previousToken) {
8284
8390
  if (token.kind === "ref") {
8285
8391
  return refTokenLatexForDocument(token, labelKinds, previousToken);
8286
8392
  }
8287
- if (token.display && token.labelEnabled && token.label && token.label.trim().length > 0) {
8393
+ if (isNumberedEquation(token)) {
8288
8394
  const body = mathBodyLatex(token);
8289
- return `\\begin{equation}
8290
- ${body}
8291
- \\label{${token.label.trim()}}
8292
- \\end{equation}`;
8395
+ const autoKey = implicitReferenceKey("eq", token.id, unitId);
8396
+ const aliases = [autoKey];
8397
+ if (token.labelEnabled && token.label?.trim() && token.label.trim() !== autoKey) aliases.push(token.label.trim());
8398
+ return "\\begin{equation}\n" + body + "\n" + aliases.map((key) => "\\label{" + key + "}").join("\n") + "\n\\end{equation}";
8399
+ }
8400
+ if (token.display && token.numbered === false && token.opening === "\\begin{equation}") {
8401
+ return "\\[" + mathBodyLatex(token) + "\\]";
8293
8402
  }
8294
8403
  if (token.sourceOwner === "editor") {
8295
8404
  return editorMathLatexForCompile(token);
@@ -8299,16 +8408,21 @@ ${body}
8299
8408
  }
8300
8409
  return renderMathNodeLatex(token.math);
8301
8410
  }
8302
- function inlineFieldLatexWithLabelKinds(field, labelKinds) {
8303
- return field.tokens.map((token, index) => tokenLatex(token, labelKinds, field.tokens[index - 1])).join("");
8411
+ function inlineFieldLatexWithLabelKinds(field, labelKinds, unitId) {
8412
+ return field.tokens.map((token, index) => tokenLatex(token, labelKinds, field.tokens[index - 1], unitId)).join("");
8304
8413
  }
8305
8414
  function inlineFieldLatex(field) {
8306
8415
  return inlineFieldLatexWithLabelKinds(field);
8307
8416
  }
8308
- function textBlockLatex(block, labelKinds) {
8309
- const content = inlineFieldLatexWithLabelKinds(block.field, labelKinds);
8417
+ function textBlockLatex(block, labelKinds, unitId) {
8418
+ const content = inlineFieldLatexWithLabelKinds(block.field, labelKinds, unitId);
8310
8419
  const body = block.command === "\\paragraph" ? `\\par
8311
8420
  ${content}` : `${block.command}{${content}}`;
8421
+ if (block.command !== "\\paragraph") {
8422
+ const keys = unitId ? [implicitHeadingReferenceKey(block.command.slice(1), block.id, unitId)] : [];
8423
+ if (block.label?.trim() && !keys.includes(block.label.trim())) keys.push(block.label.trim());
8424
+ return [body, ...keys.map((key) => `\\label{${key}}`)].join("\n");
8425
+ }
8312
8426
  if (block.command === "\\paragraph" && block.centered) {
8313
8427
  return `\\begin{center}
8314
8428
  ${body}
@@ -8319,10 +8433,10 @@ ${body}
8319
8433
  function indent(value) {
8320
8434
  return value.split("\n").map((line) => ` ${line}`).join("\n");
8321
8435
  }
8322
- function listBlockLatex(block, references, labelKinds, fixedFloats) {
8436
+ function listBlockLatex(block, references, labelKinds, fixedFloats, unitId) {
8323
8437
  const items = block.items.map((item) => {
8324
- const nested = item.blocks.map((child) => "\n" + indent(blockLatex(child, references, labelKinds, fixedFloats))).join("");
8325
- return ` \\item ${inlineFieldLatexWithLabelKinds(item.field, labelKinds)}${nested}`;
8438
+ const nested = item.blocks.map((child) => "\n" + indent(blockLatex(child, references, labelKinds, fixedFloats, unitId))).join("");
8439
+ return ` \\item ${inlineFieldLatexWithLabelKinds(item.field, labelKinds, unitId)}${nested}`;
8326
8440
  }).join("\n");
8327
8441
  return `${block.command}
8328
8442
  ${items}
@@ -8336,9 +8450,9 @@ function defaultGridColumnSpec(block) {
8336
8450
  }
8337
8451
  return `|${compact.split("").join("|")}|`;
8338
8452
  }
8339
- function tabularInnerLatex(block, labelKinds) {
8453
+ function tabularInnerLatex(block, labelKinds, unitId) {
8340
8454
  const rows = block.rows.map(
8341
- (row) => ` ${row.map((cell) => inlineFieldLatexWithLabelKinds(cell, labelKinds)).join(" & ")}`
8455
+ (row) => ` ${row.map((cell) => inlineFieldLatexWithLabelKinds(cell, labelKinds, unitId)).join(" & ")}`
8342
8456
  );
8343
8457
  const gridColumns = defaultGridColumnSpec(block);
8344
8458
  if (gridColumns) {
@@ -8352,29 +8466,30 @@ ${block.closing}`;
8352
8466
  ${rows.join(" \\\\\n")}
8353
8467
  ${block.closing}`;
8354
8468
  }
8355
- function floatCaptionLabelLines(block, counter, labelKinds) {
8469
+ function floatCaptionLabelLines(block, counter, labelKinds, unitId) {
8356
8470
  const lines = [];
8357
- const caption = inlineFieldLatexWithLabelKinds(block.captionField, labelKinds).trim();
8471
+ const caption = inlineFieldLatexWithLabelKinds(block.captionField, labelKinds, unitId).trim();
8358
8472
  const hasCaption = block.captionEnabled && caption.length > 0;
8359
8473
  if (hasCaption) {
8360
8474
  lines.push(` \\caption{${caption}}`);
8361
8475
  }
8362
- if (block.labelEnabled && block.label.trim().length > 0) {
8363
- if (!hasCaption) {
8364
- lines.push(` \\refstepcounter{${counter}}`);
8365
- }
8366
- lines.push(` \\label{${block.label.trim()}}`);
8476
+ const hasManualLabel = block.labelEnabled && block.label.trim().length > 0;
8477
+ if (hasCaption || hasManualLabel) {
8478
+ if (!hasCaption) lines.push(" \\refstepcounter{" + counter + "}");
8479
+ const autoKey = implicitReferenceKey(counter === "figure" ? "fig" : "tab", block.id, unitId);
8480
+ lines.push(" \\label{" + autoKey + "}");
8481
+ if (hasManualLabel && block.label.trim() !== autoKey) lines.push(" \\label{" + block.label.trim() + "}");
8367
8482
  }
8368
8483
  return lines;
8369
8484
  }
8370
- function tableBlockLatex(block, labelKinds, fixedFloats) {
8485
+ function tableBlockLatex(block, labelKinds, fixedFloats, unitId) {
8371
8486
  const placement = fixedFloats ? "H" : "htbp";
8372
8487
  const lines = [`\\begin{table}[${placement}]`];
8373
8488
  if (block.centered) {
8374
8489
  lines.push(" \\centering");
8375
8490
  }
8376
- lines.push(...floatCaptionLabelLines(block, "table", labelKinds));
8377
- lines.push(indent(tabularInnerLatex(block, labelKinds)));
8491
+ lines.push(...floatCaptionLabelLines(block, "table", labelKinds, unitId));
8492
+ lines.push(indent(tabularInnerLatex(block, labelKinds, unitId)));
8378
8493
  lines.push("\\end{table}");
8379
8494
  return lines.join("\n");
8380
8495
  }
@@ -8393,29 +8508,29 @@ function imageOptionsLatex(block, constrainToColumn) {
8393
8508
  }
8394
8509
  return `[${entries.map(([key, value]) => `${key}=${value}`).join(",")}]`;
8395
8510
  }
8396
- function imageBlockLatex(block, labelKinds, fixedFloats) {
8511
+ function imageBlockLatex(block, labelKinds, fixedFloats, unitId) {
8397
8512
  const placement = fixedFloats ? "H" : "htbp";
8398
8513
  const lines = [`\\begin{figure}[${placement}]`];
8399
8514
  if (block.centered) {
8400
8515
  lines.push(" \\centering");
8401
8516
  }
8402
8517
  lines.push(` ${block.command}${imageOptionsLatex(block, true)}{${block.value}}`);
8403
- lines.push(...floatCaptionLabelLines(block, "figure", labelKinds));
8518
+ lines.push(...floatCaptionLabelLines(block, "figure", labelKinds, unitId));
8404
8519
  lines.push("\\end{figure}");
8405
8520
  return lines.join("\n");
8406
8521
  }
8407
- function blockLatex(block, references, labelKinds, fixedFloats) {
8522
+ function blockLatex(block, references, labelKinds, fixedFloats, unitId) {
8408
8523
  if (block.kind === "textBlock") {
8409
- return textBlockLatex(block, labelKinds);
8524
+ return textBlockLatex(block, labelKinds, unitId);
8410
8525
  }
8411
8526
  if (block.kind === "list") {
8412
- return listBlockLatex(block, references, labelKinds, fixedFloats);
8527
+ return listBlockLatex(block, references, labelKinds, fixedFloats, unitId);
8413
8528
  }
8414
8529
  if (block.kind === "table") {
8415
- return tableBlockLatex(block, labelKinds, fixedFloats);
8530
+ return tableBlockLatex(block, labelKinds, fixedFloats, unitId);
8416
8531
  }
8417
8532
  if (block.kind === "image") {
8418
- return imageBlockLatex(block, labelKinds, fixedFloats);
8533
+ return imageBlockLatex(block, labelKinds, fixedFloats, unitId);
8419
8534
  }
8420
8535
  if (block.kind === "bibliography") {
8421
8536
  const width = String(Math.max(references.length, 9));
@@ -8459,10 +8574,8 @@ ${meta.abstract.trim()}
8459
8574
  }
8460
8575
  function documentLabelKindMap(document2) {
8461
8576
  const map = /* @__PURE__ */ new Map();
8462
- for (const entry of collectDocumentLabels(document2)) {
8463
- if (!map.has(entry.key)) {
8464
- map.set(entry.key, entry.kind);
8465
- }
8577
+ for (const [key, entry] of labelNumberMap(document2)) {
8578
+ map.set(key, entry.kind);
8466
8579
  }
8467
8580
  return map;
8468
8581
  }
@@ -8471,6 +8584,17 @@ function closingHamdalaLatex() {
8471
8584
  \\maghribi{${BUTEX_CLOSING_HAMDALA}}
8472
8585
  \\end{center}`;
8473
8586
  }
8587
+ function documentContentLatex(document2, context) {
8588
+ if (!context?.unitId?.trim()) throw new Error("book-content export requires a stable unitId");
8589
+ const labelKinds = documentLabelKindMap(document2);
8590
+ for (const target of context?.targets ?? []) {
8591
+ if (target.kind === "fig" || target.kind === "tab" || target.kind === "eq") {
8592
+ labelKinds.set(target.key, target.kind);
8593
+ if (target.manualKey) labelKinds.set(target.manualKey, target.kind);
8594
+ }
8595
+ }
8596
+ return document2.blocks.filter((block) => block.kind !== "bibliography").map((block) => blockLatex(block, document2.references, labelKinds, false, context?.unitId)).filter((part) => part.length > 0).join("\n\n");
8597
+ }
8474
8598
  function documentLatex(document2, options = {}) {
8475
8599
  const meta = document2.meta ?? emptyDocumentMeta();
8476
8600
  const twocolumn = options.twocolumn === true;
@@ -8502,6 +8626,65 @@ ${body}
8502
8626
  `;
8503
8627
  }
8504
8628
 
8629
+ // src/document/bookContent.ts
8630
+ function bookContextReferences(context) {
8631
+ return (context?.references ?? []).map((entry, index) => ({
8632
+ ...referenceFromJson(entry),
8633
+ id: "book-ref-" + String(index)
8634
+ }));
8635
+ }
8636
+ function bookContentTargets(document2, context) {
8637
+ const local = collectDocumentReferenceTargets(document2).map((target) => {
8638
+ const key = implicitReferenceKey(target.kind, target.ownerId, context.unitId);
8639
+ const projection = context.targets?.find((entry) => entry.unitId === context.unitId && (entry.ownerId === target.ownerId || entry.key === key));
8640
+ return {
8641
+ ...target,
8642
+ key,
8643
+ ...projection?.displayLabel ? { displayLabel: projection.displayLabel } : {}
8644
+ };
8645
+ });
8646
+ const headings = document2.blocks.flatMap((block) => {
8647
+ if (block.kind !== "textBlock" || block.command === "\\paragraph") return [];
8648
+ const kind = block.command.slice(1);
8649
+ const caption = block.field.tokens.filter((token) => token.kind === "text").map((token) => token.text).join("");
8650
+ return [{
8651
+ unitId: context.unitId,
8652
+ ownerId: block.id,
8653
+ kind,
8654
+ key: implicitHeadingReferenceKey(kind, block.id, context.unitId),
8655
+ caption,
8656
+ number: null,
8657
+ displayLabel: context.targets?.find((target) => target.unitId === context.unitId && target.ownerId === block.id)?.displayLabel ?? (caption || kind),
8658
+ ...block.label ? { manualKey: block.label } : {}
8659
+ }];
8660
+ });
8661
+ const external = (context.targets ?? []).filter((target) => target.unitId !== context.unitId).map((target) => ({
8662
+ ...target,
8663
+ caption: target.caption ?? "",
8664
+ number: null
8665
+ }));
8666
+ return [...local, ...headings, ...external];
8667
+ }
8668
+ function formatBookReferenceLabel(keys, document2, command, context, options = {}) {
8669
+ const targets = context.targets ?? [];
8670
+ return keys.map((key) => {
8671
+ const target = targets.find((entry) => entry.key === key || entry.manualKey === key);
8672
+ if (target?.displayLabel) return target.displayLabel;
8673
+ const local = collectDocumentReferenceTargets(document2).find((entry) => entry.manualKey === key || implicitReferenceKey(entry.kind, entry.ownerId, context.unitId) === key);
8674
+ if (local) return formatRefLabel([local.manualKey || local.key], document2, command, options);
8675
+ const heading = document2.blocks.find((block) => block.kind === "textBlock" && block.command !== "\\paragraph" && (block.label === key || implicitHeadingReferenceKey(
8676
+ block.command.slice(1),
8677
+ block.id,
8678
+ context.unitId
8679
+ ) === key));
8680
+ if (heading?.kind === "textBlock") {
8681
+ const caption = heading.field.tokens.filter((token) => token.kind === "text").map((token) => token.text).join("").trim();
8682
+ return caption || heading.command.slice(1);
8683
+ }
8684
+ return command === "eqref" ? "(?)" : "?";
8685
+ }).join(options.documentDirection === "ltr" ? ", " : "\u060C");
8686
+ }
8687
+
8505
8688
  // src/document/validation.ts
8506
8689
  var XELATEX_UNSUPPORTED_EMOJI_PATTERN = /[\p{Emoji_Presentation}\p{Emoji_Modifier}\p{Regional_Indicator}\uFE0F\u20E3]/u;
8507
8690
  function hasXeLatexUnsupportedEmoji(value) {
@@ -8561,10 +8744,17 @@ function validateToken(context, token, path, blockId) {
8561
8744
  return;
8562
8745
  }
8563
8746
  validateTextValue(context, token.source, `${path}.source`, blockId, token.id);
8747
+ if (token.numbered === true && !supportsSingleEquationNumbering(token)) {
8748
+ addIssue(context, "invalid_equation_label", `${path}.numbered`, blockId, token.id);
8749
+ }
8564
8750
  if (!token.labelEnabled) {
8565
8751
  return;
8566
8752
  }
8567
- if (!token.display) {
8753
+ if (!supportsSingleEquationNumbering(token)) {
8754
+ addIssue(context, "invalid_equation_label", `${path}.label`, blockId, token.id);
8755
+ return;
8756
+ }
8757
+ if (!isNumberedEquation(token)) {
8568
8758
  addIssue(context, "invalid_equation_label", `${path}.label`, blockId, token.id);
8569
8759
  return;
8570
8760
  }
@@ -8578,6 +8768,13 @@ function validateInlineField(context, field, path, blockId) {
8578
8768
  function validateBlock(context, block, path) {
8579
8769
  if (block.kind === "textBlock") {
8580
8770
  validateInlineField(context, block.field, `${path}.field`, block.id);
8771
+ if (block.command !== "\\paragraph") {
8772
+ const kind = block.command.slice(1);
8773
+ if (block.label) registerKey(context, block.label, `${path}.label`, kind, block.id);
8774
+ if (context.bookMode && context.bookContext) {
8775
+ context.labelKinds.set(implicitHeadingReferenceKey(kind, block.id, context.bookContext.unitId), kind);
8776
+ }
8777
+ }
8581
8778
  return;
8582
8779
  }
8583
8780
  if (block.kind === "list") {
@@ -8627,6 +8824,10 @@ function validateBlock(context, block, path) {
8627
8824
  }
8628
8825
  return;
8629
8826
  }
8827
+ if (block.kind === "bibliography" && context.bookMode) {
8828
+ addIssue(context, "book_local_bibliography", path, block.id);
8829
+ return;
8830
+ }
8630
8831
  if (block.kind === "raw") {
8631
8832
  validateTextValue(context, block.value, `${path}.value`, block.id);
8632
8833
  }
@@ -8649,7 +8850,7 @@ function validateDuplicateKeys(context) {
8649
8850
  }
8650
8851
  function validatePendingReferences(context) {
8651
8852
  for (const pending of context.pendingCitations) {
8652
- if (pending.token.keys.some((key) => !isValidDocumentKey(normalizeDocumentKey(key)))) {
8853
+ if (pending.token.keys.some((key) => !isValidDocumentKey(normalizeDocumentKey(key)) || context.citationKeys !== void 0 && !context.citationKeys.has(normalizeDocumentKey(key)))) {
8653
8854
  addIssue(
8654
8855
  context,
8655
8856
  "missing_citation",
@@ -8662,7 +8863,7 @@ function validatePendingReferences(context) {
8662
8863
  for (const pending of context.pendingReferences) {
8663
8864
  for (const key of pending.token.keys) {
8664
8865
  const normalized = normalizeDocumentKey(key);
8665
- if (!isValidDocumentKey(normalized)) {
8866
+ if (!isValidDocumentKey(normalized) || !context.labelKinds.has(normalized)) {
8666
8867
  addIssue(
8667
8868
  context,
8668
8869
  "missing_reference",
@@ -8731,7 +8932,7 @@ function resolveDocument(document2) {
8731
8932
  return null;
8732
8933
  }
8733
8934
  }
8734
- function validateDocument(document2) {
8935
+ function validateDocument(document2, options = {}) {
8735
8936
  const resolved = resolveDocument(document2);
8736
8937
  if (!resolved) {
8737
8938
  return {
@@ -8743,6 +8944,9 @@ function validateDocument(document2) {
8743
8944
  issues: [],
8744
8945
  keyOwners: [],
8745
8946
  labelKinds: /* @__PURE__ */ new Map(),
8947
+ bookMode: options.mode === "book-content",
8948
+ bookContext: options.bookContext,
8949
+ ...options.mode === "book-content" && options.bookContext?.references ? { citationKeys: new Set(options.bookContext.references.map((entry) => normalizeDocumentKey(entry.key))) } : {},
8746
8950
  pendingCitations: [],
8747
8951
  pendingReferences: []
8748
8952
  };
@@ -8761,6 +8965,28 @@ function validateDocument(document2) {
8761
8965
  resolved.blocks.forEach((block, index) => {
8762
8966
  validateBlock(context, block, `$.blocks[${String(index)}]`);
8763
8967
  });
8968
+ for (const target of collectDocumentReferenceTargets(resolved)) {
8969
+ const autoKey = context.bookMode && context.bookContext ? implicitReferenceKey(target.kind, target.ownerId, context.bookContext.unitId) : target.key;
8970
+ if (target.number !== null && target.manualKey !== autoKey) {
8971
+ registerKey(
8972
+ context,
8973
+ autoKey,
8974
+ "$.automatic_labels",
8975
+ target.kind,
8976
+ target.kind === "eq" ? void 0 : target.ownerId,
8977
+ target.kind === "eq" ? target.ownerId : void 0
8978
+ );
8979
+ }
8980
+ }
8981
+ if (context.bookMode) {
8982
+ for (const target of context.bookContext?.targets ?? []) {
8983
+ context.labelKinds.set(normalizeDocumentKey(target.key), target.kind);
8984
+ if (target.manualKey) context.labelKinds.set(normalizeDocumentKey(target.manualKey), target.kind);
8985
+ }
8986
+ }
8987
+ if (context.bookMode && !context.bookContext?.unitId?.trim()) {
8988
+ addIssue(context, "book_context_required", "$.book_context");
8989
+ }
8764
8990
  for (const diagnostic of resolved.diagnostics) {
8765
8991
  addIssue(context, "parser_diagnostic", diagnostic.path);
8766
8992
  }
@@ -8891,7 +9117,7 @@ function previewInlines(field, islands, output, equationSide, document2, preview
8891
9117
  kind: "cite",
8892
9118
  id: token.id,
8893
9119
  keys: [...token.keys],
8894
- label: formatCiteLabel(token.keys, document2.references, {
9120
+ label: formatCiteLabel(token.keys, previewOptions.mode === "book-content" ? bookContextReferences(previewOptions.bookContext) : document2.references, {
8895
9121
  documentDirection: previewOptions.documentDirection,
8896
9122
  digitForm: previewOptions.digitForm
8897
9123
  })
@@ -8903,12 +9129,16 @@ function previewInlines(field, islands, output, equationSide, document2, preview
8903
9129
  id: token.id,
8904
9130
  keys: [...token.keys],
8905
9131
  refCommand: token.refCommand,
8906
- label: formatRefLabel(token.keys, document2, token.refCommand, {
9132
+ label: previewOptions.mode === "book-content" && previewOptions.bookContext ? formatBookReferenceLabel(token.keys, document2, token.refCommand, previewOptions.bookContext, {
9133
+ documentDirection: previewOptions.documentDirection,
9134
+ digitForm: previewOptions.digitForm
9135
+ }) : formatRefLabel(token.keys, document2, token.refCommand, {
8907
9136
  documentDirection: previewOptions.documentDirection,
8908
9137
  digitForm: previewOptions.digitForm
8909
9138
  })
8910
9139
  };
8911
9140
  }
9141
+ const number = collectDocumentReferenceTargets(document2).find((target) => target.kind === "eq" && target.ownerId === token.id)?.number;
8912
9142
  const island = {
8913
9143
  id: token.id,
8914
9144
  tex: mathTex(token, equationSide, previewOptions.digitForm),
@@ -8916,8 +9146,12 @@ function previewInlines(field, islands, output, equationSide, document2, preview
8916
9146
  output,
8917
9147
  editable: token.editable
8918
9148
  };
9149
+ const numberLabel = number == null ? void 0 : formatBibliographyNumber(number, {
9150
+ documentDirection: previewOptions.documentDirection,
9151
+ digitForm: previewOptions.digitForm
9152
+ });
8919
9153
  islands.push(island);
8920
- return { kind: "math", ...island };
9154
+ return { kind: "math", ...island, ...numberLabel ? { numberLabel } : {} };
8921
9155
  });
8922
9156
  }
8923
9157
  function textBlockPreview(block, islands, output, equationSide, document2, previewOptions) {
@@ -8940,12 +9174,9 @@ function textBlockPreview(block, islands, output, equationSide, document2, previ
8940
9174
  ...block.centered ? { centered: true } : {}
8941
9175
  };
8942
9176
  }
8943
- function floatNumberLabel(document2, key, previewOptions) {
8944
- if (!key || key.trim().length === 0) {
8945
- return void 0;
8946
- }
8947
- const hit = labelNumberMap(document2).get(key.trim());
8948
- if (!hit || hit.kind !== "fig" && hit.kind !== "tab") {
9177
+ function floatNumberLabel(document2, ownerId, previewOptions) {
9178
+ const hit = collectDocumentReferenceTargets(document2).find((target) => target.ownerId === ownerId);
9179
+ if (!hit || hit.number === null || hit.kind !== "fig" && hit.kind !== "tab") {
8949
9180
  return void 0;
8950
9181
  }
8951
9182
  return formatFloatCaptionTitle(hit.kind, hit.number, {
@@ -8987,7 +9218,8 @@ function blockPreview(block, islands, output, equationSide, document2, previewOp
8987
9218
  id: block.id,
8988
9219
  rows: block.rows.map((row) => row.map((cell) => previewInlines(cell, islands, output, equationSide, document2, previewOptions))),
8989
9220
  ...captionPreview(block, islands, output, equationSide, document2, previewOptions),
8990
- ...label.length > 0 ? { label, numberLabel: floatNumberLabel(document2, label, previewOptions) } : {},
9221
+ ...label.length > 0 ? { label } : {},
9222
+ ...floatNumberLabel(document2, block.id, previewOptions) ? { numberLabel: floatNumberLabel(document2, block.id, previewOptions) } : {},
8991
9223
  ...block.metadata ? { metadata: { ...block.metadata } } : {}
8992
9224
  };
8993
9225
  }
@@ -9001,7 +9233,8 @@ function blockPreview(block, islands, output, equationSide, document2, previewOp
9001
9233
  options: block.options,
9002
9234
  centered: block.centered,
9003
9235
  ...captionPreview(block, islands, output, equationSide, document2, previewOptions),
9004
- ...label.length > 0 ? { label, numberLabel: floatNumberLabel(document2, label, previewOptions) } : {},
9236
+ ...label.length > 0 ? { label } : {},
9237
+ ...floatNumberLabel(document2, block.id, previewOptions) ? { numberLabel: floatNumberLabel(document2, block.id, previewOptions) } : {},
9005
9238
  ...block.metadata ? { metadata: { ...block.metadata } } : {}
9006
9239
  };
9007
9240
  }
@@ -9055,14 +9288,16 @@ function documentPreview(document2, output = "svg", equationSide = "arabic", pre
9055
9288
  const options = {
9056
9289
  documentDirection: previewOptions.documentDirection ?? "rtl",
9057
9290
  digitForm: previewOptions.digitForm ?? (previewOptions.documentDirection === "ltr" ? "western" : "arabicIndic"),
9058
- uiLocale: previewOptions.uiLocale ?? "ar"
9291
+ uiLocale: previewOptions.uiLocale ?? "ar",
9292
+ mode: previewOptions.mode ?? "article",
9293
+ bookContext: previewOptions.bookContext
9059
9294
  };
9060
- const body = document2.blocks.map((block) => blockPreview(block, mathIslands, output, equationSide, document2, options));
9295
+ const body = document2.blocks.filter((block) => options.mode !== "book-content" || block.kind !== "bibliography").map((block) => blockPreview(block, mathIslands, output, equationSide, document2, options));
9061
9296
  return {
9062
9297
  blocks: [
9063
- ...articleChromePreview(document2, options.uiLocale ?? "ar", options),
9298
+ ...options.mode === "book-content" ? [] : articleChromePreview(document2, options.uiLocale ?? "ar", options),
9064
9299
  ...body,
9065
- { kind: "closing", id: "article-closing", text: BUTEX_CLOSING_HAMDALA, tex: butexMaghribiDisplayTex(BUTEX_CLOSING_HAMDALA) }
9300
+ ...options.mode === "book-content" ? [] : [{ kind: "closing", id: "article-closing", text: BUTEX_CLOSING_HAMDALA, tex: butexMaghribiDisplayTex(BUTEX_CLOSING_HAMDALA) }]
9066
9301
  ],
9067
9302
  mathIslands
9068
9303
  };
@@ -9076,6 +9311,11 @@ function documentLatex2(document2, options = {}) {
9076
9311
  }
9077
9312
  return documentLatex(document2, options);
9078
9313
  }
9314
+ function documentContentLatex2(document2, context) {
9315
+ const validation = validateDocument(document2, { mode: "book-content", bookContext: context });
9316
+ if (!validation.valid) throw new DocumentValidationError(validation.issues);
9317
+ return documentContentLatex(document2, context);
9318
+ }
9079
9319
  // Annotate the CommonJS export names for ESM import in node:
9080
9320
  0 && (module.exports = {
9081
9321
  BUTEX_BASMALA,
@@ -9105,6 +9345,8 @@ function documentLatex2(document2, options = {}) {
9105
9345
  arabicXeLatexPreamblePkg,
9106
9346
  bibliographyEntryBody,
9107
9347
  bibliographyEntryLatex,
9348
+ bookContentTargets,
9349
+ bookContextReferences,
9108
9350
  butexBasmalaDisplayLatex,
9109
9351
  butexBasmalaDisplayTex,
9110
9352
  butexBasmalaTitlingPreamble,
@@ -9117,7 +9359,9 @@ function documentLatex2(document2, options = {}) {
9117
9359
  clearDocumentImageAsset,
9118
9360
  cloneDocumentMeta,
9119
9361
  cloneDocumentNode,
9362
+ collectDocumentKeyLabels,
9120
9363
  collectDocumentLabels,
9364
+ collectDocumentReferenceTargets,
9121
9365
  createDocumentHistory,
9122
9366
  createEmptyArabicEquationSession,
9123
9367
  createEmptyDocument,
@@ -9128,6 +9372,7 @@ function documentLatex2(document2, options = {}) {
9128
9372
  detectInlineSpans,
9129
9373
  detectMathSpans,
9130
9374
  diffDocument,
9375
+ documentContentLatex,
9131
9376
  documentHasAbstract,
9132
9377
  documentHasMaketitle,
9133
9378
  documentHasTitleStack,
@@ -9144,6 +9389,7 @@ function documentLatex2(document2, options = {}) {
9144
9389
  fillDocumentMetaGaps,
9145
9390
  findFirstInlineField,
9146
9391
  formatBibliographyNumber,
9392
+ formatBookReferenceLabel,
9147
9393
  formatCiteLabel,
9148
9394
  formatFloatCaptionPreview,
9149
9395
  formatFloatCaptionTitle,
@@ -9155,6 +9401,8 @@ function documentLatex2(document2, options = {}) {
9155
9401
  getDocumentReferences,
9156
9402
  hasXeLatexUnsupportedEmoji,
9157
9403
  hijriMonthLabel,
9404
+ implicitHeadingReferenceKey,
9405
+ implicitReferenceKey,
9158
9406
  inlineFieldLatex,
9159
9407
  insertCiteTokenAtCaret,
9160
9408
  insertDocumentBlockAfter,
@@ -9163,6 +9411,8 @@ function documentLatex2(document2, options = {}) {
9163
9411
  insertRefTokenAtCaret,
9164
9412
  isDocumentValid,
9165
9413
  isDuplicateDocumentKey,
9414
+ isNumberedEquation,
9415
+ isNumberedFloat,
9166
9416
  isValidDocumentKey,
9167
9417
  labelNumberMap,
9168
9418
  mathNodeFromArabicSession,
@@ -9206,6 +9456,7 @@ function documentLatex2(document2, options = {}) {
9206
9456
  toggleBlockInSelection,
9207
9457
  toggleTextTokenStyle,
9208
9458
  updateCiteTokenKeys,
9459
+ updateDocumentHeadingLabel,
9209
9460
  updateDocumentImageAsset,
9210
9461
  updateDocumentImageMeta,
9211
9462
  updateDocumentImageValue,