@drghaliasri/butex 7.0.0 → 7.0.3

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.
@@ -17,6 +17,34 @@ function document2Id(prefix) {
17
17
  return id;
18
18
  }
19
19
 
20
+ // src/editor/digits.ts
21
+ var WESTERN = "0123456789";
22
+ var ARABIC_INDIC = "\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669";
23
+ var PERSIAN_INDIC = "\u06F0\u06F1\u06F2\u06F3\u06F4\u06F5\u06F6\u06F7\u06F8\u06F9";
24
+ var digitSets = {
25
+ western: WESTERN,
26
+ arabicIndic: ARABIC_INDIC,
27
+ persianIndic: PERSIAN_INDIC
28
+ };
29
+ function digitValue(char) {
30
+ const western = WESTERN.indexOf(char);
31
+ if (western >= 0) {
32
+ return western;
33
+ }
34
+ const arabicIndic = ARABIC_INDIC.indexOf(char);
35
+ if (arabicIndic >= 0) {
36
+ return arabicIndic;
37
+ }
38
+ return PERSIAN_INDIC.indexOf(char);
39
+ }
40
+ function formatDigits(value, digitForm = "western") {
41
+ const target = digitSets[digitForm];
42
+ return Array.from(value, (char) => {
43
+ const value2 = digitValue(char);
44
+ return value2 >= 0 ? target[value2] : char;
45
+ }).join("");
46
+ }
47
+
20
48
  // src/document2/articleMeta.ts
21
49
  var BUTEX_BASMALA_LINE1 = "\u0628\u0650\u0633\u0652\u0645\u0650 \u0671\u0644\u0644\u064E\u0651\u0670\u0647\u0650 \u0671\u0644\u0631\u064E\u0651\u062D\u0652\u0645\u064E\u0670\u0646\u0650 \u0671\u0644\u0631\u064E\u0651\u062D\u0650\u064A\u0645\u0650";
22
50
  var BUTEX_BASMALA_LINE2 = "\u0648\u064E\u0671\u0644\u0635\u064E\u0651\u0644\u064E\u0627\u0629\u064F \u0648\u064E\u0671\u0644\u0633\u064E\u0651\u0644\u064E\u0627\u0645\u064F \u0639\u064E\u0644\u064E\u0649\u0670 \u0631\u064E\u0633\u064F\u0648\u0644\u0650 \u0671\u0644\u0644\u064E\u0651\u0670\u0647\u0650";
@@ -24,6 +52,70 @@ var BUTEX_BASMALA_SALAWAT = "\u0635\u064E\u0644\u064E\u0651\u0649 \u0671\u0644\u
24
52
  var BUTEX_BASMALA = `${BUTEX_BASMALA_LINE1}
25
53
  ${BUTEX_BASMALA_LINE2}
26
54
  ${BUTEX_BASMALA_SALAWAT}`;
55
+ var BUTEX_CLOSING_HAMDALA = "\u0627\u0644\u0652\u062D\u064E\u0645\u0652\u062F\u064F \u0644\u0650\u0644\u064E\u0651\u0647\u0650 \u0646\u064E\u0641\u064E\u0639\u064E\u0646\u064E\u0627 \u0628\u0650\u0639\u0650\u0644\u0652\u0645\u0650\u0647\u0650";
56
+ function escapeButexTextArg(text) {
57
+ return text.replace(/\\/g, "\\textbackslash{}").replace(/[{}]/g, "\\$&");
58
+ }
59
+ function butexFontDisplayTex(macro, text) {
60
+ return `${macro}{${escapeButexTextArg(text)}}`;
61
+ }
62
+ function butexMaghribiDisplayTex(text) {
63
+ return butexFontDisplayTex("\\butexmaghribi", text);
64
+ }
65
+ var BASMALA_LINES = [BUTEX_BASMALA_LINE1, BUTEX_BASMALA_LINE2, BUTEX_BASMALA_SALAWAT];
66
+ function butexBasmalaDisplayLatex() {
67
+ return `\\[
68
+ \\begin{gathered}
69
+ ${BASMALA_LINES.map((line) => butexMaghribiDisplayTex(line)).join(" \\\\\n")}
70
+ \\end{gathered}
71
+ \\]`;
72
+ }
73
+ function butexInColumnMaketitleHook() {
74
+ return String.raw`\makeatletter
75
+ \renewcommand{\maketitle}{%
76
+ \par
77
+ \begingroup
78
+ \renewcommand\thefootnote{\@fnsymbol\c@footnote}%
79
+ \def\@makefnmark{\rlap{\@textsuperscript{\normalfont\@thefnmark}}}%
80
+ \long\def\@makefntext##1{\parindent 1em\noindent
81
+ \hb@xt@1.8em{\hss\@textsuperscript{\normalfont\@thefnmark}}##1}%
82
+ \@maketitle
83
+ \thispagestyle{plain}\@thanks
84
+ \endgroup
85
+ \setcounter{footnote}{0}%
86
+ \global\let\thanks\relax
87
+ \global\let\maketitle\relax
88
+ \global\let\@maketitle\relax
89
+ \global\let\@thanks\@empty
90
+ \global\let\@author\@empty
91
+ \global\let\@date\@empty
92
+ \global\let\@title\@empty
93
+ \global\let\title\relax
94
+ \global\let\author\relax
95
+ \global\let\date\relax
96
+ \global\let\and\relax
97
+ }
98
+ \makeatother`;
99
+ }
100
+ function butexBasmalaTitlingPreamble(options = {}) {
101
+ const lines = [
102
+ "\\usepackage{titling}",
103
+ "\\pretitle{%",
104
+ " \\begin{center}",
105
+ ...BASMALA_LINES.map((line, index) => {
106
+ const suffix = index < BASMALA_LINES.length - 1 ? "\\\\" : "";
107
+ return ` ${butexMaghribiDisplayTex(line)}${suffix}`;
108
+ }),
109
+ " \\par\\vspace{1.5em}",
110
+ " \\LARGE",
111
+ "}",
112
+ "\\posttitle{\\par\\end{center}}"
113
+ ];
114
+ if (options.twocolumn) {
115
+ lines.push(butexInColumnMaketitleHook());
116
+ }
117
+ return lines.join("\n");
118
+ }
27
119
  var HIJRI_YEAR_MIN = 1400;
28
120
  var HIJRI_YEAR_MAX = 1500;
