@drghaliasri/butex 7.0.2 → 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() {
@@ -650,6 +807,19 @@ function collectDocument2Labels(document2) {
650
807
  walk(document2.blocks);
651
808
  return entries;
652
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
+ }
653
823
  function applyFloatMetaPatch(block, patch) {
654
824
  if (typeof patch.centered === "boolean") {
655
825
  block.centered = patch.centered;
@@ -1840,6 +2010,68 @@ var ATOMIC_OPERATOR_COMMANDS = {
1840
2010
  };
1841
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);
1842
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
+ }
1843
2075
 
1844
2076
  // src/editor/characterFonts.ts
1845
2077
  var CHARACTER_FONT_SPECS = [
@@ -2899,6 +3131,10 @@ var DOCUMENT2_KEY_PATTERN = /^[\p{L}\p{M}\p{Nd}:._-]+$/u;
2899
3131
  function normalizeDocument2Key(key) {
2900
3132
  return key.normalize("NFC").trim();
2901
3133
  }
3134
+ function isValidDocument2Key(key) {
3135
+ const normalized = normalizeDocument2Key(key);
3136
+ return normalized.length > 0 && DOCUMENT2_KEY_PATTERN.test(normalized);
3137
+ }
2902
3138
  function isDuplicateDocument2Key(key, namespace) {
2903
3139
  const normalized = normalizeDocument2Key(key);
2904
3140
  if (normalized.length === 0) {
@@ -4224,6 +4460,809 @@ function document2Outline(json) {
4224
4460
  });
4225
4461
  }
4226
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
+
4227
5266
  // src/document2-cli/protocol.ts
4228
5267
  var Document2WorkerProtocolError = class extends Error {
4229
5268
  code;
@@ -4243,7 +5282,7 @@ function parseDocument2WorkerRequest(value) {
4243
5282
  if (!("document" in value)) {
4244
5283
  throw new Document2WorkerProtocolError("invalid_request", "Worker request requires a document");
4245
5284
  }
4246
- if (value.action === "normalize" || value.action === "outline") {
5285
+ if (value.action === "normalize" || value.action === "outline" || value.action === "export") {
4247
5286
  return { action: value.action, document: value.document };
4248
5287
  }
4249
5288
  if (value.action === "apply_command") {
@@ -4254,7 +5293,28 @@ function parseDocument2WorkerRequest(value) {
4254
5293
  }
4255
5294
  throw new Document2WorkerProtocolError("invalid_request", `Unsupported worker action: ${value.action}`);
4256
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
+ }
4257
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
+ }
4258
5318
  if (error instanceof Document2CommandError) {
4259
5319
  return {
4260
5320
  response: { ok: false, error: { code: error.code, message: error.message } },
@@ -4289,13 +5349,41 @@ function asDocument2Command(value) {
4289
5349
  }
4290
5350
 
4291
5351
  // src/document2-cli/execute.ts
4292
- function normalizeDocument(document2) {
5352
+ function resolveDocument2(document2) {
4293
5353
  try {
4294
- return toDocumentJson2(fromDocumentJson2(document2));
5354
+ return fromDocumentJson2(document2);
4295
5355
  } catch {
4296
5356
  throw new Document2CommandError("invalid_document", "Document JSON is invalid");
4297
5357
  }
4298
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
+ }
4299
5387
  function executeDocument2WorkerRequest(input) {
4300
5388
  const request = parseDocument2WorkerRequest(input);
4301
5389
  if (request.action === "normalize") {
@@ -4304,6 +5392,14 @@ function executeDocument2WorkerRequest(input) {
4304
5392
  if (request.action === "outline") {
4305
5393
  return { ok: true, outline: document2Outline(asDocument2Json(request.document)) };
4306
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
+ }
4307
5403
  return {
4308
5404
  ok: true,
4309
5405
  document: applyDocument2Command(asDocument2Json(request.document), asDocument2Command(request.command))
@@ -4435,6 +5531,9 @@ function actionForPath(pathname) {
4435
5531
  if (pathname === "/v1/document2/outline") {
4436
5532
  return "outline";
4437
5533
  }
5534
+ if (pathname === "/v1/document2/export") {
5535
+ return "export";
5536
+ }
4438
5537
  if (pathname === "/v1/document2/commands") {
4439
5538
  return "apply_command";
4440
5539
  }