@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.
@@ -754,76 +754,94 @@ function refTokenLatex(keys, refCommand) {
754
754
  const command = refCommand === "eqref" ? "\\eqref" : "\\ref";
755
755
  return `${command}{${keys.join(",")}}`;
756
756
  }
757
- function collectDocumentLabels(document2) {
758
- const entries = [];
757
+ function implicitObjectKey(kind, ownerId, unitId) {
758
+ const hex = (value) => Array.from(new TextEncoder().encode(value), (byte) => byte.toString(16).padStart(2, "0")).join("");
759
+ const scope = unitId === void 0 ? "a" : "u" + hex(unitId);
760
+ return kind + ":butex-auto-" + scope + "-" + hex(ownerId);
761
+ }
762
+ function implicitReferenceKey(kind, ownerId, unitId) {
763
+ return implicitObjectKey(kind, ownerId, unitId);
764
+ }
765
+ function implicitHeadingReferenceKey(kind, ownerId, unitId) {
766
+ return implicitObjectKey(kind, ownerId, unitId);
767
+ }
768
+ function supportsSingleEquationNumbering(token) {
769
+ return token.display && (token.opening === "\\[" || token.opening === String.fromCharCode(36, 36) || token.opening === "\\begin{equation}" || token.opening === "\\begin{equation*}");
770
+ }
771
+ function isNumberedEquation(token) {
772
+ if (!supportsSingleEquationNumbering(token)) return false;
773
+ if (typeof token.numbered === "boolean") return token.numbered;
774
+ return token.opening === "\\begin{equation}" || Boolean(token.labelEnabled) && Boolean(token.label?.trim());
775
+ }
776
+ function isNumberedFloat(block) {
777
+ return block.captionEnabled && block.caption.trim().length > 0 || block.labelEnabled && block.label.trim().length > 0;
778
+ }
779
+ function collectDocumentReferenceTargets(document2) {
780
+ const targets = [];
759
781
  const counters = { fig: 0, tab: 0, eq: 0 };
760
- function pushEqFromField(tokens) {
761
- for (const token of tokens) {
762
- if (token.kind !== "math") {
763
- continue;
764
- }
765
- if (token.display && token.labelEnabled && token.label && token.label.trim().length > 0) {
766
- counters.eq += 1;
767
- entries.push({
768
- key: token.label.trim(),
769
- kind: "eq",
770
- caption: "",
771
- ownerId: token.id,
772
- number: counters.eq
773
- });
782
+ function append(kind, ownerId, caption, numbered, manualKey = "") {
783
+ if (numbered) counters[kind] += 1;
784
+ targets.push({
785
+ key: implicitReferenceKey(kind, ownerId),
786
+ kind,
787
+ ownerId,
788
+ caption,
789
+ number: numbered ? counters[kind] : null,
790
+ ...manualKey.trim() ? { manualKey: manualKey.trim() } : {}
791
+ });
792
+ }
793
+ function visitField(field) {
794
+ for (const token of field.tokens) {
795
+ if (token.kind === "math" && supportsSingleEquationNumbering(token)) {
796
+ append("eq", token.id, "", isNumberedEquation(token), token.labelEnabled ? token.label ?? "" : "");
774
797
  }
775
798
  }
776
799
  }
777
800
  function walk(blocks) {
778
801
  for (const block of blocks) {
779
- if (block.kind === "image") {
780
- if (block.labelEnabled && block.label.trim().length > 0) {
781
- counters.fig += 1;
782
- entries.push({
783
- key: block.label.trim(),
784
- kind: "fig",
785
- caption: block.captionEnabled ? block.caption : "",
786
- ownerId: block.id,
787
- number: counters.fig
788
- });
789
- }
790
- if (block.captionEnabled) {
791
- pushEqFromField(block.captionField.tokens);
792
- }
793
- }
794
- if (block.kind === "table") {
795
- if (block.labelEnabled && block.label.trim().length > 0) {
796
- counters.tab += 1;
797
- entries.push({
798
- key: block.label.trim(),
799
- kind: "tab",
800
- caption: block.captionEnabled ? block.caption : "",
801
- ownerId: block.id,
802
- number: counters.tab
803
- });
804
- }
805
- if (block.captionEnabled) {
806
- pushEqFromField(block.captionField.tokens);
807
- }
808
- for (const row of block.rows) {
809
- for (const cell of row) {
810
- pushEqFromField(cell.tokens);
811
- }
802
+ if (block.kind === "image" || block.kind === "table") {
803
+ append(
804
+ block.kind === "image" ? "fig" : "tab",
805
+ block.id,
806
+ block.captionEnabled ? block.caption : "",
807
+ isNumberedFloat(block),
808
+ block.labelEnabled ? block.label : ""
809
+ );
810
+ if (block.captionEnabled) visitField(block.captionField);
811
+ if (block.kind === "table") {
812
+ for (const row of block.rows) for (const cell of row) visitField(cell);
812
813
  }
813
- }
814
- if (block.kind === "textBlock") {
815
- pushEqFromField(block.field.tokens);
816
- }
817
- if (block.kind === "list") {
814
+ } else if (block.kind === "textBlock") {
815
+ visitField(block.field);
816
+ } else if (block.kind === "list") {
818
817
  for (const item of block.items) {
819
- pushEqFromField(item.field.tokens);
818
+ visitField(item.field);
820
819
  walk(item.blocks);
821
820
  }
822
821
  }
823
822
  }
824
823
  }
825
824
  walk(document2.blocks);
826
- return entries;
825
+ return targets;
826
+ }
827
+ function collectDocumentLabels(document2) {
828
+ return collectDocumentReferenceTargets(document2).filter((target) => target.number !== null && Boolean(target.manualKey)).map(({ manualKey, kind, caption, ownerId, number }) => ({ key: manualKey, kind, caption, ownerId, number }));
829
+ }
830
+ function collectDocumentKeyLabels(document2) {
831
+ return collectDocumentReferenceTargets(document2).filter((target) => target.number !== null).flatMap((target) => [
832
+ { key: target.key, ownerId: target.ownerId },
833
+ ...target.manualKey && target.manualKey !== target.key ? [{ key: target.manualKey, ownerId: target.ownerId }] : []
834
+ ]);
835
+ }
836
+ function labelNumberMap(document2) {
837
+ const map = /* @__PURE__ */ new Map();
838
+ for (const target of collectDocumentReferenceTargets(document2)) {
839
+ if (target.number === null) continue;
840
+ for (const key of [target.key, target.manualKey]) {
841
+ if (key && !map.has(key)) map.set(key, { kind: target.kind, number: target.number });
842
+ }
843
+ }
844
+ return map;
827
845
  }
828
846
  function stripDisplayMathDelimiters(source) {
829
847
  const trimmed = source.trim();
@@ -833,8 +851,12 @@ function stripDisplayMathDelimiters(source) {
833
851
  if (trimmed.startsWith("$$") && trimmed.endsWith("$$")) {
834
852
  return trimmed.slice(2, -2).trim();
835
853
  }
836
- if (trimmed.startsWith("\\begin{equation}") && trimmed.endsWith("\\end{equation}")) {
837
- return trimmed.slice("\\begin{equation}".length, -"\\end{equation}".length).trim();
854
+ for (const environment of ["equation", "equation*"]) {
855
+ const opening = `\\begin{${environment}}`;
856
+ const closing = `\\end{${environment}}`;
857
+ if (trimmed.startsWith(opening) && trimmed.endsWith(closing)) {
858
+ return trimmed.slice(opening.length, -closing.length).trim();
859
+ }
838
860
  }
839
861
  return trimmed;
840
862
  }
@@ -1227,7 +1249,8 @@ function createInlineField(value = "", mathObjects = [], options = {}, path = "$
1227
1249
  editable: true,
1228
1250
  sourceOwner: structuredMathJson.source_owner === "editor" ? "editor" : "imported-structured",
1229
1251
  ...typeof structuredMathJson.label_enabled === "boolean" ? { labelEnabled: structuredMathJson.label_enabled } : {},
1230
- ...typeof structuredMathJson.label === "string" ? { label: structuredMathJson.label } : {}
1252
+ ...typeof structuredMathJson.label === "string" ? { label: structuredMathJson.label } : {},
1253
+ ...typeof structuredMathJson.numbered === "boolean" ? { numbered: structuredMathJson.numbered } : {}
1231
1254
  });
1232
1255
  } else {
1233
1256
  tokens.push({
@@ -1242,7 +1265,8 @@ function createInlineField(value = "", mathObjects = [], options = {}, path = "$
1242
1265
  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",
1243
1266
  sourceOwner: "raw",
1244
1267
  ...mathJson?.node_type === "RawMathObject" && typeof mathJson.label_enabled === "boolean" ? { labelEnabled: mathJson.label_enabled } : {},
1245
- ...mathJson?.node_type === "RawMathObject" && typeof mathJson.label === "string" ? { label: mathJson.label } : {}
1268
+ ...mathJson?.node_type === "RawMathObject" && typeof mathJson.label === "string" ? { label: mathJson.label } : {},
1269
+ ...mathJson?.node_type === "RawMathObject" && typeof mathJson.numbered === "boolean" ? { numbered: mathJson.numbered } : {}
1246
1270
  });
1247
1271
  }
1248
1272
  index = span.end;
@@ -1339,6 +1363,7 @@ function parseTextBlock(json, options, path, diagnostics, identities) {
1339
1363
  identities
1340
1364
  ),
1341
1365
  ...metadataFromJson(json.metadata),
1366
+ ...typeof json.label === "string" && json.command !== "\\paragraph" ? { label: json.label } : {},
1342
1367
  ...json.centered === true ? { centered: true } : {}
1343
1368
  };
1344
1369
  }
@@ -4944,7 +4969,7 @@ function normalizedNewFloatLabel(document2, label) {
4944
4969
  if (!normalized) return "";
4945
4970
  const error = documentKeyError(normalized, {
4946
4971
  references: document2.references,
4947
- labels: collectDocumentLabels(document2)
4972
+ labels: collectDocumentKeyLabels(document2)
4948
4973
  });
4949
4974
  if (error === "duplicate") {
4950
4975
  throw new DocumentCommandError("duplicate_key", "Float label is already in use");
@@ -5388,7 +5413,7 @@ function validateReferenceKey(document2, key, excludeReferenceId) {
5388
5413
  const normalized = normalizeDocumentKey(key);
5389
5414
  const error = documentKeyError(normalized, {
5390
5415
  references: document2.references,
5391
- labels: collectDocumentLabels(document2),
5416
+ labels: collectDocumentKeyLabels(document2),
5392
5417
  ...excludeReferenceId ? { excludeReferenceId } : {}
5393
5418
  });
5394
5419
  if (error === "duplicate") {
@@ -5610,6 +5635,17 @@ function parseToken(value) {
5610
5635
  throw new DocumentCommandError("invalid_inline_token", "Unsupported inline token kind");
5611
5636
  }
5612
5637
  function parseInlineCommand(value) {
5638
+ if (value.op === "set_equation_numbering") {
5639
+ if (typeof value.numbered !== "boolean") {
5640
+ throw new DocumentCommandError("invalid_command", "numbered must be boolean");
5641
+ }
5642
+ return {
5643
+ op: "set_equation_numbering",
5644
+ field_id: requireString2(value.field_id, "field_id", false).trim(),
5645
+ token_id: requireString2(value.token_id, "token_id", false).trim(),
5646
+ numbered: value.numbered
5647
+ };
5648
+ }
5613
5649
  if (value.op === "insert_inline_token") {
5614
5650
  return {
5615
5651
  op: value.op,
@@ -5663,7 +5699,8 @@ function liveToken(input, id) {
5663
5699
  editable: true,
5664
5700
  sourceOwner: mathObject.source_owner === "editor" ? "editor" : "imported-structured",
5665
5701
  ...mathObject.label_enabled !== void 0 ? { labelEnabled: mathObject.label_enabled } : {},
5666
- ...mathObject.label !== void 0 ? { label: mathObject.label } : {}
5702
+ ...mathObject.label !== void 0 ? { label: mathObject.label } : {},
5703
+ ...mathObject.numbered !== void 0 ? { numbered: mathObject.numbered } : {}
5667
5704
  };
5668
5705
  }
5669
5706
  function insertionIndex(tokens, anchor) {
@@ -5685,6 +5722,17 @@ function applyInlineCommand(document2, command) {
5685
5722
  if (!field) {
5686
5723
  throw new DocumentCommandError("field_not_found", "Inline field was not found");
5687
5724
  }
5725
+ if (command.op === "set_equation_numbering") {
5726
+ const token = field.tokens.find((entry) => entry.id === command.token_id);
5727
+ if (!token || token.kind !== "math") {
5728
+ throw new DocumentCommandError("token_not_found", "Equation token was not found");
5729
+ }
5730
+ if (!supportsSingleEquationNumbering(token)) {
5731
+ throw new DocumentCommandError("invalid_inline_token", "Only a single display equation can be numbered");
5732
+ }
5733
+ token.numbered = command.numbered;
5734
+ return;
5735
+ }
5688
5736
  if (command.op === "insert_inline_token") {
5689
5737
  const index2 = insertionIndex(field.tokens, command.anchor);
5690
5738
  field.tokens.splice(index2, 0, liveToken(command.token, newTokenId(document2, command.token.kind)));
@@ -6037,12 +6085,13 @@ function serializeField(field) {
6037
6085
  }
6038
6086
  value += token.source;
6039
6087
  if (!token.math || token.sourceOwner === "raw") {
6040
- if (token.labelEnabled !== void 0 || token.label !== void 0) {
6088
+ if (token.labelEnabled !== void 0 || token.label !== void 0 || token.numbered !== void 0) {
6041
6089
  hasPersistedMath = true;
6042
6090
  mathObjects.push({
6043
6091
  node_type: "RawMathObject",
6044
6092
  ...token.labelEnabled !== void 0 ? { label_enabled: token.labelEnabled } : {},
6045
- ...token.label !== void 0 ? { label: token.label } : {}
6093
+ ...token.label !== void 0 ? { label: token.label } : {},
6094
+ ...token.numbered !== void 0 ? { numbered: token.numbered } : {}
6046
6095
  });
6047
6096
  } else {
6048
6097
  mathObjects.push(null);
@@ -6055,7 +6104,8 @@ function serializeField(field) {
6055
6104
  ...token.sourceSide ? { source_side: token.sourceSide } : {},
6056
6105
  source_owner: token.sourceOwner,
6057
6106
  ...token.labelEnabled !== void 0 ? { label_enabled: token.labelEnabled } : {},
6058
- ...token.label !== void 0 ? { label: token.label } : {}
6107
+ ...token.label !== void 0 ? { label: token.label } : {},
6108
+ ...token.numbered !== void 0 ? { numbered: token.numbered } : {}
6059
6109
  });
6060
6110
  }
6061
6111
  return { value, formats, mathObjects, hasPersistedMath, inlineIds: inlineIdsFromField(field) };
@@ -6095,6 +6145,7 @@ function blockJson(block) {
6095
6145
  id: block.id,
6096
6146
  command: block.command,
6097
6147
  ...fieldJson(block.field),
6148
+ ...block.command !== "\\paragraph" && block.label ? { label: block.label } : {},
6098
6149
  ...block.metadata ? { metadata: { ...block.metadata } } : {},
6099
6150
  ...block.command === "\\paragraph" ? { centered: block.centered === true } : {}
6100
6151
  };
@@ -6188,7 +6239,7 @@ function toDocumentJson(document2) {
6188
6239
 
6189
6240
  // src/document/jsonCommands.ts
6190
6241
  function isInlineCommand(command) {
6191
- return command.op === "insert_inline_token" || command.op === "replace_inline_token" || command.op === "remove_inline_token";
6242
+ return command.op === "insert_inline_token" || command.op === "replace_inline_token" || command.op === "remove_inline_token" || command.op === "set_equation_numbering";
6192
6243
  }
6193
6244
  function isListCommand(command) {
6194
6245
  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";
@@ -6223,6 +6274,13 @@ function parseBasicCommand(value) {
6223
6274
  text: requireString2(value.text, "text")
6224
6275
  };
6225
6276
  }
6277
+ if (value.op === "set_heading_label") {
6278
+ return {
6279
+ op: value.op,
6280
+ block_id: requireString2(value.block_id, "block_id", false).trim(),
6281
+ label: value.label === null ? null : requireString2(value.label, "label")
6282
+ };
6283
+ }
6226
6284
  if (value.op === "remove_block") {
6227
6285
  return { op: value.op, block_id: requireString2(value.block_id, "block_id", false).trim() };
6228
6286
  }
@@ -6303,7 +6361,7 @@ function parseCommand2(value) {
6303
6361
  if (!isObject3(value) || typeof value.op !== "string") {
6304
6362
  throw new DocumentCommandError("invalid_command", "command requires an op");
6305
6363
  }
6306
- if (value.op === "insert_inline_token" || value.op === "replace_inline_token" || value.op === "remove_inline_token") {
6364
+ if (value.op === "insert_inline_token" || value.op === "replace_inline_token" || value.op === "remove_inline_token" || value.op === "set_equation_numbering") {
6307
6365
  return parseInlineCommand(value);
6308
6366
  }
6309
6367
  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") {
@@ -6315,7 +6373,7 @@ function parseCommand2(value) {
6315
6373
  if (value.op === "update_document_meta" || value.op === "insert_reference" || value.op === "update_reference" || value.op === "remove_reference" || value.op === "move_reference") {
6316
6374
  return parseArticleCommand(value);
6317
6375
  }
6318
- 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") {
6376
+ 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") {
6319
6377
  return parseBasicCommand(value);
6320
6378
  }
6321
6379
  throw new DocumentCommandError("invalid_command", "Unsupported document command");
@@ -6360,6 +6418,20 @@ function applyBasicCommand(document2, command) {
6360
6418
  replacePlainField(document2, block2.field, command.text);
6361
6419
  return;
6362
6420
  }
6421
+ if (command.op === "set_heading_label") {
6422
+ const block2 = document2.blocks.find((entry) => entry.id === command.block_id);
6423
+ if (!block2) throw new DocumentCommandError("block_not_found", "Heading was not found");
6424
+ if (block2.kind !== "textBlock" || block2.command === "\\paragraph") {
6425
+ throw new DocumentCommandError("block_kind_mismatch", "Target is not a heading");
6426
+ }
6427
+ const key = command.label?.trim() ?? "";
6428
+ if (key && documentKeyError(key, { references: document2.references, labels: collectDocumentKeyLabels(document2), excludeOwnerId: block2.id })) {
6429
+ throw new DocumentCommandError("invalid_command", "Heading label is invalid or duplicated");
6430
+ }
6431
+ if (key) block2.label = key;
6432
+ else delete block2.label;
6433
+ return;
6434
+ }
6363
6435
  if (command.op === "remove_block") {
6364
6436
  const index = document2.blocks.findIndex((block2) => block2.id === command.block_id);
6365
6437
  if (index < 0) {
@@ -6437,7 +6509,7 @@ function applyBasicCommand(document2, command) {
6437
6509
  if (label2 !== void 0 && label2.length > 0) {
6438
6510
  const keyError = documentKeyError(label2, {
6439
6511
  references: document2.references,
6440
- labels: collectDocumentLabels(document2),
6512
+ labels: collectDocumentKeyLabels(document2),
6441
6513
  excludeOwnerId: block2.id
6442
6514
  });
6443
6515
  if (keyError === "duplicate") {
@@ -6692,7 +6764,7 @@ function getDocumentReferences(document2) {
6692
6764
  function getDocumentReferenceIndex(document2) {
6693
6765
  const referenceKeys = new Set(document2.references.map((reference) => reference.key));
6694
6766
  const labelEntries = collectDocumentLabels(document2);
6695
- const labelKeys = new Set(labelEntries.map((entry) => entry.key));
6767
+ const labelKeys = new Set(labelNumberMap(document2).keys());
6696
6768
  const citations = [];
6697
6769
  const crossReferences = [];
6698
6770
  const tokenLocations = /* @__PURE__ */ new Map();
@@ -6775,6 +6847,14 @@ function getDocumentReferenceIndex(document2) {
6775
6847
  citations,
6776
6848
  cross_references: crossReferences,
6777
6849
  labels,
6850
+ reference_targets: collectDocumentReferenceTargets(document2).map((target) => ({
6851
+ key: target.key,
6852
+ kind: target.kind,
6853
+ caption: target.caption,
6854
+ number: target.number,
6855
+ ...target.kind === "eq" ? { token_id: target.ownerId } : { block_id: target.ownerId },
6856
+ ...target.manualKey ? { manual_key: target.manualKey } : {}
6857
+ })),
6778
6858
  unresolved: {
6779
6859
  citation_keys: unresolvedCitationKeys,
6780
6860
  cross_reference_keys: unresolvedCrossReferenceKeys
@@ -7079,7 +7159,7 @@ function refTokenLatexForDocument(token, labelKinds, previousToken) {
7079
7159
  }
7080
7160
  return `${semanticRefPrefix(kind)}~${reference}`;
7081
7161
  }
7082
- function tokenLatex(token, labelKinds, previousToken) {
7162
+ function tokenLatex(token, labelKinds, previousToken, unitId) {
7083
7163
  if (token.kind === "text") {
7084
7164
  return styledTextLatex(token.text, token.style);
7085
7165
  }
@@ -7089,12 +7169,15 @@ function tokenLatex(token, labelKinds, previousToken) {
7089
7169
  if (token.kind === "ref") {
7090
7170
  return refTokenLatexForDocument(token, labelKinds, previousToken);
7091
7171
  }
7092
- if (token.display && token.labelEnabled && token.label && token.label.trim().length > 0) {
7172
+ if (isNumberedEquation(token)) {
7093
7173
  const body = mathBodyLatex(token);
7094
- return `\\begin{equation}
7095
- ${body}
7096
- \\label{${token.label.trim()}}
7097
- \\end{equation}`;
7174
+ const autoKey = implicitReferenceKey("eq", token.id, unitId);
7175
+ const aliases = [autoKey];
7176
+ if (token.labelEnabled && token.label?.trim() && token.label.trim() !== autoKey) aliases.push(token.label.trim());
7177
+ return "\\begin{equation}\n" + body + "\n" + aliases.map((key) => "\\label{" + key + "}").join("\n") + "\n\\end{equation}";
7178
+ }
7179
+ if (token.display && token.numbered === false && token.opening === "\\begin{equation}") {
7180
+ return "\\[" + mathBodyLatex(token) + "\\]";
7098
7181
  }
7099
7182
  if (token.sourceOwner === "editor") {
7100
7183
  return editorMathLatexForCompile(token);
@@ -7104,13 +7187,18 @@ ${body}
7104
7187
  }
7105
7188
  return renderMathNodeLatex(token.math);
7106
7189
  }
7107
- function inlineFieldLatexWithLabelKinds(field, labelKinds) {
7108
- return field.tokens.map((token, index) => tokenLatex(token, labelKinds, field.tokens[index - 1])).join("");
7190
+ function inlineFieldLatexWithLabelKinds(field, labelKinds, unitId) {
7191
+ return field.tokens.map((token, index) => tokenLatex(token, labelKinds, field.tokens[index - 1], unitId)).join("");
7109
7192
  }
7110
- function textBlockLatex(block, labelKinds) {
7111
- const content = inlineFieldLatexWithLabelKinds(block.field, labelKinds);
7193
+ function textBlockLatex(block, labelKinds, unitId) {
7194
+ const content = inlineFieldLatexWithLabelKinds(block.field, labelKinds, unitId);
7112
7195
  const body = block.command === "\\paragraph" ? `\\par
7113
7196
  ${content}` : `${block.command}{${content}}`;
7197
+ if (block.command !== "\\paragraph") {
7198
+ const keys = unitId ? [implicitHeadingReferenceKey(block.command.slice(1), block.id, unitId)] : [];
7199
+ if (block.label?.trim() && !keys.includes(block.label.trim())) keys.push(block.label.trim());
7200
+ return [body, ...keys.map((key) => `\\label{${key}}`)].join("\n");
7201
+ }
7114
7202
  if (block.command === "\\paragraph" && block.centered) {
7115
7203
  return `\\begin{center}
7116
7204
  ${body}
@@ -7121,10 +7209,10 @@ ${body}
7121
7209
  function indent(value) {
7122
7210
  return value.split("\n").map((line) => ` ${line}`).join("\n");
7123
7211
  }
7124
- function listBlockLatex(block, references, labelKinds, fixedFloats) {
7212
+ function listBlockLatex(block, references, labelKinds, fixedFloats, unitId) {
7125
7213
  const items = block.items.map((item) => {
7126
- const nested = item.blocks.map((child) => "\n" + indent(blockLatex(child, references, labelKinds, fixedFloats))).join("");
7127
- return ` \\item ${inlineFieldLatexWithLabelKinds(item.field, labelKinds)}${nested}`;
7214
+ const nested = item.blocks.map((child) => "\n" + indent(blockLatex(child, references, labelKinds, fixedFloats, unitId))).join("");
7215
+ return ` \\item ${inlineFieldLatexWithLabelKinds(item.field, labelKinds, unitId)}${nested}`;
7128
7216
  }).join("\n");
7129
7217
  return `${block.command}
7130
7218
  ${items}
@@ -7138,9 +7226,9 @@ function defaultGridColumnSpec(block) {
7138
7226
  }
7139
7227
  return `|${compact.split("").join("|")}|`;
7140
7228
  }
7141
- function tabularInnerLatex(block, labelKinds) {
7229
+ function tabularInnerLatex(block, labelKinds, unitId) {
7142
7230
  const rows = block.rows.map(
7143
- (row) => ` ${row.map((cell) => inlineFieldLatexWithLabelKinds(cell, labelKinds)).join(" & ")}`
7231
+ (row) => ` ${row.map((cell) => inlineFieldLatexWithLabelKinds(cell, labelKinds, unitId)).join(" & ")}`
7144
7232
  );
7145
7233
  const gridColumns = defaultGridColumnSpec(block);
7146
7234
  if (gridColumns) {
@@ -7154,29 +7242,30 @@ ${block.closing}`;
7154
7242
  ${rows.join(" \\\\\n")}
7155
7243
  ${block.closing}`;
7156
7244
  }
7157
- function floatCaptionLabelLines(block, counter, labelKinds) {
7245
+ function floatCaptionLabelLines(block, counter, labelKinds, unitId) {
7158
7246
  const lines = [];
7159
- const caption = inlineFieldLatexWithLabelKinds(block.captionField, labelKinds).trim();
7247
+ const caption = inlineFieldLatexWithLabelKinds(block.captionField, labelKinds, unitId).trim();
7160
7248
  const hasCaption = block.captionEnabled && caption.length > 0;
7161
7249
  if (hasCaption) {
7162
7250
  lines.push(` \\caption{${caption}}`);
7163
7251
  }
7164
- if (block.labelEnabled && block.label.trim().length > 0) {
7165
- if (!hasCaption) {
7166
- lines.push(` \\refstepcounter{${counter}}`);
7167
- }
7168
- lines.push(` \\label{${block.label.trim()}}`);
7252
+ const hasManualLabel = block.labelEnabled && block.label.trim().length > 0;
7253
+ if (hasCaption || hasManualLabel) {
7254
+ if (!hasCaption) lines.push(" \\refstepcounter{" + counter + "}");
7255
+ const autoKey = implicitReferenceKey(counter === "figure" ? "fig" : "tab", block.id, unitId);
7256
+ lines.push(" \\label{" + autoKey + "}");
7257
+ if (hasManualLabel && block.label.trim() !== autoKey) lines.push(" \\label{" + block.label.trim() + "}");
7169
7258
  }
7170
7259
  return lines;
7171
7260
  }
7172
- function tableBlockLatex(block, labelKinds, fixedFloats) {
7261
+ function tableBlockLatex(block, labelKinds, fixedFloats, unitId) {
7173
7262
  const placement = fixedFloats ? "H" : "htbp";
7174
7263
  const lines = [`\\begin{table}[${placement}]`];
7175
7264
  if (block.centered) {
7176
7265
  lines.push(" \\centering");
7177
7266
  }
7178
- lines.push(...floatCaptionLabelLines(block, "table", labelKinds));
7179
- lines.push(indent(tabularInnerLatex(block, labelKinds)));
7267
+ lines.push(...floatCaptionLabelLines(block, "table", labelKinds, unitId));
7268
+ lines.push(indent(tabularInnerLatex(block, labelKinds, unitId)));
7180
7269
  lines.push("\\end{table}");
7181
7270
  return lines.join("\n");
7182
7271
  }
@@ -7195,29 +7284,29 @@ function imageOptionsLatex(block, constrainToColumn) {
7195
7284
  }
7196
7285
  return `[${entries.map(([key, value]) => `${key}=${value}`).join(",")}]`;
7197
7286
  }
7198
- function imageBlockLatex(block, labelKinds, fixedFloats) {
7287
+ function imageBlockLatex(block, labelKinds, fixedFloats, unitId) {
7199
7288
  const placement = fixedFloats ? "H" : "htbp";
7200
7289
  const lines = [`\\begin{figure}[${placement}]`];
7201
7290
  if (block.centered) {
7202
7291
  lines.push(" \\centering");
7203
7292
  }
7204
7293
  lines.push(` ${block.command}${imageOptionsLatex(block, true)}{${block.value}}`);
7205
- lines.push(...floatCaptionLabelLines(block, "figure", labelKinds));
7294
+ lines.push(...floatCaptionLabelLines(block, "figure", labelKinds, unitId));
7206
7295
  lines.push("\\end{figure}");
7207
7296
  return lines.join("\n");
7208
7297
  }
7209
- function blockLatex(block, references, labelKinds, fixedFloats) {
7298
+ function blockLatex(block, references, labelKinds, fixedFloats, unitId) {
7210
7299
  if (block.kind === "textBlock") {
7211
- return textBlockLatex(block, labelKinds);
7300
+ return textBlockLatex(block, labelKinds, unitId);
7212
7301
  }
7213
7302
  if (block.kind === "list") {
7214
- return listBlockLatex(block, references, labelKinds, fixedFloats);
7303
+ return listBlockLatex(block, references, labelKinds, fixedFloats, unitId);
7215
7304
  }
7216
7305
  if (block.kind === "table") {
7217
- return tableBlockLatex(block, labelKinds, fixedFloats);
7306
+ return tableBlockLatex(block, labelKinds, fixedFloats, unitId);
7218
7307
  }
7219
7308
  if (block.kind === "image") {
7220
- return imageBlockLatex(block, labelKinds, fixedFloats);
7309
+ return imageBlockLatex(block, labelKinds, fixedFloats, unitId);
7221
7310
  }
7222
7311
  if (block.kind === "bibliography") {
7223
7312
  const width = String(Math.max(references.length, 9));
@@ -7261,10 +7350,8 @@ ${meta.abstract.trim()}
7261
7350
  }
7262
7351
  function documentLabelKindMap(document2) {
7263
7352
  const map = /* @__PURE__ */ new Map();
7264
- for (const entry of collectDocumentLabels(document2)) {
7265
- if (!map.has(entry.key)) {
7266
- map.set(entry.key, entry.kind);
7267
- }
7353
+ for (const [key, entry] of labelNumberMap(document2)) {
7354
+ map.set(key, entry.kind);
7268
7355
  }
7269
7356
  return map;
7270
7357
  }
@@ -7273,6 +7360,17 @@ function closingHamdalaLatex() {
7273
7360
  \\maghribi{${BUTEX_CLOSING_HAMDALA}}
7274
7361
  \\end{center}`;
7275
7362
  }
7363
+ function documentContentLatex(document2, context) {
7364
+ if (!context?.unitId?.trim()) throw new Error("book-content export requires a stable unitId");
7365
+ const labelKinds = documentLabelKindMap(document2);
7366
+ for (const target of context?.targets ?? []) {
7367
+ if (target.kind === "fig" || target.kind === "tab" || target.kind === "eq") {
7368
+ labelKinds.set(target.key, target.kind);
7369
+ if (target.manualKey) labelKinds.set(target.manualKey, target.kind);
7370
+ }
7371
+ }
7372
+ 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");
7373
+ }
7276
7374
  function documentLatex(document2, options = {}) {
7277
7375
  const meta = document2.meta ?? emptyDocumentMeta();
7278
7376
  const twocolumn = options.twocolumn === true;
@@ -7363,10 +7461,17 @@ function validateToken(context, token, path, blockId) {
7363
7461
  return;
7364
7462
  }
7365
7463
  validateTextValue(context, token.source, `${path}.source`, blockId, token.id);
7464
+ if (token.numbered === true && !supportsSingleEquationNumbering(token)) {
7465
+ addIssue(context, "invalid_equation_label", `${path}.numbered`, blockId, token.id);
7466
+ }
7366
7467
  if (!token.labelEnabled) {
7367
7468
  return;
7368
7469
  }
7369
- if (!token.display) {
7470
+ if (!supportsSingleEquationNumbering(token)) {
7471
+ addIssue(context, "invalid_equation_label", `${path}.label`, blockId, token.id);
7472
+ return;
7473
+ }
7474
+ if (!isNumberedEquation(token)) {
7370
7475
  addIssue(context, "invalid_equation_label", `${path}.label`, blockId, token.id);
7371
7476
  return;
7372
7477
  }
@@ -7380,6 +7485,13 @@ function validateInlineField(context, field, path, blockId) {
7380
7485
  function validateBlock(context, block, path) {
7381
7486
  if (block.kind === "textBlock") {
7382
7487
  validateInlineField(context, block.field, `${path}.field`, block.id);
7488
+ if (block.command !== "\\paragraph") {
7489
+ const kind = block.command.slice(1);
7490
+ if (block.label) registerKey(context, block.label, `${path}.label`, kind, block.id);
7491
+ if (context.bookMode && context.bookContext) {
7492
+ context.labelKinds.set(implicitHeadingReferenceKey(kind, block.id, context.bookContext.unitId), kind);
7493
+ }
7494
+ }
7383
7495
  return;
7384
7496
  }
7385
7497
  if (block.kind === "list") {
@@ -7429,6 +7541,10 @@ function validateBlock(context, block, path) {
7429
7541
  }
7430
7542
  return;
7431
7543
  }
7544
+ if (block.kind === "bibliography" && context.bookMode) {
7545
+ addIssue(context, "book_local_bibliography", path, block.id);
7546
+ return;
7547
+ }
7432
7548
  if (block.kind === "raw") {
7433
7549
  validateTextValue(context, block.value, `${path}.value`, block.id);
7434
7550
  }
@@ -7451,7 +7567,7 @@ function validateDuplicateKeys(context) {
7451
7567
  }
7452
7568
  function validatePendingReferences(context) {
7453
7569
  for (const pending of context.pendingCitations) {
7454
- if (pending.token.keys.some((key) => !isValidDocumentKey(normalizeDocumentKey(key)))) {
7570
+ if (pending.token.keys.some((key) => !isValidDocumentKey(normalizeDocumentKey(key)) || context.citationKeys !== void 0 && !context.citationKeys.has(normalizeDocumentKey(key)))) {
7455
7571
  addIssue(
7456
7572
  context,
7457
7573
  "missing_citation",
@@ -7464,7 +7580,7 @@ function validatePendingReferences(context) {
7464
7580
  for (const pending of context.pendingReferences) {
7465
7581
  for (const key of pending.token.keys) {
7466
7582
  const normalized = normalizeDocumentKey(key);
7467
- if (!isValidDocumentKey(normalized)) {
7583
+ if (!isValidDocumentKey(normalized) || !context.labelKinds.has(normalized)) {
7468
7584
  addIssue(
7469
7585
  context,
7470
7586
  "missing_reference",
@@ -7533,7 +7649,7 @@ function resolveDocument(document2) {
7533
7649
  return null;
7534
7650
  }
7535
7651
  }
7536
- function validateDocument(document2) {
7652
+ function validateDocument(document2, options = {}) {
7537
7653
  const resolved = resolveDocument(document2);
7538
7654
  if (!resolved) {
7539
7655
  return {
@@ -7545,6 +7661,9 @@ function validateDocument(document2) {
7545
7661
  issues: [],
7546
7662
  keyOwners: [],
7547
7663
  labelKinds: /* @__PURE__ */ new Map(),
7664
+ bookMode: options.mode === "book-content",
7665
+ bookContext: options.bookContext,
7666
+ ...options.mode === "book-content" && options.bookContext?.references ? { citationKeys: new Set(options.bookContext.references.map((entry) => normalizeDocumentKey(entry.key))) } : {},
7548
7667
  pendingCitations: [],
7549
7668
  pendingReferences: []
7550
7669
  };
@@ -7563,6 +7682,28 @@ function validateDocument(document2) {
7563
7682
  resolved.blocks.forEach((block, index) => {
7564
7683
  validateBlock(context, block, `$.blocks[${String(index)}]`);
7565
7684
  });
7685
+ for (const target of collectDocumentReferenceTargets(resolved)) {
7686
+ const autoKey = context.bookMode && context.bookContext ? implicitReferenceKey(target.kind, target.ownerId, context.bookContext.unitId) : target.key;
7687
+ if (target.number !== null && target.manualKey !== autoKey) {
7688
+ registerKey(
7689
+ context,
7690
+ autoKey,
7691
+ "$.automatic_labels",
7692
+ target.kind,
7693
+ target.kind === "eq" ? void 0 : target.ownerId,
7694
+ target.kind === "eq" ? target.ownerId : void 0
7695
+ );
7696
+ }
7697
+ }
7698
+ if (context.bookMode) {
7699
+ for (const target of context.bookContext?.targets ?? []) {
7700
+ context.labelKinds.set(normalizeDocumentKey(target.key), target.kind);
7701
+ if (target.manualKey) context.labelKinds.set(normalizeDocumentKey(target.manualKey), target.kind);
7702
+ }
7703
+ }
7704
+ if (context.bookMode && !context.bookContext?.unitId?.trim()) {
7705
+ addIssue(context, "book_context_required", "$.book_context");
7706
+ }
7566
7707
  for (const diagnostic of resolved.diagnostics) {
7567
7708
  addIssue(context, "parser_diagnostic", diagnostic.path);
7568
7709
  }
@@ -7590,6 +7731,11 @@ function documentLatex2(document2, options = {}) {
7590
7731
  }
7591
7732
  return documentLatex(document2, options);
7592
7733
  }
7734
+ function documentContentLatex2(document2, context) {
7735
+ const validation = validateDocument(document2, { mode: "book-content", bookContext: context });
7736
+ if (!validation.valid) throw new DocumentValidationError(validation.issues);
7737
+ return documentContentLatex(document2, context);
7738
+ }
7593
7739
 
7594
7740
  // src/document-cli/mathDiagnostic.ts
7595
7741
  function compactError(error) {
@@ -7707,9 +7853,28 @@ function parseDocumentWorkerRequest(value) {
7707
7853
  if (!("document" in value)) {
7708
7854
  throw new DocumentWorkerProtocolError("invalid_request", "Worker request requires a document");
7709
7855
  }
7710
- if (value.action === "normalize" || value.action === "outline" || value.action === "references" || value.action === "reference_index" || value.action === "export") {
7856
+ if (value.action === "normalize" || value.action === "outline" || value.action === "references" || value.action === "reference_index") {
7711
7857
  return { action: value.action, document: value.document };
7712
7858
  }
7859
+ if (value.action === "export") {
7860
+ if (value.mode !== void 0 && value.mode !== "article" && value.mode !== "book-content") {
7861
+ throw new DocumentWorkerProtocolError("invalid_request", "Unsupported export mode");
7862
+ }
7863
+ if (value.mode === "book-content" && value.book_context === void 0) {
7864
+ throw new DocumentWorkerProtocolError("invalid_request", "book-content export requires book_context with unitId");
7865
+ }
7866
+ if (value.book_context !== void 0) {
7867
+ const ctx = value.book_context;
7868
+ if (!isObject4(ctx) || typeof ctx.unitId !== "string" || !ctx.unitId.trim() || ctx.references !== void 0 && (!Array.isArray(ctx.references) || ctx.references.some((entry) => !isObject4(entry) || typeof entry.key !== "string")) || ctx.targets !== void 0 && (!Array.isArray(ctx.targets) || ctx.targets.some((entry) => !isObject4(entry) || typeof entry.key !== "string" || typeof entry.unitId !== "string" || typeof entry.ownerId !== "string" || typeof entry.kind !== "string"))) {
7869
+ throw new DocumentWorkerProtocolError("invalid_request", "Invalid book_context");
7870
+ }
7871
+ if (value.mode !== "book-content") {
7872
+ throw new DocumentWorkerProtocolError("invalid_request", "book_context requires book-content mode");
7873
+ }
7874
+ return { action: "export", document: value.document, mode: "book-content", book_context: ctx };
7875
+ }
7876
+ return { action: "export", document: value.document, ...value.mode ? { mode: value.mode } : {} };
7877
+ }
7713
7878
  if (value.action === "apply_command") {
7714
7879
  if (!("command" in value)) {
7715
7880
  throw new DocumentWorkerProtocolError("invalid_request", "apply_command requires command");
@@ -7858,7 +8023,7 @@ function executeDocumentWorkerRequest(input) {
7858
8023
  const document2 = resolveDocument2(request.document);
7859
8024
  return {
7860
8025
  ok: true,
7861
- latex: documentLatex2(document2, { twocolumn: true }),
8026
+ latex: request.mode === "book-content" ? documentContentLatex2(document2, request.book_context) : documentLatex2(document2, { twocolumn: true }),
7862
8027
  asset_ids: collectAssetIds(document2.blocks)
7863
8028
  };
7864
8029
  }