29
121
  var HIJRI_MONTH_IDS = [
@@ -40,6 +132,20 @@ var HIJRI_MONTH_IDS = [
40
132
  "\u0630\u0648 \u0627\u0644\u0642\u0639\u062F\u0629",
41
133
  "\u0630\u0648 \u0627\u0644\u062D\u062C\u0629"
42
134
  ];
135
+ var HIJRI_MONTH_LABELS_EN = {
136
+ \u0645\u062D\u0631\u0645: "Muharram",
137
+ \u0635\u0641\u0631: "Safar",
138
+ "\u0631\u0628\u064A\u0639 \u0627\u0644\u0623\u0648\u0644": "Rabi\u02BB I",
139
+ "\u0631\u0628\u064A\u0639 \u0627\u0644\u0622\u062E\u0631": "Rabi\u02BB II",
140
+ "\u062C\u0645\u0627\u062F\u0649 \u0627\u0644\u0623\u0648\u0644\u0649": "Jumada I",
141
+ "\u062C\u0645\u0627\u062F\u0649 \u0627\u0644\u0622\u062E\u0631\u0629": "Jumada II",
142
+ \u0631\u062C\u0628: "Rajab",
143
+ \u0634\u0639\u0628\u0627\u0646: "Sha\u02BBban",
144
+ \u0631\u0645\u0636\u0627\u0646: "Ramadan",
145
+ \u0634\u0648\u0627\u0644: "Shawwal",
146
+ "\u0630\u0648 \u0627\u0644\u0642\u0639\u062F\u0629": "Dhul Qa\u02BBdah",
147
+ "\u0630\u0648 \u0627\u0644\u062D\u062C\u0629": "Dhul Hijjah"
148
+ };
43
149
  var LEGACY_LATIN_MONTH = {
44
150
  muharram: "\u0645\u062D\u0631\u0645",
45
151
  safar: "\u0635\u0641\u0631",
@@ -59,6 +165,9 @@ var DEFAULT_HIJRI_DATE = {
59
165
  month: "\u0645\u062D\u0631\u0645",
60
166
  year: 1448
61
167
  };
168
+ function hijriMonthLabel(month, locale = "ar") {
169
+ return locale === "en" ? HIJRI_MONTH_LABELS_EN[month] : month;
170
+ }
62
171
  function emptyDocument2Meta() {
63
172
  return {
64
173
  title: "",
@@ -107,6 +216,24 @@ function normalizeDocument2Meta(value) {
107
216
  abstract: typeof raw.abstract === "string" ? raw.abstract : ""
108
217
  };
109
218
  }
219
+ function document2HasMaketitle(meta) {
220
+ return meta.title.trim().length > 0 || meta.authors.trim().length > 0;
221
+ }
222
+ function document2HasAbstract(meta) {
223
+ return meta.abstract.trim().length > 0;
224
+ }
225
+ function formatHijriDate(date, options = "ar") {
226
+ const opts = typeof options === "string" ? { locale: options } : options;
227
+ const locale = opts.locale ?? "ar";
228
+ const digitForm = opts.digitForm ?? (locale === "en" ? "western" : "arabicIndic");
229
+ const month = hijriMonthLabel(date.month, locale);
230
+ const day = formatDigits(String(date.day), digitForm);
231
+ const year = formatDigits(String(date.year), digitForm);
232
+ if (locale === "en") {
233
+ return `${day} ${month} ${year} AH`;
234
+ }
235
+ return `${day} ${month} ${year}\u0647\u0640`;
236
+ }
110
237
 
111
238
  // src/document2/citations.ts
112
239
  var DEFAULT_REFERENCE_FIELD_SEPARATOR = "\u060C";
@@ -135,6 +262,16 @@ function referenceFromJson(json) {
135
262
  fieldSeparator: normalizeReferenceFieldSeparator(json.field_separator)
136
263
  };
137
264
  }
265
+ function bibliographyEntryBody(reference, separator = reference.fieldSeparator, options = {}) {
266
+ const year = options.digitForm !== void 0 ? formatDigits(reference.year, options.digitForm) : reference.year;
267
+ const parts = [reference.authors, reference.title, reference.venue, year].filter((part) => part.trim().length > 0);
268
+ return parts.join(`${separator} `);
269
+ }
270
+ function bibliographyEntryLatex(reference) {
271
+ const body = bibliographyEntryBody(reference);
272
+ const url = reference.url.trim().length > 0 ? ` \\url{${reference.url}}` : "";
273
+ return `\\bibitem{${reference.key}} ${body}${url}`.trim();
274
+ }
138
275
 
139
276
  // src/ast/commands/index.ts
140
277
  function renderCommandCore(context) {
@@ -544,6 +681,26 @@ function toMathObjectJson(math) {
544
681
  closing: math.closing
545
682
  };
546
683
  }
684
+ function renderMathNodeLatex(math) {
685
+ const lines = math.lines.map((line) => line.arabicLatex());
686
+ if (math.mathMode === "$" || math.mathMode === "\\(") {
687
+ return math.mathMode + lines.join(" ") + math.closing;
688
+ }
689
+ if (math.mathMode === "$$" || math.mathMode === "\\[") {
690
+ if (lines.length === 1) {
691
+ return math.mathMode + "\n" + lines[0] + "\n" + math.closing;
692
+ }
693
+ return math.mathMode + "\n" + lines.map((line) => ` ${line}`).join(" \\\\\n") + "\n" + math.closing;
694
+ }
695
+ if (lines.length === 1) {
696
+ return `${math.mathMode}
697
+ ${lines[0]}
698
+ ${math.closing}`;
699
+ }
700
+ return `${math.mathMode}
701
+ ${lines.map((line) => ` ${line}`).join(" \\\\\n")}
702
+ ${math.closing}`;
703
+ }
547
704
 
548
705
  // src/document2/labels.ts
549
706
  function defaultFloatMeta() {
@@ -587,6 +744,99 @@ function refTokenLatex(keys, refCommand) {
587
744
  const command = refCommand === "eqref" ? "\\eqref" : "\\ref";
588
745
  return `${command}{${keys.join(",")}}`;
589
746
  }
747
+ function collectDocument2Labels(document2) {
748
+ const entries = [];
749
+ const counters = { fig: 0, tab: 0, eq: 0 };
750
+ function pushEqFromField(tokens) {
751
+ for (const token of tokens) {
752
+ if (token.kind !== "math") {
753
+ continue;
754
+ }
755
+ if (token.display && token.labelEnabled && token.label && token.label.trim().length > 0) {
756
+ counters.eq += 1;
757
+ entries.push({
758
+ key: token.label.trim(),
759
+ kind: "eq",
760
+ caption: "",
761
+ ownerId: token.id,
762
+ number: counters.eq
763
+ });
764
+ }
765
+ }
766
+ }
767
+ function walk(blocks) {
768
+ for (const block of blocks) {
769
+ if (block.kind === "image" && block.labelEnabled && block.label.trim().length > 0) {
770
+ counters.fig += 1;
771
+ entries.push({
772
+ key: block.label.trim(),
773
+ kind: "fig",
774
+ caption: block.captionEnabled ? block.caption : "",
775
+ ownerId: block.id,
776
+ number: counters.fig
777
+ });
778
+ }
779
+ if (block.kind === "table") {
780
+ if (block.labelEnabled && block.label.trim().length > 0) {
781
+ counters.tab += 1;
782
+ entries.push({
783
+ key: block.label.trim(),
784
+ kind: "tab",
785
+ caption: block.captionEnabled ? block.caption : "",
786
+ ownerId: block.id,
787
+ number: counters.tab
788
+ });
789
+ }
790
+ for (const row of block.rows) {
791
+ for (const cell of row) {
792
+ pushEqFromField(cell.tokens);
793
+ }
794
+ }
795
+ }
796
+ if (block.kind === "textBlock") {
797
+ pushEqFromField(block.field.tokens);
798
+ }
799
+ if (block.kind === "list") {
800
+ for (const item of block.items) {
801
+ pushEqFromField(item.field.tokens);
802
+ walk(item.blocks);
803
+ }
804
+ }
805
+ }
806
+ }
807
+ walk(document2.blocks);
808
+ return entries;
809
+ }
810
+ function stripDisplayMathDelimiters(source) {
811
+ const trimmed = source.trim();
812
+ if (trimmed.startsWith("\\[") && trimmed.endsWith("\\]")) {
813
+ return trimmed.slice(2, -2).trim();
814
+ }
815
+ if (trimmed.startsWith("$$") && trimmed.endsWith("$$")) {
816
+ return trimmed.slice(2, -2).trim();
817
+ }
818
+ if (trimmed.startsWith("\\begin{equation}") && trimmed.endsWith("\\end{equation}")) {
819
+ return trimmed.slice("\\begin{equation}".length, -"\\end{equation}".length).trim();
820
+ }
821
+ return trimmed;
822
+ }
823
+ function applyFloatMetaPatch(block, patch) {
824
+ if (typeof patch.centered === "boolean") {
825
+ block.centered = patch.centered;
826
+ }
827
+ if (typeof patch.captionEnabled === "boolean") {
828
+ block.captionEnabled = patch.captionEnabled;
829
+ }
830
+ if (typeof patch.caption === "string") {
831
+ block.caption = patch.caption;
832
+ }
833
+ if (typeof patch.labelEnabled === "boolean") {
834
+ block.labelEnabled = patch.labelEnabled;
835
+ }
836
+ if (typeof patch.label === "string") {
837
+ block.label = patch.label;
838
+ }
839
+ }
590
840
 
591
841
  // src/document2/inlineIdentity.ts
592
842
  function createDocument2IdentityState() {
@@ -1760,6 +2010,68 @@ var ATOMIC_OPERATOR_COMMANDS = {
1760
2010
  };
1761
2011
  var MIRRORED_OPERATOR_TEX = Object.values(ATOMIC_OPERATOR_COMMANDS).filter((command) => command.mirror).map((command) => command.Tex).sort((a, b) => b.length - a.length);
1762
2012
  var COMPILE_MIRRORED_OPERATOR_TEX = Object.values(ATOMIC_OPERATOR_COMMANDS).filter((command) => "compileMirror" in command && command.compileMirror).map((command) => command.Tex).sort((a, b) => b.length - a.length);
2013
+ function matchingMirroredOperatorFrom(tex, index, operatorTexList) {
2014
+ for (const operatorTex of operatorTexList) {
2015
+ if (!tex.startsWith(operatorTex, index)) {
2016
+ continue;
2017
+ }
2018
+ const next = tex[index + operatorTex.length];
2019
+ if (next != null && /[A-Za-z]/.test(next)) {
2020
+ continue;
2021
+ }
2022
+ return operatorTex;
2023
+ }
2024
+ return null;
2025
+ }
2026
+ function findMatchingBrace(tex, openIndex) {
2027
+ let depth = 0;
2028
+ for (let index = openIndex; index < tex.length; index += 1) {
2029
+ const char = tex[index];
2030
+ if (char === "\\") {
2031
+ index += 1;
2032
+ continue;
2033
+ }
2034
+ if (char === "{") {
2035
+ depth += 1;
2036
+ } else if (char === "}") {
2037
+ depth -= 1;
2038
+ if (depth === 0) {
2039
+ return index;
2040
+ }
2041
+ }
2042
+ }
2043
+ return -1;
2044
+ }
2045
+ function mirrorBuTeXOperatorsInTex(tex, options = {}) {
2046
+ const mirroredOperatorTex = options.target === "compile" ? COMPILE_MIRRORED_OPERATOR_TEX : MIRRORED_OPERATOR_TEX;
2047
+ let result = "";
2048
+ let index = 0;
2049
+ while (index < tex.length) {
2050
+ if (tex.startsWith("\\butexmirror{", index)) {
2051
+ const end = findMatchingBrace(tex, index + "\\butexmirror".length);
2052
+ if (end !== -1) {
2053
+ const bodyStart = index + "\\butexmirror{".length;
2054
+ const body = tex.slice(bodyStart, end);
2055
+ if (options.target === "compile" && MIRRORED_OPERATOR_TEX.includes(body) && !mirroredOperatorTex.includes(body)) {
2056
+ result += body;
2057
+ } else {
2058
+ result += tex.slice(index, end + 1);
2059
+ }
2060
+ index = end + 1;
2061
+ continue;
2062
+ }
2063
+ }
2064
+ const operatorTex = matchingMirroredOperatorFrom(tex, index, mirroredOperatorTex);
2065
+ if (operatorTex) {
2066
+ result += `\\butexmirror{${operatorTex}}`;
2067
+ index += operatorTex.length;
2068
+ continue;
2069
+ }
2070
+ result += tex[index];
2071
+ index += 1;
2072
+ }
2073
+ return result;
2074
+ }
1763
2075
 
1764
2076
  // src/editor/characterFonts.ts
1765
2077
  var CHARACTER_FONT_SPECS = [
@@ -2578,6 +2890,12 @@ function requireBoolean(value, field) {
2578
2890
  }
2579
2891
  return value;
2580
2892
  }
2893
+ function optionalBoolean(value, field) {
2894
+ if (!(field in value)) {
2895
+ return void 0;
2896
+ }
2897
+ return requireBoolean(value[field], field);
2898
+ }
2581
2899
  function requireIndex(value, field) {
2582
2900
  if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
2583
2901
  throw new Document2CommandError("invalid_command", `${field} must be a non-negative integer`);
@@ -2808,6 +3126,301 @@ function compactTextTokens2(tokens, emptyTokenId = document2Id("text")) {
2808
3126
  return compacted.length > 0 ? compacted : [{ id: emptyTokenId, kind: "text", text: "" }];
2809
3127
  }
2810
3128
 
3129
+ // src/document2/keys.ts
3130
+ var DOCUMENT2_KEY_PATTERN = /^[\p{L}\p{M}\p{Nd}:._-]+$/u;
3131
+ function normalizeDocument2Key(key) {
3132
+ return key.normalize("NFC").trim();
3133
+ }
3134
+ function isValidDocument2Key(key) {
3135
+ const normalized = normalizeDocument2Key(key);
3136
+ return normalized.length > 0 && DOCUMENT2_KEY_PATTERN.test(normalized);
3137
+ }
3138
+ function isDuplicateDocument2Key(key, namespace) {
3139
+ const normalized = normalizeDocument2Key(key);
3140
+ if (normalized.length === 0) {
3141
+ return false;
3142
+ }
3143
+ for (const reference of namespace.references ?? []) {
3144
+ if (namespace.excludeReferenceId && reference.id === namespace.excludeReferenceId) {
3145
+ continue;
3146
+ }
3147
+ if (normalizeDocument2Key(reference.key) === normalized) {
3148
+ return true;
3149
+ }
3150
+ }
3151
+ for (const label of namespace.labels ?? []) {
3152
+ if (namespace.excludeOwnerId && label.ownerId === namespace.excludeOwnerId) {
3153
+ continue;
3154
+ }
3155
+ if (normalizeDocument2Key(label.key) === normalized) {
3156
+ return true;
3157
+ }
3158
+ }
3159
+ return false;
3160
+ }
3161
+ function document2KeyError(key, namespace = {}) {
3162
+ const normalized = normalizeDocument2Key(key);
3163
+ if (normalized.length === 0) {
3164
+ return "empty";
3165
+ }
3166
+ if (!DOCUMENT2_KEY_PATTERN.test(normalized)) {
3167
+ return "invalid";
3168
+ }
3169
+ if (isDuplicateDocument2Key(normalized, namespace)) {
3170
+ return "duplicate";
3171
+ }
3172
+ return null;
3173
+ }
3174
+
3175
+ // src/document2/articleJsonCommands.ts
3176
+ var REFERENCE_TEXT_FIELDS = ["authors", "title", "year", "venue", "url"];
3177
+ function hasOwn(value, field) {
3178
+ return Object.prototype.hasOwnProperty.call(value, field);
3179
+ }
3180
+ function parseDatePatch(value) {
3181
+ if (!isObject3(value)) {
3182
+ throw new Document2CommandError("invalid_command", "date must be an object");
3183
+ }
3184
+ const patch = {};
3185
+ if (hasOwn(value, "day")) {
3186
+ if (typeof value.day !== "number" || !Number.isInteger(value.day) || value.day < 1 || value.day > 30) {
3187
+ throw new Document2CommandError("invalid_command", "date.day must be an integer from 1 to 30");
3188
+ }
3189
+ patch.day = value.day;
3190
+ }
3191
+ if (hasOwn(value, "month")) {
3192
+ if (typeof value.month !== "string" || !HIJRI_MONTH_IDS.includes(value.month)) {
3193
+ throw new Document2CommandError("invalid_command", "date.month must be a supported Hijri month");
3194
+ }
3195
+ patch.month = value.month;
3196
+ }
3197
+ if (hasOwn(value, "year")) {
3198
+ if (typeof value.year !== "number" || !Number.isInteger(value.year) || value.year < HIJRI_YEAR_MIN || value.year > HIJRI_YEAR_MAX) {
3199
+ throw new Document2CommandError(
3200
+ "invalid_command",
3201
+ `date.year must be an integer from ${String(HIJRI_YEAR_MIN)} to ${String(HIJRI_YEAR_MAX)}`
3202
+ );
3203
+ }
3204
+ patch.year = value.year;
3205
+ }
3206
+ if (Object.keys(patch).length === 0) {
3207
+ throw new Document2CommandError("invalid_command", "date requires at least one field");
3208
+ }
3209
+ return patch;
3210
+ }
3211
+ function parseReferenceSeparator(value) {
3212
+ if (!hasOwn(value, "field_separator")) {
3213
+ return void 0;
3214
+ }
3215
+ if (value.field_separator !== "," && value.field_separator !== "\u060C") {
3216
+ throw new Document2CommandError("invalid_command", "field_separator must be , or \u060C");
3217
+ }
3218
+ return value.field_separator;
3219
+ }
3220
+ function parseReferenceAnchor(value) {
3221
+ if (!isObject3(value)) {
3222
+ throw new Document2CommandError("invalid_anchor", "anchor must be an object");
3223
+ }
3224
+ const before = typeof value.before_reference_key === "string" ? normalizeDocument2Key(value.before_reference_key) : "";
3225
+ const after = typeof value.after_reference_key === "string" ? normalizeDocument2Key(value.after_reference_key) : "";
3226
+ const choices = Number(before.length > 0) + Number(after.length > 0) + Number(value.end === true);
3227
+ if (choices !== 1) {
3228
+ throw new Document2CommandError("invalid_anchor", "anchor requires exactly one reference position");
3229
+ }
3230
+ if (before) {
3231
+ return { before_reference_key: before };
3232
+ }
3233
+ if (after) {
3234
+ return { after_reference_key: after };
3235
+ }
3236
+ return { end: true };
3237
+ }
3238
+ function parseUpdateDocumentMeta(value) {
3239
+ const title = optionalString(value, "title");
3240
+ const authors = optionalString(value, "authors");
3241
+ const abstract = optionalString(value, "abstract");
3242
+ const date = hasOwn(value, "date") ? parseDatePatch(value.date) : void 0;
3243
+ if (title === void 0 && authors === void 0 && abstract === void 0 && date === void 0) {
3244
+ throw new Document2CommandError("invalid_command", "update_document_meta requires at least one field");
3245
+ }
3246
+ return {
3247
+ op: "update_document_meta",
3248
+ ...title !== void 0 ? { title } : {},
3249
+ ...authors !== void 0 ? { authors } : {},
3250
+ ...abstract !== void 0 ? { abstract } : {},
3251
+ ...date !== void 0 ? { date } : {}
3252
+ };
3253
+ }
3254
+ function referenceFields(value) {
3255
+ const fields = {};
3256
+ for (const field of REFERENCE_TEXT_FIELDS) {
3257
+ const parsed = optionalString(value, field);
3258
+ if (parsed !== void 0) {
3259
+ fields[field] = parsed;
3260
+ }
3261
+ }
3262
+ const separator = parseReferenceSeparator(value);
3263
+ if (separator !== void 0) {
3264
+ fields.field_separator = separator;
3265
+ }
3266
+ return fields;
3267
+ }
3268
+ function parseInsertReference(value) {
3269
+ const key = requireString2(value.key, "key", false);
3270
+ return {
3271
+ op: "insert_reference",
3272
+ key,
3273
+ ...referenceFields(value),
3274
+ anchor: parseReferenceAnchor(value.anchor)
3275
+ };
3276
+ }
3277
+ function parseUpdateReference(value) {
3278
+ const nextKey = optionalString(value, "key");
3279
+ const fields = referenceFields(value);
3280
+ if (nextKey === void 0 && Object.keys(fields).length === 0) {
3281
+ throw new Document2CommandError("invalid_command", "update_reference requires at least one field");
3282
+ }
3283
+ return {
3284
+ op: "update_reference",
3285
+ reference_key: requireString2(value.reference_key, "reference_key", false),
3286
+ ...nextKey !== void 0 ? { key: nextKey } : {},
3287
+ ...fields
3288
+ };
3289
+ }
3290
+ function parseArticleCommand(value) {
3291
+ if (value.op === "update_document_meta") {
3292
+ return parseUpdateDocumentMeta(value);
3293
+ }
3294
+ if (value.op === "insert_reference") {
3295
+ return parseInsertReference(value);
3296
+ }
3297
+ if (value.op === "update_reference") {
3298
+ return parseUpdateReference(value);
3299
+ }
3300
+ if (value.op === "remove_reference") {
3301
+ return {
3302
+ op: value.op,
3303
+ reference_key: requireString2(value.reference_key, "reference_key", false)
3304
+ };
3305
+ }
3306
+ if (value.op === "move_reference") {
3307
+ return {
3308
+ op: value.op,
3309
+ reference_key: requireString2(value.reference_key, "reference_key", false),
3310
+ anchor: parseReferenceAnchor(value.anchor)
3311
+ };
3312
+ }
3313
+ throw new Document2CommandError("invalid_command", "Unsupported article command");
3314
+ }
3315
+ function referenceIndexes(document2, key) {
3316
+ const normalized = normalizeDocument2Key(key);
3317
+ const indexes = [];
3318
+ document2.references.forEach((reference, index) => {
3319
+ if (normalizeDocument2Key(reference.key) === normalized) {
3320
+ indexes.push(index);
3321
+ }
3322
+ });
3323
+ return indexes;
3324
+ }
3325
+ function referenceTargetIndex(document2, key) {
3326
+ const indexes = referenceIndexes(document2, key);
3327
+ if (indexes.length === 0) {
3328
+ throw new Document2CommandError("reference_not_found", "Document reference was not found");
3329
+ }
3330
+ if (indexes.length > 1) {
3331
+ throw new Document2CommandError("duplicate_key", "Reference key is ambiguous");
3332
+ }
3333
+ return indexes[0];
3334
+ }
3335
+ function validateReferenceKey(document2, key, excludeReferenceId) {
3336
+ const normalized = normalizeDocument2Key(key);
3337
+ const error = document2KeyError(normalized, {
3338
+ references: document2.references,
3339
+ labels: collectDocument2Labels(document2),
3340
+ ...excludeReferenceId ? { excludeReferenceId } : {}
3341
+ });
3342
+ if (error === "duplicate") {
3343
+ throw new Document2CommandError("duplicate_key", "Reference key is already in use");
3344
+ }
3345
+ if (error !== null) {
3346
+ throw new Document2CommandError("invalid_key", "Reference key is invalid");
3347
+ }
3348
+ return normalized;
3349
+ }
3350
+ function referenceInsertionIndex(document2, anchor) {
3351
+ if ("end" in anchor) {
3352
+ return document2.references.length;
3353
+ }
3354
+ const key = "before_reference_key" in anchor ? anchor.before_reference_key : anchor.after_reference_key;
3355
+ const indexes = referenceIndexes(document2, key);
3356
+ if (indexes.length === 0) {
3357
+ throw new Document2CommandError("anchor_not_found", "Anchor reference was not found");
3358
+ }
3359
+ if (indexes.length > 1) {
3360
+ throw new Document2CommandError("duplicate_key", "Anchor reference key is ambiguous");
3361
+ }
3362
+ return "before_reference_key" in anchor ? indexes[0] : indexes[0] + 1;
3363
+ }
3364
+ function applyReferenceFields(reference, command) {
3365
+ for (const field of REFERENCE_TEXT_FIELDS) {
3366
+ const next = command[field];
3367
+ if (next !== void 0) {
3368
+ reference[field] = next;
3369
+ }
3370
+ }
3371
+ if (command.field_separator !== void 0) {
3372
+ reference.fieldSeparator = command.field_separator;
3373
+ }
3374
+ }
3375
+ function applyArticleCommand(document2, command) {
3376
+ if (command.op === "update_document_meta") {
3377
+ document2.meta = {
3378
+ title: command.title ?? document2.meta.title,
3379
+ authors: command.authors ?? document2.meta.authors,
3380
+ abstract: command.abstract ?? document2.meta.abstract,
3381
+ date: command.date ? normalizeDocument2HijriDate({ ...document2.meta.date, ...command.date }) : { ...document2.meta.date }
3382
+ };
3383
+ return;
3384
+ }
3385
+ if (command.op === "insert_reference") {
3386
+ const key = validateReferenceKey(document2, command.key);
3387
+ const reference2 = referenceFromJson({
3388
+ key,
3389
+ authors: command.authors,
3390
+ title: command.title,
3391
+ year: command.year,
3392
+ venue: command.venue,
3393
+ url: command.url,
3394
+ field_separator: command.field_separator
3395
+ });
3396
+ document2.references.splice(referenceInsertionIndex(document2, command.anchor), 0, reference2);
3397
+ return;
3398
+ }
3399
+ const targetIndex = referenceTargetIndex(document2, command.reference_key);
3400
+ const target = document2.references[targetIndex];
3401
+ if (command.op === "update_reference") {
3402
+ if (command.key !== void 0) {
3403
+ target.key = validateReferenceKey(document2, command.key, target.id);
3404
+ }
3405
+ applyReferenceFields(target, command);
3406
+ return;
3407
+ }
3408
+ if (command.op === "remove_reference") {
3409
+ document2.references.splice(targetIndex, 1);
3410
+ return;
3411
+ }
3412
+ const targetKey = normalizeDocument2Key(target.key);
3413
+ const anchorKey = "before_reference_key" in command.anchor ? command.anchor.before_reference_key : "after_reference_key" in command.anchor ? command.anchor.after_reference_key : null;
3414
+ if (anchorKey !== null && normalizeDocument2Key(anchorKey) === targetKey) {
3415
+ throw new Document2CommandError("invalid_anchor", "A reference cannot be moved relative to itself");
3416
+ }
3417
+ if (anchorKey !== null) {
3418
+ referenceInsertionIndex(document2, command.anchor);
3419
+ }
3420
+ const [reference] = document2.references.splice(targetIndex, 1);
3421
+ document2.references.splice(referenceInsertionIndex(document2, command.anchor), 0, reference);
3422
+ }
3423
+
2811
3424
  // src/document2/inlineJsonCommands.ts
2812
3425
  function parseInlineAnchor(value) {
2813
3426
  if (!isObject3(value)) {
@@ -3482,6 +4095,9 @@ function isListCommand(command) {
3482
4095
  function isTableCommand(command) {
3483
4096
  return command.op === "insert_table" || command.op === "replace_table_cell" || command.op === "insert_table_row" || command.op === "remove_table_row" || command.op === "move_table_row" || command.op === "insert_table_column" || command.op === "remove_table_column" || command.op === "move_table_column";
3484
4097
  }
4098
+ function isArticleCommand(command) {
4099
+ return command.op === "update_document_meta" || command.op === "insert_reference" || command.op === "update_reference" || command.op === "remove_reference" || command.op === "move_reference";
4100
+ }
3485
4101
  function parseTextBlockKind(value) {
3486
4102
  if (value === "section" || value === "subsection" || value === "subsubsection" || value === "paragraph") {
3487
4103
  return value;
@@ -3509,6 +4125,62 @@ function parseBasicCommand(value) {
3509
4125
  if (value.op === "remove_block") {
3510
4126
  return { op: value.op, block_id: requireString2(value.block_id, "block_id", false).trim() };
3511
4127
  }
4128
+ if (value.op === "move_block") {
4129
+ return {
4130
+ op: value.op,
4131
+ block_id: requireString2(value.block_id, "block_id", false).trim(),
4132
+ anchor: parseBlockAnchor(value.anchor)
4133
+ };
4134
+ }
4135
+ if (value.op === "insert_bibliography") {
4136
+ const metadata = parseMetadata(value.metadata);
4137
+ return {
4138
+ op: value.op,
4139
+ anchor: parseBlockAnchor(value.anchor),
4140
+ ...metadata ? { metadata } : {}
4141
+ };
4142
+ }
4143
+ if (value.op === "update_figure") {
4144
+ const hasAssetId = Object.prototype.hasOwnProperty.call(value, "asset_id");
4145
+ const hasValue = Object.prototype.hasOwnProperty.call(value, "value");
4146
+ if (!hasAssetId && !hasValue) {
4147
+ throw new Document2CommandError("invalid_command", "update_figure requires asset_id or value");
4148
+ }
4149
+ let assetId;
4150
+ if (hasAssetId) {
4151
+ if (value.asset_id === null) {
4152
+ assetId = null;
4153
+ } else {
4154
+ assetId = requireString2(value.asset_id, "asset_id", false).trim();
4155
+ }
4156
+ }
4157
+ const figureValue = hasValue ? requireString2(value.value, "value") : void 0;
4158
+ return {
4159
+ op: value.op,
4160
+ block_id: requireString2(value.block_id, "block_id", false).trim(),
4161
+ ...hasAssetId ? { asset_id: assetId } : {},
4162
+ ...hasValue ? { value: figureValue } : {}
4163
+ };
4164
+ }
4165
+ if (value.op === "update_float_meta") {
4166
+ const centered = optionalBoolean(value, "centered");
4167
+ const captionEnabled = optionalBoolean(value, "caption_enabled");
4168
+ const caption = optionalString(value, "caption");
4169
+ const labelEnabled = optionalBoolean(value, "label_enabled");
4170
+ const label = optionalString(value, "label");
4171
+ if (centered === void 0 && captionEnabled === void 0 && caption === void 0 && labelEnabled === void 0 && label === void 0) {
4172
+ throw new Document2CommandError("invalid_command", "update_float_meta requires at least one field");
4173
+ }
4174
+ return {
4175
+ op: value.op,
4176
+ block_id: requireString2(value.block_id, "block_id", false).trim(),
4177
+ ...centered !== void 0 ? { centered } : {},
4178
+ ...captionEnabled !== void 0 ? { caption_enabled: captionEnabled } : {},
4179
+ ...caption !== void 0 ? { caption } : {},
4180
+ ...labelEnabled !== void 0 ? { label_enabled: labelEnabled } : {},
4181
+ ...label !== void 0 ? { label } : {}
4182
+ };
4183
+ }
3512
4184
  if (value.op === "insert_figure") {
3513
4185
  const figureValue = optionalString(value, "value");
3514
4186
  const caption = optionalString(value, "caption");
@@ -3539,7 +4211,10 @@ function parseCommand2(value) {
3539
4211
  if (value.op === "insert_table" || value.op === "replace_table_cell" || value.op === "insert_table_row" || value.op === "remove_table_row" || value.op === "move_table_row" || value.op === "insert_table_column" || value.op === "remove_table_column" || value.op === "move_table_column") {
3540
4212
  return parseTableCommand(value);
3541
4213
  }
3542
- if (value.op === "insert_text_block" || value.op === "replace_text_block" || value.op === "remove_block" || value.op === "insert_figure") {
4214
+ if (value.op === "update_document_meta" || value.op === "insert_reference" || value.op === "update_reference" || value.op === "remove_reference" || value.op === "move_reference") {
4215
+ return parseArticleCommand(value);
4216
+ }
4217
+ 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") {
3543
4218
  return parseBasicCommand(value);
3544
4219
  }
3545
4220
  throw new Document2CommandError("invalid_command", "Unsupported document command");
@@ -3592,6 +4267,94 @@ function applyBasicCommand(document2, command) {
3592
4267
  document2.blocks.splice(index, 1);
3593
4268
  return;
3594
4269
  }
4270
+ if (command.op === "move_block") {
4271
+ const index = document2.blocks.findIndex((block3) => block3.id === command.block_id);
4272
+ if (index < 0) {
4273
+ throw new Document2CommandError("block_not_found", "Document block was not found");
4274
+ }
4275
+ const anchorId = "before_block_id" in command.anchor ? command.anchor.before_block_id : "after_block_id" in command.anchor ? command.anchor.after_block_id : null;
4276
+ if (anchorId === command.block_id) {
4277
+ throw new Document2CommandError("invalid_anchor", "A block cannot be moved relative to itself");
4278
+ }
4279
+ if (anchorId !== null) {
4280
+ blockInsertionIndex(document2, command.anchor);
4281
+ }
4282
+ const [block2] = document2.blocks.splice(index, 1);
4283
+ document2.blocks.splice(blockInsertionIndex(document2, command.anchor), 0, block2);
4284
+ return;
4285
+ }
4286
+ if (command.op === "insert_bibliography") {
4287
+ let hasBibliography2 = function(blocks) {
4288
+ return blocks.some((block3) => block3.kind === "bibliography" || block3.kind === "list" && block3.items.some((item) => hasBibliography2(item.blocks)));
4289
+ };
4290
+ var hasBibliography = hasBibliography2;
4291
+ if (hasBibliography2(document2.blocks)) {
4292
+ throw new Document2CommandError("bibliography_exists", "Document already contains a bibliography block");
4293
+ }
4294
+ const block2 = {
4295
+ id: newBlockId(document2),
4296
+ kind: "bibliography",
4297
+ command: "\\begin{thebibliography}",
4298
+ closing: "\\end{thebibliography}",
4299
+ ...command.metadata ? { metadata: { ...command.metadata } } : {}
4300
+ };
4301
+ document2.blocks.splice(blockInsertionIndex(document2, command.anchor), 0, block2);
4302
+ return;
4303
+ }
4304
+ if (command.op === "update_figure") {
4305
+ const block2 = findBlock(document2.blocks, command.block_id);
4306
+ if (!block2) {
4307
+ throw new Document2CommandError("block_not_found", "Document block was not found");
4308
+ }
4309
+ if (block2.kind !== "image") {
4310
+ throw new Document2CommandError("block_kind_mismatch", "Target block is not a figure");
4311
+ }
4312
+ if ("asset_id" in command) {
4313
+ if (command.asset_id === null) {
4314
+ delete block2.assetId;
4315
+ } else {
4316
+ block2.assetId = command.asset_id;
4317
+ }
4318
+ }
4319
+ if (command.value !== void 0) {
4320
+ block2.value = command.value;
4321
+ }
4322
+ return;
4323
+ }
4324
+ if (command.op === "update_float_meta") {
4325
+ const block2 = findBlock(document2.blocks, command.block_id);
4326
+ if (!block2) {
4327
+ throw new Document2CommandError("block_not_found", "Document block was not found");
4328
+ }
4329
+ if (block2.kind !== "image" && block2.kind !== "table") {
4330
+ throw new Document2CommandError("block_kind_mismatch", "Target block is not a figure or table");
4331
+ }
4332
+ let label = command.label;
4333
+ if (label !== void 0) {
4334
+ label = label.trim().length > 0 ? normalizeDocument2Key(label) : "";
4335
+ }
4336
+ if (label !== void 0 && label.length > 0) {
4337
+ const keyError = document2KeyError(label, {
4338
+ references: document2.references,
4339
+ labels: collectDocument2Labels(document2),
4340
+ excludeOwnerId: block2.id
4341
+ });
4342
+ if (keyError === "duplicate") {
4343
+ throw new Document2CommandError("duplicate_key", "Float label is already in use");
4344
+ }
4345
+ if (keyError !== null) {
4346
+ throw new Document2CommandError("invalid_key", "Float label is invalid");
4347
+ }
4348
+ }
4349
+ applyFloatMetaPatch(block2, {
4350
+ ...command.centered !== void 0 ? { centered: command.centered } : {},
4351
+ ...command.caption_enabled !== void 0 ? { captionEnabled: command.caption_enabled } : {},
4352
+ ...command.caption !== void 0 ? { caption: command.caption } : {},
4353
+ ...command.label_enabled !== void 0 ? { labelEnabled: command.label_enabled } : {},
4354
+ ...label !== void 0 ? { label } : {}
4355
+ });
4356
+ return;
4357
+ }
3595
4358
  const block = {
3596
4359
  id: newBlockId(document2),
3597
4360
  kind: "image",
@@ -3615,6 +4378,8 @@ function applyDocument2Command(json, commandInput) {
3615
4378
  applyListCommand(document2, command);
3616
4379
  } else if (isTableCommand(command)) {
3617
4380
  applyTableCommand(document2, command);
4381
+ } else if (isArticleCommand(command)) {
4382
+ applyArticleCommand(document2, command);
3618
4383
  } else {
3619
4384
  applyBasicCommand(document2, command);
3620
4385
  }
@@ -3695,6 +4460,809 @@ function document2Outline(json) {
3695
4460
  });
3696
4461
  }
3697
4462
 
4463
+ // src/document2/arabicPreamble.ts
4464
+ function fontOptions(digitsMapping, includeScript = true) {
4465
+ const parts = [];
4466
+ if (includeScript) {
4467
+ parts.push("Script=Arabic");
4468
+ }
4469
+ if (digitsMapping !== "digits") {
4470
+ parts.push(`Mapping=${digitsMapping}`);
4471
+ }
4472
+ if (parts.length === 0) {
4473
+ return "";
4474
+ }
4475
+ return `[${parts.join(",")}]`;
4476
+ }
4477
+ function arabicXeLatexPreamblePkg(twocolumn = false) {
4478
+ const classOptions = twocolumn ? "12pt,a4paper,notitlepage,twocolumn" : "12pt,a4paper,notitlepage";
4479
+ return `
4480
+ \\documentclass[${classOptions}]{article}
4481
+ ` + String.raw`\usepackage{amsmath,amsfonts,amssymb,mathrsfs,tikz,fancyhdr, mathtools}
4482
+ \usepackage{fontspec} % For loading OpenType fonts
4483
+ \usepackage{unicode-math} % For setting the math font
4484
+ \usepackage{polyglossia} % For Arabic support
4485
+ \usepackage{array}
4486
+ \usepackage{cancel}
4487
+ \usepackage{bidi}
4488
+ \usepackage{multirow}
4489
+ \usepackage{booktabs}
4490
+ \usepackage{graphicx} % For \reflectbox
4491
+ \usepackage{xcolor}
4492
+ \usepackage{tikz}
4493
+ \usepackage{tcolorbox} % For tcolorbox environment
4494
+ \usepackage{textcomp} % For \textrightarrow command
4495
+ \usepackage{url}
4496
+
4497
+
4498
+ % visit : https://www.symbolcopy.com/punctuation-symbol.html
4499
+ % for inversed punctuation
4500
+
4501
+ % save inverted comma for use - copy paste -> ،
4502
+ % save back tick for use - copy paste -> ` + "`";
4503
+ }
4504
+ function arabicXeLatexPreambleFont(digitsMapping = "arabicdigits") {
4505
+ const customFonts = NON_DEFAULT_CHARACTER_FONT_SPECS.filter((font) => font.latexFontCommand && font.latexFontFamily).map((font) => `\\newfontfamily${font.latexFontCommand}${fontOptions(digitsMapping)}{${font.latexFontFamily}}`).join("\n");
4506
+ const mathFontOptions = fontOptions(digitsMapping, false);
4507
+ return `
4508
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4509
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4510
+ % Persian digits: Mapping=farsidigits
4511
+ % Arabic-Indic digits: Mapping=arabicdigits
4512
+ % Western digits: omit Mapping entirely
4513
+ \\setdefaultlanguage[calendar=gregorian]{arabic} % from polyglossia
4514
+ \\setmainfont${fontOptions(digitsMapping)}{Amiri}
4515
+ ${customFonts}
4516
+ \\newfontfamily\\boldarabic${fontOptions(digitsMapping)}{Amiri Bold}
4517
+ \\newfontfamily\\italicarabic${fontOptions(digitsMapping)}{Amiri Italic}
4518
+
4519
+ % for polyglossia url I dont know, sugggested by cursor
4520
+ \\newfontfamily\\arabicfonttt${fontOptions(digitsMapping)}{Amiri}
4521
+ \\newfontfamily\\arabicfontsf${fontOptions(digitsMapping)}{Amiri}
4522
+
4523
+
4524
+ % Explicitly set math font to XITS Math
4525
+ \\setmathfont${mathFontOptions}{XITS Math} % Ensure XITS Math is correctly installed and available
4526
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4527
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4528
+ `;
4529
+ }
4530
+ function arabicXeLatexPreambleCmd() {
4531
+ const fontCommands = NON_DEFAULT_CHARACTER_FONT_SPECS.filter((font) => font.macro && font.latexFontCommand).map((font) => `\\newcommand{${font.macro}}[1]{\\text{${font.latexFontCommand}{#1}}}`).join("\n");
4532
+ return String.raw`
4533
+ % Run with XeLaTeX compiler
4534
+ ${fontCommands}
4535
+ \newcommand{\butexmirror}[1]{\reflectbox{\(#1\)}}
4536
+
4537
+ \newcommand{\arabN}{\text{\diwanioutlineshaded{ط}}}
4538
+ \newcommand{\arabZ}{\text{\diwanioutlineshaded{ص}}}
4539
+ \newcommand{\arabQ}{\text{\diwanioutlineshaded{ن}}}
4540
+ \newcommand{\arabR}{\text{\diwanioutlineshaded{ح}}}
4541
+ \newcommand{\arabC}{\text{\diwanioutlineshaded{ع}}}
4542
+ \newcommand{\arabH}{\text{\diwanioutlineshaded{ر}}}
4543
+
4544
+
4545
+ \newcommand{\lowerscript}[1]{\raisebox{-4pt}{\scriptsize #1}}
4546
+ \newcommand{\llowerscript}[1]{\raisebox{-8pt}{\scriptsize #1}}
4547
+ \newcommand{\lllowerscript}[2]{\raisebox{#2pt}{\scriptsize #1}}
4548
+
4549
+ \newcommand{\arabdsub}[3]{\prescript{}{#1}{\prescript{}{#2}{#3}}} % arabic double subscript
4550
+ \newcommand{\arabsub}[2]{\prescript{}{#1}{#2}} % arabic single subscript
4551
+
4552
+
4553
+
4554
+ \newcommand{\upperscript}[1]{\raisebox{8pt}{\scriptsize #1}}
4555
+ \newcommand{\uupperscript}[2]{\raisebox{#2pt}{\scriptsize #1}}
4556
+ \newcommand{\vertbar}{\rule[-1ex]{0.5pt}{2.5ex}}
4557
+ \newcommand{\horzbar}{\rule[.5ex]{2.5ex}{0.5pt}}
4558
+
4559
+
4560
+ \newcommand{\arsqrt}[2][]{\reflectbox{\(\sqrt[\reflectbox{\(#1\)}]{\reflectbox{\(#2\)}}\)}}
4561
+ \newcommand{\arabsqrt}[2][]{\arsqrt[#1]{#2}}
4562
+ \newcommand{\arabvec}[1]{\reflectbox{$\vec{\reflectbox{$#1$}}$}}
4563
+
4564
+ \newcommand{\arabexp}[1]{{}^{#1}\!\raisebox{-4.5pt}{\text{\diwani{ه}}}}
4565
+ \newcommand{\arablog}[2]{\left(\text{#2}\right)\!\prescript{}{\text{#1}}{\text{\diwani{لو}}}}
4566
+ \newcommand{\arabnlog}[1]{\left(\text{#1}\right)\!\prescript{}{\text{\diwani{ه}}}{\text{\diwani{لو}}}}
4567
+
4568
+ \newcommand{\arabcos}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{جتا}}}}
4569
+ \newcommand{\arabsin}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{جا}}}}
4570
+ \newcommand{\arabtan}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{ظا}}}}
4571
+ \newcommand{\arabcot}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{ظتا}}}}
4572
+ \newcommand{\arabsec}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قا}}}}
4573
+ \newcommand{\arabcsc}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قتا}}}}
4574
+
4575
+ \newcommand{\arabacos}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قجتا}}}}
4576
+ \newcommand{\arabasin}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قجا}}}}
4577
+ \newcommand{\arabatan}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قظا}}}}
4578
+ \newcommand{\arabacot}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قظتا}}}}
4579
+ \newcommand{\arabasec}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{ققا}}}}
4580
+ \newcommand{\arabacsc}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{ققتا}}}}
4581
+
4582
+
4583
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4584
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4585
+ % summation
4586
+ \newcommand{\arablim}[2]{\underset{#2 \leftarrow #1}{\text{نـــــها}}}
4587
+ \newcommand{\arabsum}[2]{\underset{#1}{\overset{#2}{\text{مجـــ}}}}
4588
+ \newcommand{\arabprod}[2]{\underset{#1}{\overset{#2}{\text{جـــذ}}}}
4589
+ \newcommand{\arabint}[2]{\prescript{#2}{#1\!\!\!}\int}
4590
+
4591
+
4592
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4593
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4594
+ % we define this command to make it ease for change of notation later
4595
+ \newcommand{\ad}[0]{\text{ء}} % "ad" for arabic differentiation or derivative (ء" لإشتقاق")
4596
+ \newcommand{\arpi}[0]{\!\text{\diwani{ط}}}
4597
+
4598
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4599
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4600
+ % differentials
4601
+
4602
+ \newcommand{\arabdiff}[2]{\frac{#1\ad}{#2\ad}} % arabic differential
4603
+ \newcommand{\arabddiff}[2]{\frac{#1{}^{2}\ad}{{}^{2}#2\ad}} % arabic second differential
4604
+
4605
+ \newcommand{\arabode}[2][-5pt]{\stackrel{\raisebox{#1}{$\cdot$}}{\text{#2}}}
4606
+ \newcommand{\arabodde}[2][-5pt]{\stackrel{\raisebox{#1}{$\vcenter{\hbox{$\cdot\!\cdot$}}$}}{\text{#2}}}
4607
+ \newcommand{\araboddde}[2][-5pt]{\stackrel{\raisebox{#1}{$\vcenter{\hbox{$\cdot\!\cdot\!\cdot$}}$}}{\text{#2}}}
4608
+ \newcommand{\arabpde}[1]{\prescript{}{#1\!\!}{\nabla}} % arabic partial differential equation (PDE)
4609
+
4610
+ \newcommand{\arabprime}[0]{\reflectbox{$\prime$}\!} % arabic prime notation
4611
+ \newcommand{\arabpprime}[0]{\reflectbox{$\prime$}\reflectbox{$\prime$}\!} % arabic prime notation
4612
+ \newcommand{\arabppprime}[0]{\reflectbox{$\prime$}\reflectbox{$\prime$}\reflectbox{$\prime$}\!} % arabic prime notation
4613
+
4614
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4615
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4616
+ % probability
4617
+ \newcommand{\ap}[0]{\!\text{\diwani{حـ}}} % arabic Probability - used a lot so short form
4618
+ \newcommand{\arabExpct}[0]{\text{\diwani{توقـ}}} % arabic Expectation
4619
+ \newcommand{\arabVar}[0]{\!\text{\diwani{با}}} % arabic Variance
4620
+ \newcommand{\arabCov}[0]{\!\text{\diwani{ت}}} % arabic Covariance
4621
+
4622
+
4623
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4624
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4625
+ % custom commands specific to lesson
4626
+ \newcommand{\lagrange}[2]{\left(#2\right)\!\prescript{}{#1}{\text{\diwani{لا}}}}
4627
+ \newcommand{\xii}[0]{\left(\prescript{}{\text{يـ}}{\text{س}}\right)\!}
4628
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4629
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4630
+
4631
+
4632
+ \newcommand{\arexp}[0]{\!\raisebox{-4.5pt}{\text{\diwani{ه}}}}
4633
+ \newcommand{\arlog}[0]{\!\!\text{\diwani{لو}}}
4634
+ \newcommand{\arln}[0]{\!\!\prescript{}{\text{\diwani{ه}}}{\text{\diwani{لو}}}}
4635
+ \newcommand{\ardet}[0]{\!\!\text{\diwani{محدد}}}
4636
+
4637
+ \newcommand{\arsum}[0]{\text{مجـــ}}
4638
+ \newcommand{\arprod}[0]{\text{جـــذ}}
4639
+
4640
+ \newcommand{\arlim}[0]{\text{نـــــها}}
4641
+ \newcommand{\armax}[0]{\text{أكبر}}
4642
+ \newcommand{\armin}[0]{\text{أصغر}}
4643
+ \newcommand{\arsup}[0]{\text{أعلى}}
4644
+ \newcommand{\arinf}[0]{\text{أدنى}}
4645
+
4646
+ \newcommand{\arsin}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{جا}}}}
4647
+ \newcommand{\arcos}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{جتا}}}}
4648
+ \newcommand{\artan}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ظا}}}}
4649
+ \newcommand{\arcot}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ظتا}}}}
4650
+ \newcommand{\arsec}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قا}}}}
4651
+ \newcommand{\arcsc}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قتا}}}}
4652
+
4653
+ \newcommand{\arasin}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قجا}}}}
4654
+ \newcommand{\aracos}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قجتا}}}}
4655
+ \newcommand{\aratan}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قظا}}}}
4656
+ \newcommand{\aracot}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قظتا}}}}
4657
+ \newcommand{\arasec}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ققا}}}}
4658
+ \newcommand{\aracsc}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ققتا}}}}
4659
+
4660
+ \newcommand{\arsinh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{جزا}}}}
4661
+ \newcommand{\arcosh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{جتزا}}}}
4662
+ \newcommand{\artanh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ظزا}}}}
4663
+ \newcommand{\arcoth}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ظتزا}}}}
4664
+ \newcommand{\arsech}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قزا}}}}
4665
+ \newcommand{\arcsch}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قتزا}}}}
4666
+
4667
+ \newcommand{\arasinh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قجزا}}}}
4668
+ \newcommand{\aracosh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قجتزا}}}}
4669
+ \newcommand{\aratanh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قظزا}}}}
4670
+ \newcommand{\aracoth}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قظتزا}}}}
4671
+ \newcommand{\arasech}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ققزا}}}}
4672
+ \newcommand{\aracsch}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ققتزا}}}}
4673
+
4674
+ \newcommand{\unit}[1]{\text{#1}}
4675
+ \newcommand{\idx}[1]{#1}
4676
+ \newcommand{\arbinom}[2]{\left(\begin{array}{c} #1 \\ #2 \end{array} \right)}
4677
+ `;
4678
+ }
4679
+ function getArabicXeLatexPreamble(digitsMappingOrOptions = "arabicdigits") {
4680
+ const options = typeof digitsMappingOrOptions === "string" ? { digitsMapping: digitsMappingOrOptions } : digitsMappingOrOptions;
4681
+ const digitsMapping = options.digitsMapping ?? "arabicdigits";
4682
+ const twocolumn = options.twocolumn === true;
4683
+ return arabicXeLatexPreamblePkg(twocolumn) + arabicXeLatexPreambleFont(digitsMapping) + arabicXeLatexPreambleCmd();
4684
+ }
4685
+
4686
+ // src/document2/exportLatex.ts
4687
+ function digitsMappingFromDigitForm(digitForm) {
4688
+ if (digitForm === "western") {
4689
+ return "digits";
4690
+ }
4691
+ if (digitForm === "persianIndic") {
4692
+ return "farsidigits";
4693
+ }
4694
+ return "arabicdigits";
4695
+ }
4696
+ function mathBodyLatex(token) {
4697
+ if (token.sourceOwner === "editor") {
4698
+ return stripDisplayMathDelimiters(mirrorBuTeXOperatorsInTex(token.source, { target: "compile" }));
4699
+ }
4700
+ if (!token.math || token.sourceOwner === "raw") {
4701
+ return stripDisplayMathDelimiters(token.source);
4702
+ }
4703
+ const rendered = renderMathNodeLatex(token.math);
4704
+ return stripDisplayMathDelimiters(rendered);
4705
+ }
4706
+ function styledTextLatex(text, style) {
4707
+ let output = text;
4708
+ if (style?.bold) {
4709
+ output = `\\textbf{${output}}`;
4710
+ }
4711
+ if (style?.italic) {
4712
+ output = `\\textit{${output}}`;
4713
+ }
4714
+ if (style?.underline) {
4715
+ output = `\\underline{${output}}`;
4716
+ }
4717
+ return output;
4718
+ }
4719
+ function semanticRefPrefix(kind) {
4720
+ if (kind === "fig") {
4721
+ return "\u0627\u0644\u0634\u0643\u0644";
4722
+ }
4723
+ if (kind === "tab") {
4724
+ return "\u0627\u0644\u062C\u062F\u0648\u0644";
4725
+ }
4726
+ return "\u0627\u0644\u0645\u0639\u0627\u062F\u0644\u0629";
4727
+ }
4728
+ function semanticRefNames(kind) {
4729
+ if (kind === "fig") {
4730
+ return ["\u0627\u0644\u0634\u0643\u0644", "\u0634\u0643\u0644", "Figure", "figure"];
4731
+ }
4732
+ if (kind === "tab") {
4733
+ return ["\u0627\u0644\u062C\u062F\u0648\u0644", "\u062C\u062F\u0648\u0644", "Table", "table"];
4734
+ }
4735
+ return ["\u0627\u0644\u0645\u0639\u0627\u062F\u0644\u0629", "\u0645\u0639\u0627\u062F\u0644\u0629", "Equation", "equation"];
4736
+ }
4737
+ function previousTextAlreadyNamesKind(previousToken, kind) {
4738
+ if (previousToken?.kind !== "text") {
4739
+ return false;
4740
+ }
4741
+ const text = previousToken.text.trimEnd();
4742
+ return semanticRefNames(kind).some((name) => text.endsWith(name));
4743
+ }
4744
+ function refTokenLatexForDocument(token, labelKinds, previousToken) {
4745
+ const reference = refTokenLatex(token.keys, token.refCommand);
4746
+ if (!labelKinds || token.keys.length !== 1) {
4747
+ return reference;
4748
+ }
4749
+ const kind = labelKinds.get(token.keys[0]);
4750
+ if (!kind || previousTextAlreadyNamesKind(previousToken, kind)) {
4751
+ return reference;
4752
+ }
4753
+ return `${semanticRefPrefix(kind)}~${reference}`;
4754
+ }
4755
+ function tokenLatex(token, labelKinds, previousToken) {
4756
+ if (token.kind === "text") {
4757
+ return styledTextLatex(token.text, token.style);
4758
+ }
4759
+ if (token.kind === "cite") {
4760
+ return citeTokenLatex(token.keys);
4761
+ }
4762
+ if (token.kind === "ref") {
4763
+ return refTokenLatexForDocument(token, labelKinds, previousToken);
4764
+ }
4765
+ if (token.display && token.labelEnabled && token.label && token.label.trim().length > 0) {
4766
+ const body = mathBodyLatex(token);
4767
+ return `\\begin{equation}
4768
+ ${body}
4769
+ \\label{${token.label.trim()}}
4770
+ \\end{equation}`;
4771
+ }
4772
+ if (token.sourceOwner === "editor") {
4773
+ return mirrorBuTeXOperatorsInTex(token.source, { target: "compile" });
4774
+ }
4775
+ if (!token.math || token.sourceOwner === "raw") {
4776
+ return token.source;
4777
+ }
4778
+ return renderMathNodeLatex(token.math);
4779
+ }
4780
+ function inlineFieldLatexWithLabelKinds(field, labelKinds) {
4781
+ return field.tokens.map((token, index) => tokenLatex(token, labelKinds, field.tokens[index - 1])).join("");
4782
+ }
4783
+ function textBlockLatex(block, labelKinds) {
4784
+ const content = inlineFieldLatexWithLabelKinds(block.field, labelKinds);
4785
+ const body = block.command === "\\paragraph" ? `\\par
4786
+ ${content}` : `${block.command}{${content}}`;
4787
+ if (block.command === "\\paragraph" && block.centered) {
4788
+ return `\\begin{center}
4789
+ ${body}
4790
+ \\end{center}`;
4791
+ }
4792
+ return body;
4793
+ }
4794
+ function indent(value) {
4795
+ return value.split("\n").map((line) => ` ${line}`).join("\n");
4796
+ }
4797
+ function listBlockLatex(block, references, labelKinds, fixedFloats) {
4798
+ const items = block.items.map((item) => {
4799
+ const nested = item.blocks.map((child) => "\n" + indent(blockLatex(child, references, labelKinds, fixedFloats))).join("");
4800
+ return ` \\item ${inlineFieldLatexWithLabelKinds(item.field, labelKinds)}${nested}`;
4801
+ }).join("\n");
4802
+ return `${block.command}
4803
+ ${items}
4804
+ ${block.closing}`;
4805
+ }
4806
+ function defaultGridColumnSpec(block) {
4807
+ const compact = block.columns.replace(/\s+/g, "");
4808
+ const columnCount = block.rows[0]?.length ?? 0;
4809
+ if (columnCount === 0 || compact.length !== columnCount || !/^[lcr]+$/.test(compact)) {
4810
+ return null;
4811
+ }
4812
+ return `|${compact.split("").join("|")}|`;
4813
+ }
4814
+ function tabularInnerLatex(block, labelKinds) {
4815
+ const rows = block.rows.map(
4816
+ (row) => ` ${row.map((cell) => inlineFieldLatexWithLabelKinds(cell, labelKinds)).join(" & ")}`
4817
+ );
4818
+ const gridColumns = defaultGridColumnSpec(block);
4819
+ if (gridColumns) {
4820
+ const griddedRows = rows.map((row) => `${row} \\\\ \\hline`).join("\n");
4821
+ return `${block.command}{${gridColumns}}
4822
+ \\hline
4823
+ ${griddedRows}
4824
+ ${block.closing}`;
4825
+ }
4826
+ return `${block.command}{${block.columns}}
4827
+ ${rows.join(" \\\\\n")}
4828
+ ${block.closing}`;
4829
+ }
4830
+ function floatCaptionLabelLines(block, counter) {
4831
+ const lines = [];
4832
+ const hasCaption = block.captionEnabled && block.caption.trim().length > 0;
4833
+ if (hasCaption) {
4834
+ lines.push(` \\caption{${block.caption.trim()}}`);
4835
+ }
4836
+ if (block.labelEnabled && block.label.trim().length > 0) {
4837
+ if (!hasCaption) {
4838
+ lines.push(` \\refstepcounter{${counter}}`);
4839
+ }
4840
+ lines.push(` \\label{${block.label.trim()}}`);
4841
+ }
4842
+ return lines;
4843
+ }
4844
+ function tableBlockLatex(block, labelKinds, fixedFloats) {
4845
+ const placement = fixedFloats ? "H" : "htbp";
4846
+ const lines = [`\\begin{table}[${placement}]`];
4847
+ if (block.centered) {
4848
+ lines.push(" \\centering");
4849
+ }
4850
+ lines.push(...floatCaptionLabelLines(block, "table"));
4851
+ lines.push(indent(tabularInnerLatex(block, labelKinds)));
4852
+ lines.push("\\end{table}");
4853
+ return lines.join("\n");
4854
+ }
4855
+ function remapImageWidthForColumns(value) {
4856
+ return value.replace(/\\textwidth\b/g, "\\columnwidth");
4857
+ }
4858
+ function imageOptionsLatex(block, constrainToColumn) {
4859
+ const entries = Object.entries(block.options).map(([key, value]) => {
4860
+ if (constrainToColumn && key === "width") {
4861
+ return [key, remapImageWidthForColumns(value)];
4862
+ }
4863
+ return [key, value];
4864
+ });
4865
+ if (entries.length === 0) {
4866
+ return "";
4867
+ }
4868
+ return `[${entries.map(([key, value]) => `${key}=${value}`).join(",")}]`;
4869
+ }
4870
+ function imageBlockLatex(block, fixedFloats) {
4871
+ const placement = fixedFloats ? "H" : "htbp";
4872
+ const lines = [`\\begin{figure}[${placement}]`];
4873
+ if (block.centered) {
4874
+ lines.push(" \\centering");
4875
+ }
4876
+ lines.push(` ${block.command}${imageOptionsLatex(block, true)}{${block.value}}`);
4877
+ lines.push(...floatCaptionLabelLines(block, "figure"));
4878
+ lines.push("\\end{figure}");
4879
+ return lines.join("\n");
4880
+ }
4881
+ function blockLatex(block, references, labelKinds, fixedFloats) {
4882
+ if (block.kind === "textBlock") {
4883
+ return textBlockLatex(block, labelKinds);
4884
+ }
4885
+ if (block.kind === "list") {
4886
+ return listBlockLatex(block, references, labelKinds, fixedFloats);
4887
+ }
4888
+ if (block.kind === "table") {
4889
+ return tableBlockLatex(block, labelKinds, fixedFloats);
4890
+ }
4891
+ if (block.kind === "image") {
4892
+ return imageBlockLatex(block, fixedFloats);
4893
+ }
4894
+ if (block.kind === "bibliography") {
4895
+ const width = String(Math.max(references.length, 9));
4896
+ const items = references.map((reference) => ` ${bibliographyEntryLatex(reference)}`).join("\n");
4897
+ return `${block.command}{${width}}
4898
+ ${items}
4899
+ ${block.closing}`;
4900
+ }
4901
+ return block.value;
4902
+ }
4903
+ function authorLatex(authors) {
4904
+ return authors.split(/\n+/).map((line) => line.trim()).filter((line) => line.length > 0).join(" \\\\ ");
4905
+ }
4906
+ function articleMaketitlePreamble(meta, twocolumn = false) {
4907
+ if (!document2HasMaketitle(meta)) {
4908
+ return "";
4909
+ }
4910
+ const parts = [butexBasmalaTitlingPreamble({ twocolumn })];
4911
+ if (meta.title.trim().length > 0) {
4912
+ parts.push(`\\title{${meta.title.trim()}}`);
4913
+ }
4914
+ if (meta.authors.trim().length > 0) {
4915
+ parts.push(`\\author{${authorLatex(meta.authors)}}`);
4916
+ }
4917
+ parts.push(`\\date{${formatHijriDate(meta.date, { locale: "ar", digitForm: "western" })}}`);
4918
+ return parts.join("\n");
4919
+ }
4920
+ function articleFrontMatterLatex(meta) {
4921
+ const parts = [];
4922
+ if (document2HasMaketitle(meta)) {
4923
+ parts.push("\\maketitle");
4924
+ } else {
4925
+ parts.push(butexBasmalaDisplayLatex());
4926
+ }
4927
+ if (document2HasAbstract(meta)) {
4928
+ parts.push(`\\begin{abstract}
4929
+ ${meta.abstract.trim()}
4930
+ \\end{abstract}`);
4931
+ }
4932
+ return parts;
4933
+ }
4934
+ function documentLabelKindMap(document2) {
4935
+ const map = /* @__PURE__ */ new Map();
4936
+ for (const entry of collectDocument2Labels(document2)) {
4937
+ if (!map.has(entry.key)) {
4938
+ map.set(entry.key, entry.kind);
4939
+ }
4940
+ }
4941
+ return map;
4942
+ }
4943
+ function closingHamdalaLatex() {
4944
+ return `\\begin{center}
4945
+ \\maghribi{${BUTEX_CLOSING_HAMDALA}}
4946
+ \\end{center}`;
4947
+ }
4948
+ function document2Latex(document2, options = {}) {
4949
+ const meta = document2.meta ?? emptyDocument2Meta();
4950
+ const twocolumn = options.twocolumn === true;
4951
+ const front = articleFrontMatterLatex(meta);
4952
+ const labelKinds = documentLabelKindMap(document2);
4953
+ const bodyBlocks = document2.blocks.map(
4954
+ (block) => blockLatex(block, document2.references, labelKinds, twocolumn)
4955
+ );
4956
+ const closing = closingHamdalaLatex();
4957
+ const body = [...front, ...bodyBlocks, closing].filter((part) => part.length > 0).join("\n\n");
4958
+ const wrapDocument = options.wrapDocument !== false;
4959
+ if (!wrapDocument) {
4960
+ const metaPreamble = articleMaketitlePreamble(meta, twocolumn);
4961
+ return metaPreamble.length > 0 ? `${metaPreamble}
4962
+
4963
+ ${body}` : body;
4964
+ }
4965
+ const floatPackage = twocolumn ? "\n\\usepackage{float}\n" : "\n";
4966
+ const preamble = getArabicXeLatexPreamble({
4967
+ digitsMapping: options.digitsMapping ?? digitsMappingFromDigitForm(options.digitForm),
4968
+ twocolumn
4969
+ }) + floatPackage + articleMaketitlePreamble(meta, twocolumn);
4970
+ return `${preamble}
4971
+ \\begin{document}
4972
+
4973
+ ${body}
4974
+
4975
+ \\end{document}
4976
+ `;
4977
+ }
4978
+
4979
+ // src/document2/validation.ts
4980
+ var XELATEX_UNSUPPORTED_EMOJI_PATTERN = /[\p{Emoji_Presentation}\p{Emoji_Modifier}\p{Regional_Indicator}\uFE0F\u20E3]/u;
4981
+ function hasXeLatexUnsupportedEmoji(value) {
4982
+ return XELATEX_UNSUPPORTED_EMOJI_PATTERN.test(value);
4983
+ }
4984
+ function addIssue(context, code, path, blockId, tokenId) {
4985
+ context.issues.push({
4986
+ code,
4987
+ path,
4988
+ ...blockId ? { blockId } : {},
4989
+ ...tokenId ? { tokenId } : {}
4990
+ });
4991
+ }
4992
+ function validateTextValue(context, value, path, blockId, tokenId) {
4993
+ if (hasXeLatexUnsupportedEmoji(value)) {
4994
+ addIssue(context, "unsupported_emoji", path, blockId, tokenId);
4995
+ }
4996
+ }
4997
+ function registerKey(context, key, path, kind, blockId, tokenId) {
4998
+ const normalized = normalizeDocument2Key(key);
4999
+ if (normalized.length === 0) {
5000
+ addIssue(context, "key_empty", path, blockId, tokenId);
5001
+ return;
5002
+ }
5003
+ if (!isValidDocument2Key(normalized)) {
5004
+ addIssue(context, "key_invalid", path, blockId, tokenId);
5005
+ return;
5006
+ }
5007
+ context.keyOwners.push({
5008
+ key: normalized,
5009
+ path,
5010
+ kind,
5011
+ ...blockId ? { blockId } : {},
5012
+ ...tokenId ? { tokenId } : {}
5013
+ });
5014
+ if (kind !== "reference" && !context.labelKinds.has(normalized)) {
5015
+ context.labelKinds.set(normalized, kind);
5016
+ }
5017
+ }
5018
+ function validateToken(context, token, path, blockId) {
5019
+ if (token.kind === "text") {
5020
+ validateTextValue(context, token.text, `${path}.text`, blockId, token.id);
5021
+ return;
5022
+ }
5023
+ if (token.kind === "cite") {
5024
+ if (token.keys.length === 0) {
5025
+ addIssue(context, "empty_citation", `${path}.keys`, blockId, token.id);
5026
+ }
5027
+ context.pendingCitations.push({ token, path, blockId });
5028
+ return;
5029
+ }
5030
+ if (token.kind === "ref") {
5031
+ if (token.keys.length === 0) {
5032
+ addIssue(context, "empty_reference", `${path}.keys`, blockId, token.id);
5033
+ }
5034
+ context.pendingReferences.push({ token, path, blockId });
5035
+ return;
5036
+ }
5037
+ validateTextValue(context, token.source, `${path}.source`, blockId, token.id);
5038
+ if (!token.labelEnabled) {
5039
+ return;
5040
+ }
5041
+ if (!token.display) {
5042
+ addIssue(context, "invalid_equation_label", `${path}.label`, blockId, token.id);
5043
+ return;
5044
+ }
5045
+ registerKey(context, token.label ?? "", `${path}.label`, "eq", blockId, token.id);
5046
+ }
5047
+ function validateInlineField(context, field, path, blockId) {
5048
+ field.tokens.forEach((token, index) => {
5049
+ validateToken(context, token, `${path}.tokens[${String(index)}]`, blockId);
5050
+ });
5051
+ }
5052
+ function validateBlock(context, block, path) {
5053
+ if (block.kind === "textBlock") {
5054
+ validateInlineField(context, block.field, `${path}.field`, block.id);
5055
+ return;
5056
+ }
5057
+ if (block.kind === "list") {
5058
+ block.items.forEach((item, itemIndex) => {
5059
+ const itemPath = `${path}.items[${String(itemIndex)}]`;
5060
+ validateInlineField(context, item.field, `${itemPath}.field`, block.id);
5061
+ item.blocks.forEach((child, childIndex) => {
5062
+ validateBlock(context, child, `${itemPath}.blocks[${String(childIndex)}]`);
5063
+ });
5064
+ });
5065
+ return;
5066
+ }
5067
+ if (block.kind === "table") {
5068
+ if (block.columns.trim().length === 0 || block.rows.length === 0) {
5069
+ addIssue(context, "invalid_table", path, block.id);
5070
+ }
5071
+ const expectedColumns = block.rows[0]?.length ?? 0;
5072
+ if (expectedColumns === 0 || block.rows.some((row) => row.length !== expectedColumns)) {
5073
+ addIssue(context, "invalid_table", `${path}.rows`, block.id);
5074
+ }
5075
+ block.rows.forEach((row, rowIndex) => {
5076
+ row.forEach((cell, columnIndex) => {
5077
+ validateInlineField(
5078
+ context,
5079
+ cell,
5080
+ `${path}.rows[${String(rowIndex)}][${String(columnIndex)}]`,
5081
+ block.id
5082
+ );
5083
+ });
5084
+ });
5085
+ validateTextValue(context, block.caption, `${path}.caption`, block.id);
5086
+ if (block.labelEnabled) {
5087
+ registerKey(context, block.label, `${path}.label`, "tab", block.id);
5088
+ }
5089
+ return;
5090
+ }
5091
+ if (block.kind === "image") {
5092
+ const hasAssetId = typeof block.assetId === "string" && block.assetId.trim().length > 0;
5093
+ const hasValue = block.value.trim().length > 0;
5094
+ if (!hasAssetId && !hasValue) {
5095
+ addIssue(context, "empty_image", path, block.id);
5096
+ }
5097
+ validateTextValue(context, block.value, `${path}.value`, block.id);
5098
+ validateTextValue(context, block.caption, `${path}.caption`, block.id);
5099
+ if (block.labelEnabled) {
5100
+ registerKey(context, block.label, `${path}.label`, "fig", block.id);
5101
+ }
5102
+ return;
5103
+ }
5104
+ if (block.kind === "raw") {
5105
+ validateTextValue(context, block.value, `${path}.value`, block.id);
5106
+ }
5107
+ }
5108
+ function validateDuplicateKeys(context) {
5109
+ const grouped = /* @__PURE__ */ new Map();
5110
+ for (const owner of context.keyOwners) {
5111
+ const group = grouped.get(owner.key) ?? [];
5112
+ group.push(owner);
5113
+ grouped.set(owner.key, group);
5114
+ }
5115
+ for (const owners of grouped.values()) {
5116
+ if (owners.length < 2) {
5117
+ continue;
5118
+ }
5119
+ for (const owner of owners) {
5120
+ addIssue(context, "key_duplicate", owner.path, owner.blockId, owner.tokenId);
5121
+ }
5122
+ }
5123
+ }
5124
+ function validatePendingReferences(context) {
5125
+ for (const pending of context.pendingCitations) {
5126
+ if (pending.token.keys.some((key) => !isValidDocument2Key(normalizeDocument2Key(key)))) {
5127
+ addIssue(
5128
+ context,
5129
+ "missing_citation",
5130
+ `${pending.path}.keys`,
5131
+ pending.blockId,
5132
+ pending.token.id
5133
+ );
5134
+ }
5135
+ }
5136
+ for (const pending of context.pendingReferences) {
5137
+ for (const key of pending.token.keys) {
5138
+ const normalized = normalizeDocument2Key(key);
5139
+ if (!isValidDocument2Key(normalized)) {
5140
+ addIssue(
5141
+ context,
5142
+ "missing_reference",
5143
+ `${pending.path}.keys`,
5144
+ pending.blockId,
5145
+ pending.token.id
5146
+ );
5147
+ break;
5148
+ }
5149
+ const kind = context.labelKinds.get(normalized);
5150
+ if (kind && pending.token.refCommand === "eqref" !== (kind === "eq")) {
5151
+ addIssue(
5152
+ context,
5153
+ "reference_kind_mismatch",
5154
+ `${pending.path}.keys`,
5155
+ pending.blockId,
5156
+ pending.token.id
5157
+ );
5158
+ break;
5159
+ }
5160
+ }
5161
+ }
5162
+ }
5163
+ function isRecord(value) {
5164
+ return typeof value === "object" && value !== null;
5165
+ }
5166
+ function hasRuntimeDocumentShape(document2) {
5167
+ const value = document2;
5168
+ return isRecord(value) && value.nodeType === "DocumentObject";
5169
+ }
5170
+ function hasWireDocumentShape(document2) {
5171
+ const value = document2;
5172
+ if (!isRecord(value) || value.node_type !== "DocumentObject" || !Array.isArray(value.blocks)) {
5173
+ return false;
5174
+ }
5175
+ if (value.meta !== void 0 && !isRecord(value.meta)) {
5176
+ return false;
5177
+ }
5178
+ if (value.references !== void 0) {
5179
+ if (!Array.isArray(value.references)) {
5180
+ return false;
5181
+ }
5182
+ for (const reference of value.references) {
5183
+ if (!isRecord(reference) || typeof reference.key !== "string" || reference.key.trim().length === 0) {
5184
+ return false;
5185
+ }
5186
+ }
5187
+ }
5188
+ return true;
5189
+ }
5190
+ function resolveDocument(document2) {
5191
+ if (hasRuntimeDocumentShape(document2)) {
5192
+ try {
5193
+ toDocumentJson2(document2);
5194
+ return document2;
5195
+ } catch {
5196
+ return null;
5197
+ }
5198
+ }
5199
+ if (!hasWireDocumentShape(document2)) {
5200
+ return null;
5201
+ }
5202
+ try {
5203
+ return fromDocumentJson2(document2);
5204
+ } catch {
5205
+ return null;
5206
+ }
5207
+ }
5208
+ function validateDocument2(document2) {
5209
+ const resolved = resolveDocument(document2);
5210
+ if (!resolved) {
5211
+ return {
5212
+ valid: false,
5213
+ issues: [{ code: "malformed_document", path: "$" }]
5214
+ };
5215
+ }
5216
+ const context = {
5217
+ issues: [],
5218
+ keyOwners: [],
5219
+ labelKinds: /* @__PURE__ */ new Map(),
5220
+ pendingCitations: [],
5221
+ pendingReferences: []
5222
+ };
5223
+ validateTextValue(context, resolved.meta.title, "$.meta.title");
5224
+ validateTextValue(context, resolved.meta.authors, "$.meta.authors");
5225
+ validateTextValue(context, resolved.meta.abstract, "$.meta.abstract");
5226
+ resolved.references.forEach((reference, index) => {
5227
+ const path = `$.references[${String(index)}]`;
5228
+ registerKey(context, reference.key, `${path}.key`, "reference");
5229
+ validateTextValue(context, reference.authors, `${path}.authors`);
5230
+ validateTextValue(context, reference.title, `${path}.title`);
5231
+ validateTextValue(context, reference.year, `${path}.year`);
5232
+ validateTextValue(context, reference.url, `${path}.url`);
5233
+ validateTextValue(context, reference.venue, `${path}.venue`);
5234
+ });
5235
+ resolved.blocks.forEach((block, index) => {
5236
+ validateBlock(context, block, `$.blocks[${String(index)}]`);
5237
+ });
5238
+ for (const diagnostic of resolved.diagnostics) {
5239
+ addIssue(context, "parser_diagnostic", diagnostic.path);
5240
+ }
5241
+ validateDuplicateKeys(context);
5242
+ validatePendingReferences(context);
5243
+ return {
5244
+ valid: context.issues.length === 0,
5245
+ issues: context.issues
5246
+ };
5247
+ }
5248
+ var Document2ValidationError = class extends Error {
5249
+ issues;
5250
+ constructor(issues) {
5251
+ super("Document2 validation failed; invalid drafts cannot be exported to LaTeX.");
5252
+ this.name = "Document2ValidationError";
5253
+ this.issues = issues;
5254
+ }
5255
+ };
5256
+
5257
+ // src/document2/validatedLatex.ts
5258
+ function document2Latex2(document2, options = {}) {
5259
+ const validation = validateDocument2(document2);
5260
+ if (!validation.valid) {
5261
+ throw new Document2ValidationError(validation.issues);
5262
+ }
5263
+ return document2Latex(document2, options);
5264
+ }
5265
+
3698
5266
  // src/document2-cli/protocol.ts
3699
5267
  var Document2WorkerProtocolError = class extends Error {
3700
5268
  code;
@@ -3714,7 +5282,7 @@ function parseDocument2WorkerRequest(value) {
3714
5282
  if (!("document" in value)) {
3715
5283
  throw new Document2WorkerProtocolError("invalid_request", "Worker request requires a document");
3716
5284
  }
3717
- if (value.action === "normalize" || value.action === "outline") {
5285
+ if (value.action === "normalize" || value.action === "outline" || value.action === "export") {
3718
5286
  return { action: value.action, document: value.document };
3719
5287
  }
3720
5288
  if (value.action === "apply_command") {
@@ -3725,7 +5293,28 @@ function parseDocument2WorkerRequest(value) {
3725
5293
  }
3726
5294
  throw new Document2WorkerProtocolError("invalid_request", `Unsupported worker action: ${value.action}`);
3727
5295
  }
5296
+ function boundedValidationIssues(issues) {
5297
+ return issues.slice(0, 100).map((issue) => ({
5298
+ code: issue.code,
5299
+ path: issue.path.slice(0, 500),
5300
+ ...issue.blockId ? { blockId: issue.blockId.slice(0, 500) } : {},
5301
+ ...issue.tokenId ? { tokenId: issue.tokenId.slice(0, 500) } : {}
5302
+ }));
5303
+ }
3728
5304
  function workerFailure(error) {
5305
+ if (error instanceof Document2ValidationError) {
5306
+ return {
5307
+ response: {
5308
+ ok: false,
5309
+ error: {
5310
+ code: "invalid_document",
5311
+ message: "Document validation failed",
5312
+ issues: boundedValidationIssues(error.issues)
5313
+ }
5314
+ },
5315
+ status: 422
5316
+ };
5317
+ }
3729
5318
  if (error instanceof Document2CommandError) {
3730
5319
  return {
3731
5320
  response: { ok: false, error: { code: error.code, message: error.message } },
@@ -3760,13 +5349,41 @@ function asDocument2Command(value) {
3760
5349
  }
3761
5350
 
3762
5351
  // src/document2-cli/execute.ts
3763
- function normalizeDocument(document2) {
5352
+ function resolveDocument2(document2) {
3764
5353
  try {
3765
- return toDocumentJson2(fromDocumentJson2(document2));
5354
+ return fromDocumentJson2(document2);
3766
5355
  } catch {
3767
5356
  throw new Document2CommandError("invalid_document", "Document JSON is invalid");
3768
5357
  }
3769
5358
  }
5359
+ function normalizeDocument(document2) {
5360
+ return toDocumentJson2(resolveDocument2(document2));
5361
+ }
5362
+ function collectAssetIds(blocks) {
5363
+ const assetIds = [];
5364
+ const seen = /* @__PURE__ */ new Set();
5365
+ const visit = (block) => {
5366
+ if (block.kind === "image") {
5367
+ const assetId = block.assetId?.trim();
5368
+ if (assetId && !seen.has(assetId)) {
5369
+ seen.add(assetId);
5370
+ assetIds.push(assetId);
5371
+ }
5372
+ return;
5373
+ }
5374
+ if (block.kind === "list") {
5375
+ for (const item of block.items) {
5376
+ for (const child of item.blocks) {
5377
+ visit(child);
5378
+ }
5379
+ }
5380
+ }
5381
+ };
5382
+ for (const block of blocks) {
5383
+ visit(block);
5384
+ }
5385
+ return assetIds;
5386
+ }
3770
5387
  function executeDocument2WorkerRequest(input) {
3771
5388
  const request = parseDocument2WorkerRequest(input);
3772
5389
  if (request.action === "normalize") {
@@ -3775,6 +5392,14 @@ function executeDocument2WorkerRequest(input) {
3775
5392
  if (request.action === "outline") {
3776
5393
  return { ok: true, outline: document2Outline(asDocument2Json(request.document)) };
3777
5394
  }
5395
+ if (request.action === "export") {
5396
+ const document2 = resolveDocument2(request.document);
5397
+ return {
5398
+ ok: true,
5399
+ latex: document2Latex2(document2, { twocolumn: true }),
5400
+ asset_ids: collectAssetIds(document2.blocks)
5401
+ };
5402
+ }
3778
5403
  return {
3779
5404
  ok: true,
3780
5405
  document: applyDocument2Command(asDocument2Json(request.document), asDocument2Command(request.command))
@@ -3906,6 +5531,9 @@ function actionForPath(pathname) {
3906
5531
  if (pathname === "/v1/document2/outline") {
3907
5532
  return "outline";
3908
5533
  }
5534
+ if (pathname === "/v1/document2/export") {
5535
+ return "export";
5536
+ }
3909
5537
  if (pathname === "/v1/document2/commands") {
3910
5538
  return "apply_command";
3911
5539
  }