@drghaliasri/butex 8.1.2 → 8.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/book.js CHANGED
@@ -22,6 +22,7 @@ var book_exports = {};
22
22
  __export(book_exports, {
23
23
  BookContractError: () => BookContractError,
24
24
  applyBookCommand: () => applyBookCommand,
25
+ book2Latex: () => book2Latex,
25
26
  bookContextForUnit: () => bookContextForUnit,
26
27
  bookOutline: () => bookOutline,
27
28
  getBookReferenceIndex: () => getBookReferenceIndex,
@@ -41,6 +42,34 @@ function documentId(prefix) {
41
42
  return id;
42
43
  }
43
44
 
45
+ // src/editor/digits.ts
46
+ var WESTERN = "0123456789";
47
+ var ARABIC_INDIC = "\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669";
48
+ var PERSIAN_INDIC = "\u06F0\u06F1\u06F2\u06F3\u06F4\u06F5\u06F6\u06F7\u06F8\u06F9";
49
+ var digitSets = {
50
+ western: WESTERN,
51
+ arabicIndic: ARABIC_INDIC,
52
+ persianIndic: PERSIAN_INDIC
53
+ };
54
+ function digitValue(char) {
55
+ const western = WESTERN.indexOf(char);
56
+ if (western >= 0) {
57
+ return western;
58
+ }
59
+ const arabicIndic = ARABIC_INDIC.indexOf(char);
60
+ if (arabicIndic >= 0) {
61
+ return arabicIndic;
62
+ }
63
+ return PERSIAN_INDIC.indexOf(char);
64
+ }
65
+ function formatDigits(value, digitForm = "western") {
66
+ const target = digitSets[digitForm];
67
+ return Array.from(value, (char) => {
68
+ const value2 = digitValue(char);
69
+ return value2 >= 0 ? target[value2] : char;
70
+ }).join("");
71
+ }
72
+
44
73
  // src/document/articleMeta.ts
45
74
  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";
46
75
  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";
@@ -159,6 +188,16 @@ function referenceFromJson(json) {
159
188
  fieldSeparator: normalizeReferenceFieldSeparator(json.field_separator)
160
189
  };
161
190
  }
191
+ function bibliographyEntryBody(reference, separator = reference.fieldSeparator, options = {}) {
192
+ const year = options.digitForm !== void 0 ? formatDigits(reference.year, options.digitForm) : reference.year;
193
+ const parts = [reference.authors, reference.title, reference.venue, year].filter((part) => part.trim().length > 0);
194
+ return parts.join(`${separator} `);
195
+ }
196
+ function bibliographyEntryLatex(reference) {
197
+ const body = bibliographyEntryBody(reference);
198
+ const url = reference.url.trim().length > 0 ? ` \\url{${reference.url}}` : "";
199
+ return `\\bibitem{${reference.key}} ${body}${url}`.trim();
200
+ }
162
201
 
163
202
  // src/ast/commands/index.ts
164
203
  function renderCommandCore(context) {
@@ -513,6 +552,26 @@ function fromMathObjectJson(json, mode = "english") {
513
552
  closing: json.closing
514
553
  };
515
554
  }
555
+ function renderMathNodeLatex(math) {
556
+ const lines = math.lines.map((line) => line.arabicLatex());
557
+ if (math.mathMode === "$" || math.mathMode === "\\(") {
558
+ return math.mathMode + lines.join(" ") + math.closing;
559
+ }
560
+ if (math.mathMode === "$$" || math.mathMode === "\\[") {
561
+ if (lines.length === 1) {
562
+ return math.mathMode + "\n" + lines[0] + "\n" + math.closing;
563
+ }
564
+ return math.mathMode + "\n" + lines.map((line) => ` ${line}`).join(" \\\\\n") + "\n" + math.closing;
565
+ }
566
+ if (lines.length === 1) {
567
+ return `${math.mathMode}
568
+ ${lines[0]}
569
+ ${math.closing}`;
570
+ }
571
+ return `${math.mathMode}
572
+ ${lines.map((line) => ` ${line}`).join(" \\\\\n")}
573
+ ${math.closing}`;
574
+ }
516
575
 
517
576
  // src/document/labels.ts
518
577
  function parseFloatMetaFromJson(json) {
@@ -630,6 +689,23 @@ function labelNumberMap(document2) {
630
689
  }
631
690
  return map;
632
691
  }
692
+ function stripDisplayMathDelimiters(source) {
693
+ const trimmed = source.trim();
694
+ if (trimmed.startsWith("\\[") && trimmed.endsWith("\\]")) {
695
+ return trimmed.slice(2, -2).trim();
696
+ }
697
+ if (trimmed.startsWith("$$") && trimmed.endsWith("$$")) {
698
+ return trimmed.slice(2, -2).trim();
699
+ }
700
+ for (const environment of ["equation", "equation*"]) {
701
+ const opening = `\\begin{${environment}}`;
702
+ const closing = `\\end{${environment}}`;
703
+ if (trimmed.startsWith(opening) && trimmed.endsWith(closing)) {
704
+ return trimmed.slice(opening.length, -closing.length).trim();
705
+ }
706
+ }
707
+ return trimmed;
708
+ }
633
709
 
634
710
  // src/document/inlineIdentity.ts
635
711
  function createDocumentIdentityState() {
@@ -1279,6 +1355,535 @@ function fromDocumentJson(json, options = {}) {
1279
1355
  };
1280
1356
  }
1281
1357
 
1358
+ // src/editor/accentCommands.ts
1359
+ var ACCENT_COMMANDS = {
1360
+ vec: {
1361
+ id: "vec",
1362
+ englishTex: "\\vec",
1363
+ arabicTex: "\\arabvec",
1364
+ placement: "over",
1365
+ label: "\u20D7",
1366
+ title: "\u0633\u0647\u0645 \u0641\u0648\u0642"
1367
+ },
1368
+ hat: {
1369
+ id: "hat",
1370
+ englishTex: "\\hat",
1371
+ arabicTex: "\\hat",
1372
+ placement: "over",
1373
+ label: "\u02C6",
1374
+ title: "\u0642\u0628\u0639\u0629"
1375
+ },
1376
+ tilde: {
1377
+ id: "tilde",
1378
+ englishTex: "\\tilde",
1379
+ arabicTex: "\\tilde",
1380
+ placement: "over",
1381
+ label: "\u02DC",
1382
+ title: "\u0645\u062F\u0629"
1383
+ },
1384
+ dot: {
1385
+ id: "dot",
1386
+ englishTex: "\\dot",
1387
+ arabicTex: "\\dot",
1388
+ placement: "over",
1389
+ label: "\u02D9",
1390
+ title: "\u0646\u0642\u0637\u0629 \u0641\u0648\u0642"
1391
+ },
1392
+ ddot: {
1393
+ id: "ddot",
1394
+ englishTex: "\\ddot",
1395
+ arabicTex: "\\ddot",
1396
+ placement: "over",
1397
+ label: "\xA8",
1398
+ title: "\u0646\u0642\u0637\u062A\u0627\u0646 \u0641\u0648\u0642"
1399
+ },
1400
+ dddot: {
1401
+ id: "dddot",
1402
+ englishTex: "\\dddot",
1403
+ arabicTex: "\\dddot",
1404
+ placement: "over",
1405
+ label: "\u20DB",
1406
+ title: "\u062B\u0644\u0627\u062B \u0646\u0642\u0627\u0637 \u0641\u0648\u0642"
1407
+ },
1408
+ bar: {
1409
+ id: "bar",
1410
+ englishTex: "\\bar",
1411
+ arabicTex: "\\bar",
1412
+ placement: "over",
1413
+ label: "\xAF",
1414
+ title: "\u062E\u0637 \u0641\u0648\u0642"
1415
+ },
1416
+ check: {
1417
+ id: "check",
1418
+ englishTex: "\\check",
1419
+ arabicTex: "\\check",
1420
+ placement: "over",
1421
+ label: "\u02C7",
1422
+ title: "\u0639\u0644\u0627\u0645\u0629 \u062A\u062D\u0642\u0642"
1423
+ },
1424
+ breve: {
1425
+ id: "breve",
1426
+ englishTex: "\\breve",
1427
+ arabicTex: "\\breve",
1428
+ placement: "over",
1429
+ label: "\u02D8",
1430
+ title: "\u0642\u0648\u0633 \u0642\u0635\u064A\u0631"
1431
+ },
1432
+ acute: {
1433
+ id: "acute",
1434
+ englishTex: "\\acute",
1435
+ arabicTex: "\\grave",
1436
+ placement: "over",
1437
+ label: "\xB4",
1438
+ title: "\u0646\u0628\u0631\u0629 \u062D\u0627\u062F\u0629"
1439
+ },
1440
+ grave: {
1441
+ id: "grave",
1442
+ englishTex: "\\grave",
1443
+ arabicTex: "\\acute",
1444
+ placement: "over",
1445
+ label: "`",
1446
+ title: "\u0646\u0628\u0631\u0629 \u062B\u0642\u064A\u0644\u0629"
1447
+ },
1448
+ overline: {
1449
+ id: "overline",
1450
+ englishTex: "\\overline",
1451
+ arabicTex: "\\overline",
1452
+ placement: "over",
1453
+ label: "\u203E",
1454
+ title: "\u062E\u0637 \u0639\u0644\u0648\u064A \u0645\u0645\u062A\u062F"
1455
+ },
1456
+ underline: {
1457
+ id: "underline",
1458
+ englishTex: "\\underline",
1459
+ arabicTex: "\\underline",
1460
+ placement: "under",
1461
+ label: "_",
1462
+ title: "\u062E\u0637 \u0633\u0641\u0644\u064A"
1463
+ },
1464
+ overleftarrow: {
1465
+ id: "overleftarrow",
1466
+ englishTex: "\\overleftarrow",
1467
+ arabicTex: "\\overrightarrow",
1468
+ placement: "over",
1469
+ label: "\u2190",
1470
+ title: "\u0633\u0647\u0645 \u0639\u0644\u0648\u064A \u0625\u0644\u0649 \u0627\u0644\u064A\u0633\u0627\u0631"
1471
+ },
1472
+ overrightarrow: {
1473
+ id: "overrightarrow",
1474
+ englishTex: "\\overrightarrow",
1475
+ arabicTex: "\\overleftarrow",
1476
+ placement: "over",
1477
+ label: "\u2192",
1478
+ title: "\u0633\u0647\u0645 \u0639\u0644\u0648\u064A \u0625\u0644\u0649 \u0627\u0644\u064A\u0645\u064A\u0646"
1479
+ },
1480
+ overleftrightarrow: {
1481
+ id: "overleftrightarrow",
1482
+ englishTex: "\\overleftrightarrow",
1483
+ arabicTex: "\\overleftrightarrow",
1484
+ placement: "over",
1485
+ label: "\u2194",
1486
+ title: "\u0633\u0647\u0645 \u0639\u0644\u0648\u064A \u0645\u0632\u062F\u0648\u062C \u0627\u0644\u0627\u062A\u062C\u0627\u0647"
1487
+ }
1488
+ };
1489
+ function accentCommandSpec(id) {
1490
+ return Object.prototype.hasOwnProperty.call(ACCENT_COMMANDS, id) ? ACCENT_COMMANDS[id] : null;
1491
+ }
1492
+ function accentCommandIdFromTex(tex) {
1493
+ const normalized = tex.startsWith("\\") ? tex : `\\${tex}`;
1494
+ for (const spec of Object.values(ACCENT_COMMANDS)) {
1495
+ if (spec.englishTex === normalized) {
1496
+ return spec.id;
1497
+ }
1498
+ }
1499
+ for (const spec of Object.values(ACCENT_COMMANDS)) {
1500
+ if (spec.arabicTex === normalized) {
1501
+ return spec.id;
1502
+ }
1503
+ }
1504
+ return null;
1505
+ }
1506
+
1507
+ // src/editor/atomicCommands.ts
1508
+ var ATOMIC_COMMANDS = {
1509
+ ///////////////////////// Functions ////////////////////////////////
1510
+ //////////////// Trigonometric Functions
1511
+ cos: {
1512
+ id: "cos",
1513
+ category: "function",
1514
+ englishTex: "\\cos",
1515
+ arabicTex: "\\arcos",
1516
+ arabicLabel: "\u062C\u062A\u0627",
1517
+ title: "\u062C\u064A\u0628 \u0627\u0644\u062A\u0645\u0627\u0645"
1518
+ },
1519
+ sin: {
1520
+ id: "sin",
1521
+ category: "function",
1522
+ englishTex: "\\sin",
1523
+ arabicTex: "\\arsin",
1524
+ arabicLabel: "\u062C\u0627",
1525
+ title: "\u062C\u064A\u0628"
1526
+ },
1527
+ tan: {
1528
+ id: "tan",
1529
+ category: "function",
1530
+ englishTex: "\\tan",
1531
+ arabicTex: "\\artan",
1532
+ arabicLabel: "\u0638\u0627",
1533
+ title: "\u0638\u0644"
1534
+ },
1535
+ cot: {
1536
+ id: "cot",
1537
+ category: "function",
1538
+ englishTex: "\\cot",
1539
+ arabicTex: "\\arcot",
1540
+ arabicLabel: "\u0638\u062A\u0627",
1541
+ title: "\u0638\u0644 \u062A\u0645\u0627\u0645"
1542
+ },
1543
+ sec: {
1544
+ id: "sec",
1545
+ category: "function",
1546
+ englishTex: "\\sec",
1547
+ arabicTex: "\\arsec",
1548
+ arabicLabel: "\u0642\u0627",
1549
+ title: "\u0642\u0627\u0637\u0639"
1550
+ },
1551
+ csc: {
1552
+ id: "csc",
1553
+ category: "function",
1554
+ englishTex: "\\csc",
1555
+ arabicTex: "\\arcsc",
1556
+ arabicLabel: "\u0642\u062A\u0627",
1557
+ title: "\u0642\u0627\u0637\u0639 \u062A\u0645\u0627\u0645"
1558
+ },
1559
+ /////////////////// Arc Trigonometric Functions
1560
+ arccos: {
1561
+ id: "arccos",
1562
+ category: "function",
1563
+ englishTex: "\\arccos",
1564
+ arabicTex: "\\aracos",
1565
+ arabicLabel: "\u0642\u062C\u062A\u0627",
1566
+ title: "\u0642\u0627\u0637\u0639 \u062C\u064A\u0628 \u0627\u0644\u062A\u0645\u0627\u0645"
1567
+ },
1568
+ arcsin: {
1569
+ id: "arcsin",
1570
+ category: "function",
1571
+ englishTex: "\\arcsin",
1572
+ arabicTex: "\\arasin",
1573
+ arabicLabel: "\u0642\u062C\u0627",
1574
+ title: "\u0642\u0627\u0637\u0639 \u062C\u064A\u0628"
1575
+ },
1576
+ arctan: {
1577
+ id: "arctan",
1578
+ category: "function",
1579
+ englishTex: "\\arctan",
1580
+ arabicTex: "\\aratan",
1581
+ arabicLabel: "\u0642\u0638\u0627",
1582
+ title: "\u0642\u0627\u0637\u0639 \u0638\u0644"
1583
+ },
1584
+ arccot: {
1585
+ id: "arccot",
1586
+ category: "function",
1587
+ englishTex: "\\arccot",
1588
+ arabicTex: "\\aracot",
1589
+ arabicLabel: "\u0642\u0638\u062A\u0627",
1590
+ title: "\u0642\u0627\u0637\u0639 \u0638\u0644 \u0627\u0644\u062A\u0645\u0627\u0645"
1591
+ },
1592
+ arcsec: {
1593
+ id: "arcsec",
1594
+ category: "function",
1595
+ englishTex: "\\arcsec",
1596
+ arabicTex: "\\arasec",
1597
+ arabicLabel: "\u0642\u0642\u0627",
1598
+ title: "\u0642\u0627\u0637\u0639 \u0627\u0644\u0642\u0627\u0637\u0639"
1599
+ },
1600
+ arccsc: {
1601
+ id: "arccsc",
1602
+ category: "function",
1603
+ englishTex: "\\arccsc",
1604
+ arabicTex: "\\aracsc",
1605
+ arabicLabel: "\u0642\u0642\u062A\u0627",
1606
+ title: "\u0642\u0627\u0637\u0639 \u0627\u0644\u0642\u0627\u0637\u0639 \u0627\u0644\u062A\u0645\u0627\u0645"
1607
+ },
1608
+ ///////////////// Hyperbolic Functions
1609
+ cosh: {
1610
+ id: "cosh",
1611
+ category: "function",
1612
+ englishTex: "\\cosh",
1613
+ arabicTex: "\\arcosh",
1614
+ arabicLabel: "\u062C\u062A\u0632\u0627",
1615
+ title: "\u062C\u064A\u0628 \u0627\u0644\u062A\u0645\u0627\u0645 \u0627\u0644\u0632\u0627\u0626\u062F"
1616
+ },
1617
+ sinh: {
1618
+ id: "sinh",
1619
+ category: "function",
1620
+ englishTex: "\\sinh",
1621
+ arabicTex: "\\arsinh",
1622
+ arabicLabel: "\u062C\u0632\u0627",
1623
+ title: "\u062C\u064A\u0628 \u0627\u0644\u0632\u0627\u0626\u062F"
1624
+ },
1625
+ tanh: {
1626
+ id: "tanh",
1627
+ category: "function",
1628
+ englishTex: "\\tanh",
1629
+ arabicTex: "\\artanh",
1630
+ arabicLabel: "\u0638\u0632\u0627",
1631
+ title: "\u0638\u0644 \u0627\u0644\u0632\u0627\u0626\u062F"
1632
+ },
1633
+ coth: {
1634
+ id: "coth",
1635
+ category: "function",
1636
+ englishTex: "\\coth",
1637
+ arabicTex: "\\arcoth",
1638
+ arabicLabel: "\u0638\u062A\u0632\u0627",
1639
+ title: "\u0638\u0644 \u062A\u0645\u0627\u0645 \u0627\u0644\u0632\u0627\u0626\u062F"
1640
+ },
1641
+ ////// These function somehow doesnt exist in LaTeX and therefore MathJax, skip for now. no problem.
1642
+ // sech: {
1643
+ // id: 'sech',
1644
+ // category: 'function',
1645
+ // englishTex: '\\sech',
1646
+ // arabicTex: '\\arsech',
1647
+ // arabicLabel: 'قزا',
1648
+ // title: 'قاطع الزائد',
1649
+ // },
1650
+ // csch: {
1651
+ // id: 'csch',
1652
+ // category: 'function',
1653
+ // englishTex: '\\csch',
1654
+ // arabicTex: '\\arcsch',
1655
+ // arabicLabel: 'قتزا',
1656
+ // title: 'قاطع تمام الزائد',
1657
+ // },
1658
+ ///////////////// arc Hyperbolic Functions
1659
+ ///// Not on MathJax, skip for now, it is okay.
1660
+ ////////////////////// Limits & Series ////////////////////////////////
1661
+ sum: {
1662
+ id: "sum",
1663
+ category: "limits_series",
1664
+ englishTex: "\\sum",
1665
+ arabicTex: "\\arsum",
1666
+ arabicLabel: "\u0645\u062C\u0640\u0640\u0640",
1667
+ title: "\u0645\u062C\u0645\u0648\u0639"
1668
+ },
1669
+ prod: {
1670
+ id: "prod",
1671
+ category: "limits_series",
1672
+ englishTex: "\\prod",
1673
+ arabicTex: "\\arprod",
1674
+ arabicLabel: "\u062C\u0640\u0640\u0640\u062F",
1675
+ title: "\u062C\u062F\u0627\u0621"
1676
+ },
1677
+ lim: {
1678
+ id: "lim",
1679
+ category: "limits_series",
1680
+ englishTex: "\\lim",
1681
+ arabicTex: "\\arlim",
1682
+ arabicLabel: "\u0646\u0640\u0640\u0640\u0640\u0640\u0647\u0627",
1683
+ title: "\u062D\u062F"
1684
+ },
1685
+ arg: {
1686
+ id: "arg",
1687
+ category: "limits_series",
1688
+ englishTex: "\\arg",
1689
+ arabicTex: "\\ararg",
1690
+ arabicLabel: "\u062D\u062C",
1691
+ title: "\u062D\u062C\u0629"
1692
+ },
1693
+ max: {
1694
+ id: "max",
1695
+ category: "limits_series",
1696
+ englishTex: "\\max",
1697
+ arabicTex: "\\armax",
1698
+ arabicLabel: "\u0623\u0643\u0628\u0631",
1699
+ title: "\u0623\u0643\u0628\u0631"
1700
+ },
1701
+ min: {
1702
+ id: "min",
1703
+ category: "limits_series",
1704
+ englishTex: "\\min",
1705
+ arabicTex: "\\armin",
1706
+ arabicLabel: "\u0623\u0635\u063A\u0631",
1707
+ title: "\u0623\u0635\u063A\u0631"
1708
+ },
1709
+ sup: {
1710
+ id: "sup",
1711
+ category: "limits_series",
1712
+ englishTex: "\\sup",
1713
+ arabicTex: "\\arsup",
1714
+ arabicLabel: "\u0623\u0639\u0644\u0649",
1715
+ title: "\u0623\u0639\u0644\u0649"
1716
+ },
1717
+ inf: {
1718
+ id: "inf",
1719
+ category: "limits_series",
1720
+ englishTex: "\\inf",
1721
+ arabicTex: "\\arinf",
1722
+ arabicLabel: "\u0623\u062F\u0646\u0649",
1723
+ title: "\u0623\u062F\u0646\u0649"
1724
+ },
1725
+ ////////////////////// Logarithmic and Exponential and Determinant Functions ////////////////////////////////
1726
+ pi: {
1727
+ id: "pi",
1728
+ category: "function2",
1729
+ englishTex: "\\pi",
1730
+ arabicTex: "\\arpi",
1731
+ arabicLabel: "\u0637",
1732
+ title: "\u0646\u0633\u0628\u0629 \u0627\u0644\u062F\u0627\u0626\u0631\u0629"
1733
+ },
1734
+ exp: {
1735
+ id: "exp",
1736
+ category: "function2",
1737
+ englishTex: "\\exp",
1738
+ arabicTex: "\\arexp",
1739
+ arabicLabel: "\u0647\u0640",
1740
+ title: "\u0623\u0633\u064A\u0629"
1741
+ },
1742
+ ln: {
1743
+ id: "ln",
1744
+ category: "function2",
1745
+ englishTex: "\\ln",
1746
+ arabicTex: "\\arln",
1747
+ arabicRenderTex: "\\prescript{}{\\arexp}{\\arlog}",
1748
+ arabicLabel: "\u0644\u0648",
1749
+ title: "\u0644\u0648\u063A\u0627\u0631\u064A\u062A\u0645 \u0637\u0628\u064A\u0639\u064A"
1750
+ },
1751
+ log: {
1752
+ id: "log",
1753
+ category: "function2",
1754
+ englishTex: "\\log",
1755
+ arabicTex: "\\arlog",
1756
+ arabicLabel: "\u0644\u0648",
1757
+ title: "\u0644\u0648\u063A\u0627\u0631\u064A\u062A\u0645"
1758
+ },
1759
+ det: {
1760
+ id: "det",
1761
+ category: "function2",
1762
+ englishTex: "\\det",
1763
+ arabicTex: "\\ardet",
1764
+ arabicLabel: "\u0645\u062D\u062F\u062F",
1765
+ title: "\u0645\u062D\u062F\u062F"
1766
+ },
1767
+ ////////////////////// Derivatives ////////////////////////////////
1768
+ ad: {
1769
+ id: "ad",
1770
+ category: "derivative",
1771
+ englishTex: "\\mathrm{d}",
1772
+ englishLabel: "d",
1773
+ arabicTex: "\\ad",
1774
+ arabicLabel: "\u0621",
1775
+ title: "\u0639\u0644\u0627\u0645\u0629 \u0627\u0644\u0627\u0634\u062A\u0642\u0627\u0642"
1776
+ },
1777
+ ////////////////////// Groups /////////////////////////////////
1778
+ N: {
1779
+ id: "N",
1780
+ category: "groups",
1781
+ englishTex: "\\mathbb{N}",
1782
+ arabicTex: "\\arabN",
1783
+ arabicLabel: "\u0637",
1784
+ title: "\u0623\u0639\u062F\u0627\u062F \u0637\u0628\u064A\u0639\u064A\u0629"
1785
+ },
1786
+ Z: {
1787
+ id: "Z",
1788
+ category: "groups",
1789
+ englishTex: "\\mathbb{Z}",
1790
+ arabicTex: "\\arabZ",
1791
+ arabicLabel: "\u0635",
1792
+ title: "\u0623\u0639\u062F\u0627\u062F \u0635\u062D\u064A\u062D\u0629"
1793
+ },
1794
+ Q: {
1795
+ id: "Q",
1796
+ category: "groups",
1797
+ englishTex: "\\mathbb{Q}",
1798
+ arabicTex: "\\arabQ",
1799
+ arabicLabel: "\u0646",
1800
+ title: "\u0623\u0639\u062F\u0627\u062F \u0646\u0633\u0628\u064A\u0629"
1801
+ },
1802
+ R: {
1803
+ id: "R",
1804
+ category: "groups",
1805
+ englishTex: "\\mathbb{R}",
1806
+ arabicTex: "\\arabR",
1807
+ arabicLabel: "\u062D",
1808
+ title: "\u0623\u0639\u062F\u0627\u062F \u062D\u0642\u064A\u0642\u064A\u0629"
1809
+ },
1810
+ C: {
1811
+ id: "C",
1812
+ category: "groups",
1813
+ englishTex: "\\mathbb{C}",
1814
+ arabicTex: "\\arabC",
1815
+ arabicLabel: "\u0639",
1816
+ title: "\u0623\u0639\u062F\u0627\u062F \u0639\u064F\u0642\u062F\u064A\u0629"
1817
+ },
1818
+ H: {
1819
+ id: "H",
1820
+ category: "groups",
1821
+ englishTex: "\\mathbb{H}",
1822
+ arabicTex: "\\arabH",
1823
+ arabicLabel: "\u0631",
1824
+ title: "\u0623\u0639\u062F\u0627\u062F \u0631\u0628\u0627\u0639\u064A\u0629"
1825
+ },
1826
+ ////////////////////// Operations ////////////////////////////
1827
+ ////////////////////// Spacing ////////////////////////////////
1828
+ negThinSpace: {
1829
+ id: "negThinSpace",
1830
+ category: "spacing",
1831
+ englishTex: "\\!",
1832
+ arabicTex: "\\!",
1833
+ arabicLabel: "",
1834
+ title: "\u0641\u0631\u0627\u063A \u0633\u0627\u0644\u0628 \u0631\u0641\u064A\u0639",
1835
+ spacing: { direction: "negative", level: 1 }
1836
+ },
1837
+ thinSpace: {
1838
+ id: "thinSpace",
1839
+ category: "spacing",
1840
+ englishTex: "\\,",
1841
+ arabicTex: "\\,",
1842
+ arabicLabel: "",
1843
+ title: "\u0641\u0631\u0627\u063A \u0631\u0641\u064A\u0639",
1844
+ spacing: { direction: "positive", level: 1 }
1845
+ },
1846
+ mediumSpace: {
1847
+ id: "mediumSpace",
1848
+ category: "spacing",
1849
+ englishTex: "\\:",
1850
+ arabicTex: "\\:",
1851
+ arabicLabel: "",
1852
+ title: "\u0641\u0631\u0627\u063A \u0645\u062A\u0648\u0633\u0637",
1853
+ spacing: { direction: "positive", level: 1 }
1854
+ },
1855
+ thickSpace: {
1856
+ id: "thickSpace",
1857
+ category: "spacing",
1858
+ englishTex: "\\;",
1859
+ arabicTex: "\\;",
1860
+ arabicLabel: "",
1861
+ title: "\u0641\u0631\u0627\u063A \u0639\u0631\u064A\u0636",
1862
+ spacing: { direction: "positive", level: 2 }
1863
+ },
1864
+ quadSpace: {
1865
+ id: "quadSpace",
1866
+ category: "spacing",
1867
+ englishTex: "\\quad",
1868
+ arabicTex: "\\quad",
1869
+ arabicLabel: "",
1870
+ title: "\u0641\u0631\u0627\u063A \u0643\u0628\u064A\u0631",
1871
+ spacing: { direction: "positive", level: 3 }
1872
+ },
1873
+ qquadSpace: {
1874
+ id: "qquadSpace",
1875
+ category: "spacing",
1876
+ englishTex: "\\qquad",
1877
+ arabicTex: "\\qquad",
1878
+ arabicLabel: "",
1879
+ title: "\u0641\u0631\u0627\u063A \u0643\u0628\u064A\u0631 \u062C\u062F\u0627",
1880
+ spacing: { direction: "positive", level: 4 }
1881
+ }
1882
+ };
1883
+ function atomicCommandSpec(id) {
1884
+ return Object.prototype.hasOwnProperty.call(ATOMIC_COMMANDS, id) ? ATOMIC_COMMANDS[id] : null;
1885
+ }
1886
+
1282
1887
  // src/editor/atomicCommandsOperators.ts
1283
1888
  var ATOMIC_OPERATOR_COMMANDS = {
1284
1889
  inf: {
@@ -1834,6 +2439,300 @@ var ATOMIC_OPERATOR_COMMANDS = {
1834
2439
  };
1835
2440
  var MIRRORED_OPERATOR_TEX = Object.values(ATOMIC_OPERATOR_COMMANDS).filter((command) => command.mirror).map((command) => command.Tex).sort((a, b) => b.length - a.length);
1836
2441
  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);
2442
+ function matchingMirroredOperatorFrom(tex, index, operatorTexList) {
2443
+ for (const operatorTex of operatorTexList) {
2444
+ if (!tex.startsWith(operatorTex, index)) {
2445
+ continue;
2446
+ }
2447
+ const next = tex[index + operatorTex.length];
2448
+ if (next != null && /[A-Za-z]/.test(next)) {
2449
+ continue;
2450
+ }
2451
+ return operatorTex;
2452
+ }
2453
+ return null;
2454
+ }
2455
+ function findMatchingBrace(tex, openIndex) {
2456
+ let depth = 0;
2457
+ for (let index = openIndex; index < tex.length; index += 1) {
2458
+ const char = tex[index];
2459
+ if (char === "\\") {
2460
+ index += 1;
2461
+ continue;
2462
+ }
2463
+ if (char === "{") {
2464
+ depth += 1;
2465
+ } else if (char === "}") {
2466
+ depth -= 1;
2467
+ if (depth === 0) {
2468
+ return index;
2469
+ }
2470
+ }
2471
+ }
2472
+ return -1;
2473
+ }
2474
+ function mirrorBuTeXOperatorsInTex(tex, options = {}) {
2475
+ const mirroredOperatorTex = options.target === "compile" ? COMPILE_MIRRORED_OPERATOR_TEX : MIRRORED_OPERATOR_TEX;
2476
+ let result = "";
2477
+ let index = 0;
2478
+ while (index < tex.length) {
2479
+ if (tex.startsWith("\\butexmirror{", index)) {
2480
+ const end = findMatchingBrace(tex, index + "\\butexmirror".length);
2481
+ if (end !== -1) {
2482
+ const bodyStart = index + "\\butexmirror{".length;
2483
+ const body = tex.slice(bodyStart, end);
2484
+ if (options.target === "compile" && MIRRORED_OPERATOR_TEX.includes(body) && !mirroredOperatorTex.includes(body)) {
2485
+ result += body;
2486
+ } else {
2487
+ result += tex.slice(index, end + 1);
2488
+ }
2489
+ index = end + 1;
2490
+ continue;
2491
+ }
2492
+ }
2493
+ const operatorTex = matchingMirroredOperatorFrom(tex, index, mirroredOperatorTex);
2494
+ if (operatorTex) {
2495
+ result += `\\butexmirror{${operatorTex}}`;
2496
+ index += operatorTex.length;
2497
+ continue;
2498
+ }
2499
+ result += tex[index];
2500
+ index += 1;
2501
+ }
2502
+ return result;
2503
+ }
2504
+ function atomicOperatorCommandSpec(id) {
2505
+ return Object.prototype.hasOwnProperty.call(ATOMIC_OPERATOR_COMMANDS, id) ? ATOMIC_OPERATOR_COMMANDS[id] : null;
2506
+ }
2507
+
2508
+ // src/editor/standardCommands.ts
2509
+ var STANDARD_COMMANDS = {
2510
+ "\\alpha": { tex: "\\alpha", label: "\u03B1", title: "alpha" },
2511
+ "\\beta": { tex: "\\beta", label: "\u03B2", title: "beta" },
2512
+ "\\gamma": { tex: "\\gamma", label: "\u03B3", title: "gamma" },
2513
+ "\\delta": { tex: "\\delta", label: "\u03B4", title: "delta" },
2514
+ "\\epsilon": { tex: "\\epsilon", label: "\u03B5", title: "epsilon" },
2515
+ "\\eta": { tex: "\\eta", label: "\u03B7", title: "eta" },
2516
+ "\\theta": { tex: "\\theta", label: "\u03B8", title: "theta" },
2517
+ "\\lambda": { tex: "\\lambda", label: "\u03BB", title: "lambda" },
2518
+ "\\mu": { tex: "\\mu", label: "\u03BC", title: "mu" },
2519
+ "\\rho": { tex: "\\rho", label: "\u03C1", title: "rho" },
2520
+ "\\sigma": { tex: "\\sigma", label: "\u03C3", title: "sigma" },
2521
+ "\\tau": { tex: "\\tau", label: "\u03C4", title: "tau" },
2522
+ "\\phi": { tex: "\\phi", label: "\u03C6", title: "phi" },
2523
+ "\\chi": { tex: "\\chi", label: "\u03C7", title: "chi" },
2524
+ "\\psi": { tex: "\\psi", label: "\u03C8", title: "psi" },
2525
+ "\\omega": { tex: "\\omega", label: "\u03C9", title: "omega" },
2526
+ "\\zeta": { tex: "\\zeta", label: "\u03B6", title: "zeta" },
2527
+ "\\nabla": { tex: "\\nabla", label: "\u2207", title: "nabla" },
2528
+ "\\Delta": { tex: "\\Delta", label: "\u0394", title: "Delta" },
2529
+ "\\partial": { tex: "\\partial", label: "\u2202", title: "partial derivative" },
2530
+ "\\Longleftrightarrow": { tex: "\\Longleftrightarrow", label: "\u27FA", title: "long equivalence arrow" },
2531
+ "\\backslash": { tex: "\\backslash", label: "\u2216", title: "reverse solidus" }
2532
+ };
2533
+ function standardCommandSpec(tex) {
2534
+ return Object.prototype.hasOwnProperty.call(STANDARD_COMMANDS, tex) ? STANDARD_COMMANDS[tex] : null;
2535
+ }
2536
+ function isStandardCommandTex(tex) {
2537
+ return standardCommandSpec(tex) !== null;
2538
+ }
2539
+
2540
+ // src/editor/factory.ts
2541
+ var nextId2 = 1;
2542
+ function makeId(prefix) {
2543
+ const id = `${prefix}_${String(nextId2)}`;
2544
+ nextId2 += 1;
2545
+ return id;
2546
+ }
2547
+ function createEditorChain(nodes = []) {
2548
+ return {
2549
+ id: makeId("chain"),
2550
+ nodes
2551
+ };
2552
+ }
2553
+ function createEditorNode(kind, expr) {
2554
+ return {
2555
+ id: makeId("node"),
2556
+ kind,
2557
+ expr,
2558
+ characterFont: void 0,
2559
+ superscript: null,
2560
+ subscript: null,
2561
+ leftDelimExpr: "",
2562
+ rightDelimExpr: "",
2563
+ innerExpr: null,
2564
+ numerator: null,
2565
+ denominator: null,
2566
+ radicand: null,
2567
+ rootIndex: null,
2568
+ overExpr: null,
2569
+ underExpr: null,
2570
+ baseExpr: null,
2571
+ envName: null,
2572
+ matrixStyle: null,
2573
+ matrixRows: null,
2574
+ columnAlignments: null
2575
+ };
2576
+ }
2577
+ function createDelimiterNode(leftDelimExpr2, rightDelimExpr2) {
2578
+ return {
2579
+ ...createEditorNode("delimiter", ""),
2580
+ leftDelimExpr: leftDelimExpr2,
2581
+ rightDelimExpr: rightDelimExpr2,
2582
+ innerExpr: createEditorChain()
2583
+ };
2584
+ }
2585
+ function createBoxedNode() {
2586
+ return {
2587
+ ...createEditorNode("boxed", ""),
2588
+ innerExpr: createEditorChain()
2589
+ };
2590
+ }
2591
+ function createFracNode() {
2592
+ return {
2593
+ ...createEditorNode("frac", ""),
2594
+ numerator: createEditorChain(),
2595
+ denominator: createEditorChain()
2596
+ };
2597
+ }
2598
+ function createSqrtNode() {
2599
+ return {
2600
+ ...createEditorNode("sqrt", ""),
2601
+ radicand: createEditorChain(),
2602
+ rootIndex: createEditorChain()
2603
+ };
2604
+ }
2605
+ function createOversetNode() {
2606
+ return {
2607
+ ...createEditorNode("overset", ""),
2608
+ overExpr: createEditorChain(),
2609
+ baseExpr: createEditorChain()
2610
+ };
2611
+ }
2612
+ function createUndersetNode() {
2613
+ return {
2614
+ ...createEditorNode("underset", ""),
2615
+ underExpr: createEditorChain(),
2616
+ baseExpr: createEditorChain()
2617
+ };
2618
+ }
2619
+ function createAccentNode(accentId) {
2620
+ return {
2621
+ ...createEditorNode("accent", accentId),
2622
+ baseExpr: createEditorChain()
2623
+ };
2624
+ }
2625
+ function createGridEnvNode(envName, rows, columns, columnAlignments) {
2626
+ const safeRows = Math.max(1, Math.min(12, Math.trunc(rows)));
2627
+ const safeColumns = envName === "cases" ? 2 : Math.max(1, Math.min(12, Math.trunc(columns)));
2628
+ const matrixStyles = /* @__PURE__ */ new Set(["matrix", "pmatrix", "bmatrix", "Bmatrix", "vmatrix", "Vmatrix"]);
2629
+ const isMatrix = matrixStyles.has(envName) && envName !== "array" && envName !== "aligned";
2630
+ return {
2631
+ ...createEditorNode("env", ""),
2632
+ envName,
2633
+ matrixStyle: isMatrix ? envName : null,
2634
+ matrixRows: Array.from(
2635
+ { length: safeRows },
2636
+ () => Array.from({ length: safeColumns }, () => createEditorChain())
2637
+ ),
2638
+ columnAlignments: envName === "array" ? Array.from({ length: safeColumns }, (_, index) => columnAlignments?.[index] ?? "c") : null
2639
+ };
2640
+ }
2641
+ function cloneEditorSession(session) {
2642
+ return {
2643
+ englishTree: structuredClone(session.englishTree),
2644
+ arabicTree: structuredClone(session.arabicTree),
2645
+ activeSide: session.activeSide,
2646
+ splitLeafTyping: session.splitLeafTyping,
2647
+ forceSplitNextLeaf: session.forceSplitNextLeaf,
2648
+ arabicReverseNumberTyping: session.arabicReverseNumberTyping,
2649
+ currentCharacterFont: session.currentCharacterFont ?? "default",
2650
+ currentCharacterWrapper: session.currentCharacterWrapper ?? null,
2651
+ currentDigitForm: session.currentDigitForm ?? "western",
2652
+ caret: { ...session.caret },
2653
+ selection: session.selection ? { ...session.selection } : null,
2654
+ selectedNodeId: session.selectedNodeId,
2655
+ selectedStructureNodeId: session.selectedStructureNodeId,
2656
+ sync: structuredClone(session.sync),
2657
+ debugLog: session.debugLog.slice()
2658
+ };
2659
+ }
2660
+ function collectNodeIds(chain, ids) {
2661
+ for (const node of chain.nodes) {
2662
+ ids.push(node.id);
2663
+ if (node.superscript) {
2664
+ collectNodeIds(node.superscript, ids);
2665
+ }
2666
+ if (node.subscript) {
2667
+ collectNodeIds(node.subscript, ids);
2668
+ }
2669
+ if (node.innerExpr) {
2670
+ collectNodeIds(node.innerExpr, ids);
2671
+ }
2672
+ if (node.numerator) {
2673
+ collectNodeIds(node.numerator, ids);
2674
+ }
2675
+ if (node.denominator) {
2676
+ collectNodeIds(node.denominator, ids);
2677
+ }
2678
+ if (node.rootIndex) {
2679
+ collectNodeIds(node.rootIndex, ids);
2680
+ }
2681
+ if (node.radicand) {
2682
+ collectNodeIds(node.radicand, ids);
2683
+ }
2684
+ if (node.overExpr) {
2685
+ collectNodeIds(node.overExpr, ids);
2686
+ }
2687
+ if (node.underExpr) {
2688
+ collectNodeIds(node.underExpr, ids);
2689
+ }
2690
+ if (node.baseExpr) {
2691
+ collectNodeIds(node.baseExpr, ids);
2692
+ }
2693
+ if (node.matrixRows) {
2694
+ for (const row of node.matrixRows) {
2695
+ for (const cell of row) {
2696
+ collectNodeIds(cell, ids);
2697
+ }
2698
+ }
2699
+ }
2700
+ }
2701
+ }
2702
+ function buildInitialSyncMap(englishTree, arabicTree) {
2703
+ const englishIds = [];
2704
+ const arabicIds = [];
2705
+ collectNodeIds(englishTree, englishIds);
2706
+ collectNodeIds(arabicTree, arabicIds);
2707
+ const all = /* @__PURE__ */ new Set([...englishIds, ...arabicIds]);
2708
+ const sync = {};
2709
+ for (const nodeId of all) {
2710
+ sync[nodeId] = { expr: "synced" };
2711
+ }
2712
+ return sync;
2713
+ }
2714
+ function createEditorSession(englishTree, arabicTree, activeSide = "arabic") {
2715
+ return {
2716
+ englishTree,
2717
+ arabicTree,
2718
+ activeSide,
2719
+ splitLeafTyping: false,
2720
+ forceSplitNextLeaf: false,
2721
+ arabicReverseNumberTyping: true,
2722
+ currentCharacterFont: "default",
2723
+ currentCharacterWrapper: null,
2724
+ currentDigitForm: "western",
2725
+ caret: {
2726
+ chainId: englishTree.id,
2727
+ index: 0
2728
+ },
2729
+ selection: null,
2730
+ selectedNodeId: null,
2731
+ selectedStructureNodeId: null,
2732
+ sync: buildInitialSyncMap(englishTree, arabicTree),
2733
+ debugLog: []
2734
+ };
2735
+ }
1837
2736
 
1838
2737
  // src/editor/characterFonts.ts
1839
2738
  var CHARACTER_FONT_SPECS = [
@@ -1899,6 +2798,344 @@ var CHARACTER_FONT_OPTIONS = CHARACTER_FONT_SPECS.map(({ id, label }) => ({ id,
1899
2798
  var NON_DEFAULT_CHARACTER_FONT_SPECS = CHARACTER_FONT_SPECS.filter(
1900
2799
  (font) => font.id !== "default" && typeof font.macro === "string"
1901
2800
  );
2801
+ function characterFontSpec(fontId) {
2802
+ return CHARACTER_FONT_SPECS.find((font) => font.id === fontId) ?? CHARACTER_FONT_SPECS[0];
2803
+ }
2804
+
2805
+ // src/editor/divideOperator.ts
2806
+ var DIVIDE_OPERATOR_EN = "/";
2807
+ var DIVIDE_OPERATOR_AR = "\\";
2808
+ var DIVIDE_OPERATOR_AR_LATEX = "\\backslash";
2809
+ function isDivideOperatorExpr(expr) {
2810
+ return expr === DIVIDE_OPERATOR_EN || expr === DIVIDE_OPERATOR_AR || expr === DIVIDE_OPERATOR_AR_LATEX;
2811
+ }
2812
+ function renderDivideOperatorLatex(side) {
2813
+ return side === "arabic" ? "\\backslash" : DIVIDE_OPERATOR_EN;
2814
+ }
2815
+
2816
+ // src/editor/rawOperatorPresentation.ts
2817
+ var RTL_DIRECTIONAL_RAW_OPERATOR_SURFACE = {
2818
+ "<": ">",
2819
+ ">": "<"
2820
+ };
2821
+ function renderRawOperatorLatex(expr, side) {
2822
+ if (isDivideOperatorExpr(expr)) {
2823
+ return renderDivideOperatorLatex(side);
2824
+ }
2825
+ if (side === "arabic" && Object.prototype.hasOwnProperty.call(RTL_DIRECTIONAL_RAW_OPERATOR_SURFACE, expr)) {
2826
+ return `\\butexmirror{${expr}}`;
2827
+ }
2828
+ return expr;
2829
+ }
2830
+
2831
+ // src/editor/indexSequence.ts
2832
+ function isIndexComma(node) {
2833
+ return node.kind === "operator" && (node.expr === "," || node.expr === "\u060C");
2834
+ }
2835
+ function isValidIndexSequence(chain) {
2836
+ let count = 0;
2837
+ let afterComma = false;
2838
+ for (const node of chain.nodes) {
2839
+ if (node.superscript || node.subscript) return false;
2840
+ if (isIndexComma(node)) {
2841
+ if (count === 0 || afterComma) return false;
2842
+ afterComma = true;
2843
+ continue;
2844
+ }
2845
+ const isDigit = node.kind === "number" && /^[0-9]$/.test(node.expr);
2846
+ const identity = node.sourceLatex ?? node.expr;
2847
+ const isLetter = node.kind === "char" && (/^[A-Za-z]$/.test(identity) || Array.from(identity).length === 1 && /^\p{L}$/u.test(identity));
2848
+ if (!isDigit && !isLetter) return false;
2849
+ count += 1;
2850
+ afterComma = false;
2851
+ if (count > 64) return false;
2852
+ }
2853
+ return count >= 2 && !afterComma;
2854
+ }
2855
+
2856
+ // src/editor/render.ts
2857
+ function selectedDigitForm(options) {
2858
+ return options?.digitForm ?? "western";
2859
+ }
2860
+ function latinScripts(node, options) {
2861
+ let scripts = "";
2862
+ if (node.superscript) {
2863
+ scripts += `^{${renderChainEnglish(node.superscript, options)}}`;
2864
+ }
2865
+ if (node.subscript) {
2866
+ scripts += `_{${renderChainEnglish(node.subscript, options)}}`;
2867
+ }
2868
+ return scripts;
2869
+ }
2870
+ function optionalRootIndexEnglish(node, options) {
2871
+ if (!node.rootIndex) {
2872
+ return "";
2873
+ }
2874
+ const rendered = renderChainEnglish(node.rootIndex, options);
2875
+ return rendered === "" ? "" : `[${rendered}]`;
2876
+ }
2877
+ function optionalRootIndexArabic(node, options) {
2878
+ if (!node.rootIndex) {
2879
+ return "";
2880
+ }
2881
+ const rendered = renderChainArabic(node.rootIndex, options);
2882
+ return rendered === "" ? "" : `[${rendered}]`;
2883
+ }
2884
+ function arabicScripts(node, content, options) {
2885
+ const sup = node.superscript ? renderChainArabic(node.superscript, options) : "";
2886
+ const sub = node.subscript ? renderChainArabic(node.subscript, options) : "";
2887
+ if (sup !== "" || sub !== "") {
2888
+ return `\\prescript{${sup}}{${sub}}{${content}}`;
2889
+ }
2890
+ return content;
2891
+ }
2892
+ function renderMatrixRowsEnglish(node, options) {
2893
+ if (!node.matrixRows) {
2894
+ return "";
2895
+ }
2896
+ const envName = node.envName ?? node.matrixStyle;
2897
+ if (!envName) {
2898
+ return "";
2899
+ }
2900
+ const rows = node.matrixRows.map((row) => row.map((cell) => renderChainEnglish(cell, options)).join(" & "));
2901
+ if (envName === "array") {
2902
+ const spec = (node.columnAlignments ?? []).slice(0, node.matrixRows[0]?.length ?? 0).join("");
2903
+ return `\\begin{array}{${spec || "c"}}${rows.join(" \\\\\n")}\\end{array}`;
2904
+ }
2905
+ return `\\begin{${envName}}${rows.join(" \\\\\n")}\\end{${envName}}`;
2906
+ }
2907
+ function reverseAlignmentForArabic(alignment) {
2908
+ if (alignment === "l") {
2909
+ return "r";
2910
+ }
2911
+ if (alignment === "r") {
2912
+ return "l";
2913
+ }
2914
+ return "c";
2915
+ }
2916
+ function renderMatrixRowsArabic(node, options) {
2917
+ if (!node.matrixRows) {
2918
+ return "";
2919
+ }
2920
+ const envName = node.envName ?? node.matrixStyle;
2921
+ if (!envName) {
2922
+ return "";
2923
+ }
2924
+ const rows = node.matrixRows.map(
2925
+ (row) => row.slice().reverse().map((cell) => renderChainArabic(cell, options)).join(" & ")
2926
+ );
2927
+ if (envName === "array") {
2928
+ const spec = (node.columnAlignments ?? []).slice(0, node.matrixRows[0]?.length ?? 0).reverse().map(reverseAlignmentForArabic).join("");
2929
+ return `\\begin{array}{${spec || "c"}}${rows.join(" \\\\\n")}\\end{array}`;
2930
+ }
2931
+ if (envName === "cases" && options?.casesPresentation) {
2932
+ return `\\left.\\begin{array}{rl}${rows.join(" \\\\\n")}\\end{array}\\right\\}`;
2933
+ }
2934
+ return `\\begin{${envName}}${rows.join(" \\\\\n")}\\end{${envName}}`;
2935
+ }
2936
+ function renderAccentEnglish(command, accent, base, options) {
2937
+ const baseTex = base ? renderChainEnglish(base, options) : "";
2938
+ const accentTex = accent ? renderChainEnglish(accent, options) : "";
2939
+ if (accentTex === "") {
2940
+ return baseTex;
2941
+ }
2942
+ return `\\${command}{${accentTex}}{${baseTex}}`;
2943
+ }
2944
+ function renderAccentArabic(command, accent, base, options) {
2945
+ const baseTex = base ? renderChainArabic(base, options) : "";
2946
+ const accentTex = accent ? renderChainArabic(accent, options) : "";
2947
+ if (accentTex === "") {
2948
+ return baseTex;
2949
+ }
2950
+ return `\\${command}{${accentTex}}{${baseTex}}`;
2951
+ }
2952
+ function escapeText(s) {
2953
+ return s.replace(/\\/g, "\\textbackslash{}").replace(/[{}]/g, "\\$&");
2954
+ }
2955
+ function escapeAtomicLiteral(text) {
2956
+ const unescaped = text.replace(/\\([%_&#{}$])/g, "$1");
2957
+ return escapeText(unescaped).replace(/[%_&#$]/g, "\\$&");
2958
+ }
2959
+ function renderCharContent(node, options) {
2960
+ const expr = formatDigits(node.expr, selectedDigitForm(options));
2961
+ const font = node.characterFont ?? "default";
2962
+ const macro = characterFontSpec(font).macro;
2963
+ if (macro) {
2964
+ return `${macro}{${escapeText(expr)}}`;
2965
+ }
2966
+ return expr;
2967
+ }
2968
+ function renderNodeEnglish(node, options) {
2969
+ if (node.kind === "delimiter" && node.innerExpr) {
2970
+ return `${node.leftDelimExpr} ${renderChainEnglish(node.innerExpr, options)}${node.rightDelimExpr}${latinScripts(node, options)}`;
2971
+ }
2972
+ if (node.kind === "boxed" && node.innerExpr) {
2973
+ const body = `\\boxed{${renderChainEnglish(node.innerExpr, options)}}`;
2974
+ return `${body}${latinScripts(node, options)}`;
2975
+ }
2976
+ if (node.kind === "frac" && node.numerator && node.denominator) {
2977
+ const body = `\\frac{${renderChainEnglish(node.numerator, options)}}{${renderChainEnglish(node.denominator, options)}}`;
2978
+ return `${body}${latinScripts(node, options)}`;
2979
+ }
2980
+ if (node.kind === "sqrt" && node.radicand) {
2981
+ const body = `\\sqrt${optionalRootIndexEnglish(node, options)}{${renderChainEnglish(node.radicand, options)}}`;
2982
+ return `${body}${latinScripts(node, options)}`;
2983
+ }
2984
+ if (node.kind === "overset" && node.baseExpr) {
2985
+ const body = renderAccentEnglish("overset", node.overExpr, node.baseExpr, options);
2986
+ return `${body}${latinScripts(node, options)}`;
2987
+ }
2988
+ if (node.kind === "underset" && node.baseExpr) {
2989
+ const body = renderAccentEnglish("underset", node.underExpr, node.baseExpr, options);
2990
+ return `${body}${latinScripts(node, options)}`;
2991
+ }
2992
+ if (node.kind === "accent" && node.baseExpr) {
2993
+ const cmd = accentCommandSpec(node.expr)?.englishTex ?? `\\${node.expr}`;
2994
+ const body = `${cmd}{${renderChainEnglish(node.baseExpr, options)}}`;
2995
+ return `${body}${latinScripts(node, options)}`;
2996
+ }
2997
+ if (node.kind === "env") {
2998
+ return `${renderMatrixRowsEnglish(node, options)}${latinScripts(node, options)}`;
2999
+ }
3000
+ if (node.kind === "atomicCommand") {
3001
+ const body = atomicCommandSpec(node.expr)?.englishTex ?? node.expr;
3002
+ return `${body}${latinScripts(node, options)}`;
3003
+ }
3004
+ if (node.kind === "atomicOperatorCommand") {
3005
+ const body = node.sourceLatex === "\\le" || node.sourceLatex === "\\ge" ? node.sourceLatex : atomicOperatorCommandSpec(node.expr)?.Tex ?? node.expr;
3006
+ return `${body}${latinScripts(node, options)}`;
3007
+ }
3008
+ if (node.kind === "standardCommand") {
3009
+ return `${node.expr}${latinScripts(node, options)}`;
3010
+ }
3011
+ if (node.kind === "char") {
3012
+ if (node.sourceLatex) {
3013
+ if (node.wrapperCommand === "\\boldarabic" || node.wrapperCommand === "\\mathbf") {
3014
+ const boldSource = node.sourceLatex.startsWith("\\mathbf{") ? node.sourceLatex : `\\mathbf{${node.sourceLatex}}`;
3015
+ return `${boldSource}${latinScripts(node, options)}`;
3016
+ }
3017
+ return `${node.sourceLatex}${latinScripts(node, options)}`;
3018
+ }
3019
+ if (node.wrapperCommand) {
3020
+ const expr = formatDigits(node.expr, selectedDigitForm(options));
3021
+ const wrapper = node.wrapperCommand === "\\boldarabic" ? "\\mathbf" : node.wrapperCommand;
3022
+ const escaped = wrapper === "\\operatorname" || wrapper === "\\text" ? escapeAtomicLiteral(expr) : escapeText(expr);
3023
+ return `${wrapper}{${escaped}}${latinScripts(node, options)}`;
3024
+ }
3025
+ return `${renderCharContent(node, options)}${latinScripts(node, options)}`;
3026
+ }
3027
+ if (node.kind === "operator") {
3028
+ return `${renderRawOperatorLatex(node.expr, "english")}${latinScripts(node, options)}`;
3029
+ }
3030
+ return `${formatDigits(node.expr, selectedDigitForm(options))}${latinScripts(node, options)}`;
3031
+ }
3032
+ function renderNodeArabic(node, options) {
3033
+ if (node.kind === "delimiter" && node.innerExpr) {
3034
+ const content = `${node.leftDelimExpr}${renderChainArabic(node.innerExpr, options)}${node.rightDelimExpr}`;
3035
+ return arabicScripts(node, content, options);
3036
+ }
3037
+ if (node.kind === "boxed" && node.innerExpr) {
3038
+ const content = `\\boxed{${renderChainArabic(node.innerExpr, options)}}`;
3039
+ return arabicScripts(node, content, options);
3040
+ }
3041
+ if (node.kind === "frac" && node.numerator && node.denominator) {
3042
+ const content = `\\frac{${renderChainArabic(node.numerator, options)}}{${renderChainArabic(node.denominator, options)}}`;
3043
+ return arabicScripts(node, content, options);
3044
+ }
3045
+ if (node.kind === "sqrt" && node.radicand) {
3046
+ const content = `\\arsqrt${optionalRootIndexArabic(node, options)}{${renderChainArabic(node.radicand, options)}}`;
3047
+ return arabicScripts(node, content, options);
3048
+ }
3049
+ if (node.kind === "overset" && node.baseExpr) {
3050
+ const content = renderAccentArabic("overset", node.overExpr, node.baseExpr, options);
3051
+ return arabicScripts(node, content, options);
3052
+ }
3053
+ if (node.kind === "underset" && node.baseExpr) {
3054
+ const content = renderAccentArabic("underset", node.underExpr, node.baseExpr, options);
3055
+ return arabicScripts(node, content, options);
3056
+ }
3057
+ if (node.kind === "accent" && node.baseExpr) {
3058
+ const cmd = accentCommandSpec(node.expr)?.arabicTex ?? `\\${node.expr}`;
3059
+ const content = `${cmd}{${renderChainArabic(node.baseExpr, options)}}`;
3060
+ return arabicScripts(node, content, options);
3061
+ }
3062
+ if (node.kind === "env") {
3063
+ return arabicScripts(node, renderMatrixRowsArabic(node, options), options);
3064
+ }
3065
+ if (node.kind === "atomicCommand") {
3066
+ const spec = atomicCommandSpec(node.expr);
3067
+ const content = spec?.arabicRenderTex ?? spec?.arabicTex ?? node.expr;
3068
+ return arabicScripts(node, content, options);
3069
+ }
3070
+ if (node.kind === "atomicOperatorCommand") {
3071
+ const spec = atomicOperatorCommandSpec(node.expr);
3072
+ const tex = spec?.Tex ?? node.expr;
3073
+ const content = spec?.mirror ? `\\butexmirror{${tex}}` : tex;
3074
+ return arabicScripts(node, content, options);
3075
+ }
3076
+ if (node.kind === "standardCommand") {
3077
+ return arabicScripts(node, node.expr, options);
3078
+ }
3079
+ if (node.kind === "char") {
3080
+ const expr = formatDigits(node.expr, selectedDigitForm(options));
3081
+ const content = renderCharContent(node, options);
3082
+ if (node.wrapperCommand) {
3083
+ const wrapper = node.wrapperCommand === "\\mathbf" ? "\\boldarabic" : node.wrapperCommand;
3084
+ const literal = wrapper === "\\operatorname" || wrapper === "\\text" ? escapeAtomicLiteral(expr) : content;
3085
+ return arabicScripts(node, `${wrapper}{${literal}}`, options);
3086
+ }
3087
+ return arabicScripts(node, (node.characterFont ?? "default") === "default" ? `\\text{${escapeText(expr)}}` : content, options);
3088
+ }
3089
+ if (node.kind === "operator") {
3090
+ return arabicScripts(node, renderRawOperatorLatex(node.expr, "arabic"), options);
3091
+ }
3092
+ return arabicScripts(node, formatDigits(node.expr, selectedDigitForm(options)), options);
3093
+ }
3094
+ function renderChainEnglish(chain, options) {
3095
+ if (chain.indexSequence && isValidIndexSequence(chain)) {
3096
+ const atoms = chain.nodes.map((node) => isIndexComma(node) ? "," : renderNodeEnglish(node, options));
3097
+ return "\\mathnormal{" + atoms.join("") + "}";
3098
+ }
3099
+ return chain.nodes.map((node) => renderNodeEnglish(node, options)).join(" ");
3100
+ }
3101
+ function renderChainArabic(chain, options) {
3102
+ const rendered = chain.nodes.slice().reverse().map((node) => renderNodeArabic(node, options));
3103
+ if (chain.indexSequence && isValidIndexSequence(chain)) {
3104
+ return "\\mathnormal{" + rendered.join("\\,") + "}";
3105
+ }
3106
+ return rendered.join(" ");
3107
+ }
3108
+ function renderEnglishLatexFromSession(session) {
3109
+ return renderChainEnglish(session.englishTree, { digitForm: session.currentDigitForm ?? "western" });
3110
+ }
3111
+ function renderArabicLatexFromSession(session) {
3112
+ return renderChainArabic(session.arabicTree, { digitForm: session.currentDigitForm ?? "western" });
3113
+ }
3114
+ function renderArabicPreviewLatexFromSession(session) {
3115
+ return renderChainArabic(session.arabicTree, { digitForm: session.currentDigitForm ?? "western", casesPresentation: true });
3116
+ }
3117
+
3118
+ // src/editor/state.ts
3119
+ function appendDebug(session, command, note) {
3120
+ const entry = {
3121
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3122
+ command,
3123
+ activeSide: session.activeSide,
3124
+ englishLatex: renderEnglishLatexFromSession(session),
3125
+ arabicLatex: renderArabicLatexFromSession(session),
3126
+ renderOk: true,
3127
+ renderError: null,
3128
+ note
3129
+ };
3130
+ const nextLog = session.debugLog.concat(entry);
3131
+ session.debugLog = nextLog.slice(-120);
3132
+ }
3133
+ function setCurrentDigitForm(session, digitForm) {
3134
+ const next = cloneEditorSession(session);
3135
+ next.currentDigitForm = digitForm;
3136
+ appendDebug(next, "setCurrentDigitForm", digitForm);
3137
+ return next;
3138
+ }
1902
3139
 
1903
3140
  // src/editor/display/delimiter.ts
1904
3141
  var DELIMITER_CSS = `
@@ -2670,8 +3907,63 @@ var WRAPPER_SPECS = [
2670
3907
  ]),
2671
3908
  { prefix: "\\text" }
2672
3909
  ];
2673
-
2674
- // src/shared/math-document/mathEditorAdapter.ts
3910
+ function readBracedArg(source, openBraceIndex) {
3911
+ if (source[openBraceIndex] !== "{") {
3912
+ return null;
3913
+ }
3914
+ let depth = 0;
3915
+ for (let index = openBraceIndex; index < source.length; index += 1) {
3916
+ const char = source[index];
3917
+ if (char === "{") {
3918
+ depth += 1;
3919
+ } else if (char === "}") {
3920
+ depth -= 1;
3921
+ if (depth === 0) {
3922
+ return { inner: source.slice(openBraceIndex + 1, index), end: index + 1 };
3923
+ }
3924
+ }
3925
+ }
3926
+ return null;
3927
+ }
3928
+ function peelWrapper(source) {
3929
+ for (const wrapper of WRAPPER_SPECS) {
3930
+ if (!source.startsWith(wrapper.prefix)) {
3931
+ continue;
3932
+ }
3933
+ const braced = readBracedArg(source, wrapper.prefix.length);
3934
+ if (!braced || braced.end !== source.length) {
3935
+ continue;
3936
+ }
3937
+ return { inner: braced.inner, font: wrapper.font };
3938
+ }
3939
+ return null;
3940
+ }
3941
+ function normalizeCharImportExpr(expr) {
3942
+ const original = expr;
3943
+ let current = expr;
3944
+ let characterFont = "default";
3945
+ let changed = false;
3946
+ while (true) {
3947
+ const peeled = peelWrapper(current);
3948
+ if (!peeled) {
3949
+ break;
3950
+ }
3951
+ current = peeled.inner;
3952
+ if (peeled.font) {
3953
+ characterFont = peeled.font;
3954
+ }
3955
+ changed = true;
3956
+ }
3957
+ if (!changed) {
3958
+ return { expr: original, characterFont: "default" };
3959
+ }
3960
+ if (current.includes("\\")) {
3961
+ return { expr: original, characterFont: "default" };
3962
+ }
3963
+ return { expr: current, characterFont };
3964
+ }
3965
+
3966
+ // src/shared/math-document/mathEditorAdapter.ts
2675
3967
  var COMMAND_FONT_MAP = Object.fromEntries([
2676
3968
  ["\\text", "infer"],
2677
3969
  ...NON_DEFAULT_CHARACTER_FONT_SPECS.flatMap((font) => [
@@ -2682,6 +3974,535 @@ var COMMAND_FONT_MAP = Object.fromEntries([
2682
3974
  var CHAR_FONT_EXPORT_TEX = Object.fromEntries(
2683
3975
  NON_DEFAULT_CHARACTER_FONT_SPECS.map((font) => [font.id, font.macro])
2684
3976
  );
3977
+ function commandIdForTex(tex) {
3978
+ for (const spec of Object.values(ATOMIC_COMMANDS)) {
3979
+ const renderTex = spec.arabicRenderTex;
3980
+ if (spec.englishTex === tex || spec.arabicTex === tex || renderTex === tex) {
3981
+ return spec.id;
3982
+ }
3983
+ }
3984
+ return null;
3985
+ }
3986
+ function operatorCommandIdForTex(tex) {
3987
+ const normalized = tex === "\\le" ? "\\leq" : tex === "\\ge" ? "\\geq" : tex;
3988
+ for (const spec of Object.values(ATOMIC_OPERATOR_COMMANDS)) {
3989
+ if (spec.Tex === normalized) {
3990
+ return spec.id;
3991
+ }
3992
+ }
3993
+ return null;
3994
+ }
3995
+ function cloneChainWithFreshIds(chain) {
3996
+ return structuredClone(chain);
3997
+ }
3998
+ function attachScripts(astNode, editorNode) {
3999
+ if (astNode.sourceLatex) {
4000
+ editorNode.sourceLatex = astNode.sourceLatex;
4001
+ }
4002
+ if (astNode.superscript) {
4003
+ const sup = chainToEditorChain(astNode.superscript, true);
4004
+ if (!sup.editable) {
4005
+ return sup;
4006
+ }
4007
+ editorNode.superscript = sup.chain;
4008
+ }
4009
+ if (astNode.subscript) {
4010
+ const sub = chainToEditorChain(astNode.subscript, true);
4011
+ if (!sub.editable) {
4012
+ return sub;
4013
+ }
4014
+ editorNode.subscript = sub.chain;
4015
+ }
4016
+ return null;
4017
+ }
4018
+ var MATRIX_ENV_NAMES = /* @__PURE__ */ new Set(["matrix", "pmatrix", "bmatrix", "Bmatrix", "vmatrix", "Vmatrix"]);
4019
+ function isGridEnvName(value) {
4020
+ return MATRIX_ENV_NAMES.has(value) || value === "array" || value === "aligned" || value === "cases";
4021
+ }
4022
+ function isMatrixEnvName(value) {
4023
+ return MATRIX_ENV_NAMES.has(value);
4024
+ }
4025
+ function parseEnvOpening(opening) {
4026
+ const match = /^\\begin\{([^}]+)\}(?:\{([lcr]+)\})?$/.exec(opening);
4027
+ if (!match) {
4028
+ return null;
4029
+ }
4030
+ const envName = match[1] ?? "";
4031
+ if (!isGridEnvName(envName)) {
4032
+ return null;
4033
+ }
4034
+ if (envName === "array") {
4035
+ const spec = match[2] ?? "c";
4036
+ return {
4037
+ envName,
4038
+ alignments: spec.split("").map((alignment) => alignment)
4039
+ };
4040
+ }
4041
+ return { envName };
4042
+ }
4043
+ function splitEnvLine(line) {
4044
+ const cells = [];
4045
+ let current = [];
4046
+ for (const node of line.chain) {
4047
+ if (node instanceof OperatorNode && node.expr === "&") {
4048
+ cells.push(new ChainNode(current));
4049
+ current = [];
4050
+ } else {
4051
+ current.push(node);
4052
+ }
4053
+ }
4054
+ cells.push(new ChainNode(current));
4055
+ return cells;
4056
+ }
4057
+ function envToEditorNode(node) {
4058
+ const parsed = parseEnvOpening(node.opening);
4059
+ if (!parsed) {
4060
+ return { editable: false, reason: `\u0628\u064A\u0626\u0629 \u0631\u064A\u0627\u0636\u064A\u0629 \u063A\u064A\u0631 \u0645\u062F\u0639\u0648\u0645\u0629 \u062D\u0627\u0644\u064A\u0627: ${node.opening}` };
4061
+ }
4062
+ const expectedClosing = `\\end{${parsed.envName}}`;
4063
+ if (node.closing !== expectedClosing) {
4064
+ return { editable: false, reason: `\u0625\u063A\u0644\u0627\u0642 \u0628\u064A\u0626\u0629 \u0631\u064A\u0627\u0636\u064A\u0629 \u063A\u064A\u0631 \u0645\u062F\u0639\u0648\u0645 \u062D\u0627\u0644\u064A\u0627: ${node.closing}` };
4065
+ }
4066
+ const rowCells = node.lines.map(splitEnvLine);
4067
+ if (parsed.envName === "cases" && (rowCells.length === 0 || rowCells.length > 12 || rowCells.some((row) => row.length !== 2))) {
4068
+ return { editable: false, reason: "\u0628\u064A\u0626\u0629 cases \u062A\u062A\u0637\u0644\u0628 \u062A\u0639\u0628\u064A\u0631\u0627 \u0648\u0634\u0631\u0637\u0627 \u0641\u064A \u0643\u0644 \u0635\u0641 (\u0639\u0645\u0648\u062F\u0627\u0646)" };
4069
+ }
4070
+ const rows = Math.max(1, rowCells.length);
4071
+ const columns = Math.max(1, ...rowCells.map((row) => row.length));
4072
+ const env = createGridEnvNode(parsed.envName, rows, columns, parsed.alignments);
4073
+ for (let rowIndex = 0; rowIndex < rows; rowIndex += 1) {
4074
+ const row = rowCells[rowIndex] ?? [];
4075
+ for (let columnIndex = 0; columnIndex < columns; columnIndex += 1) {
4076
+ const cell = chainToEditorChain(row[columnIndex] ?? new ChainNode());
4077
+ if (!cell.editable) {
4078
+ return cell;
4079
+ }
4080
+ env.matrixRows[rowIndex][columnIndex] = cell.chain;
4081
+ }
4082
+ }
4083
+ if (parsed.envName === "array") {
4084
+ env.columnAlignments = Array.from(
4085
+ { length: columns },
4086
+ (_, index) => parsed.alignments?.[index] ?? "c"
4087
+ );
4088
+ }
4089
+ if (isMatrixEnvName(parsed.envName)) {
4090
+ env.matrixStyle = parsed.envName;
4091
+ }
4092
+ const scripts = attachScripts(node, env);
4093
+ return scripts ?? { editable: true, node: env };
4094
+ }
4095
+ function charFromTextLikeCommand(node) {
4096
+ const commandFont = COMMAND_FONT_MAP[node.name];
4097
+ if (commandFont === void 0) {
4098
+ return null;
4099
+ }
4100
+ if (node.optionalArgs.length > 0 || node.mandatoryArgs.length !== 1) {
4101
+ return null;
4102
+ }
4103
+ const arg = node.mandatoryArgs[0];
4104
+ if (arg.chain.length !== 1) {
4105
+ return null;
4106
+ }
4107
+ const child = arg.chain[0];
4108
+ if (child instanceof CommandNode) {
4109
+ const nested = charFromTextLikeCommand(child);
4110
+ if (!nested?.editable) {
4111
+ return null;
4112
+ }
4113
+ if (commandFont !== "infer") {
4114
+ nested.node.characterFont = commandFont;
4115
+ }
4116
+ const scripts2 = attachScripts(node, nested.node);
4117
+ return scripts2 ?? nested;
4118
+ }
4119
+ if (!(child instanceof CharNode)) {
4120
+ return null;
4121
+ }
4122
+ const normalized = normalizeCharImportExpr(child.expr);
4123
+ const characterFont = commandFont === "infer" ? normalized.characterFont : commandFont;
4124
+ const editorNode = createEditorNode("char", normalized.expr);
4125
+ if (characterFont !== "default") {
4126
+ editorNode.characterFont = characterFont;
4127
+ }
4128
+ const scripts = attachScripts(node, editorNode);
4129
+ return scripts ?? { editable: true, node: editorNode };
4130
+ }
4131
+ function singleCommandChar(node) {
4132
+ if (node.optionalArgs.length > 0 || node.mandatoryArgs.length !== 1) {
4133
+ return null;
4134
+ }
4135
+ const arg = node.mandatoryArgs[0];
4136
+ if (arg.chain.length !== 1 || !(arg.chain[0] instanceof CharNode)) {
4137
+ return null;
4138
+ }
4139
+ return arg.chain[0];
4140
+ }
4141
+ function wrappedAtomicCommandId(node) {
4142
+ if (node.name !== "\\mathbb" && node.name !== "\\mathrm") {
4143
+ return null;
4144
+ }
4145
+ const child = singleCommandChar(node);
4146
+ if (!child) {
4147
+ return null;
4148
+ }
4149
+ return commandIdForTex(`${node.name}{${child.expr}}`);
4150
+ }
4151
+ function editableWrapperCommand(node) {
4152
+ if (node.name !== "\\mathtt" && node.name !== "\\operatorname" && node.name !== "\\text" && node.name !== "\\mathsf" && node.name !== "\\unit" && node.name !== "\\mathbf" && node.name !== "\\boldarabic") {
4153
+ return null;
4154
+ }
4155
+ if (node.name === "\\text" && node.sourceLatex && !node.sourceLatex.startsWith("\\text{")) {
4156
+ return null;
4157
+ }
4158
+ const child = singleCommandChar(node);
4159
+ if (node.name === "\\text" && child?.sourceLatex && !node.sourceLatex) return null;
4160
+ let editorNode;
4161
+ if (child) {
4162
+ const normalized = normalizeCharImportExpr(child.expr);
4163
+ editorNode = createEditorNode("char", normalized.expr);
4164
+ if (child.sourceLatex) editorNode.sourceLatex = child.sourceLatex;
4165
+ if (normalized.characterFont !== "default") {
4166
+ editorNode.characterFont = normalized.characterFont;
4167
+ }
4168
+ } else {
4169
+ if (node.optionalArgs.length || node.mandatoryArgs.length !== 1) return null;
4170
+ const nodes = node.mandatoryArgs[0]?.chain;
4171
+ if (!nodes || nodes.length !== 1 || !(nodes[0] instanceof CommandNode)) return null;
4172
+ const nested = charFromTextLikeCommand(nodes[0]);
4173
+ if (!nested?.editable) return null;
4174
+ editorNode = nested.node;
4175
+ }
4176
+ editorNode.wrapperCommand = node.name === "\\mathsf" ? "\\unit" : node.name;
4177
+ const scripts = attachScripts(node, editorNode);
4178
+ if (scripts) {
4179
+ return scripts;
4180
+ }
4181
+ if (!editorNode.sourceLatex && node.name === "\\mathsf" && child) {
4182
+ editorNode.sourceLatex = `\\mathsf{${child.expr}}`;
4183
+ }
4184
+ return { editable: true, node: editorNode };
4185
+ }
4186
+ function commandToEditorNode(node) {
4187
+ if (node.name === "\\frac" && node.mandatoryArgs.length >= 2) {
4188
+ const frac = createFracNode();
4189
+ const numerator = chainToEditorChain(node.mandatoryArgs[0]);
4190
+ const denominator = chainToEditorChain(node.mandatoryArgs[1]);
4191
+ if (!numerator.editable) {
4192
+ return numerator;
4193
+ }
4194
+ if (!denominator.editable) {
4195
+ return denominator;
4196
+ }
4197
+ frac.numerator = numerator.chain;
4198
+ frac.denominator = denominator.chain;
4199
+ const scripts = attachScripts(node, frac);
4200
+ if (scripts) {
4201
+ return scripts;
4202
+ }
4203
+ return { editable: true, node: frac };
4204
+ }
4205
+ if ((node.name === "\\sqrt" || node.name === "\\arabsqrt" || node.name === "\\arsqrt") && node.mandatoryArgs.length >= 1) {
4206
+ const sqrt = createSqrtNode();
4207
+ const radicand = chainToEditorChain(node.mandatoryArgs[0]);
4208
+ if (!radicand.editable) {
4209
+ return radicand;
4210
+ }
4211
+ sqrt.radicand = radicand.chain;
4212
+ if (node.optionalArgs[0]) {
4213
+ const rootIndex = chainToEditorChain(node.optionalArgs[0]);
4214
+ if (!rootIndex.editable) {
4215
+ return rootIndex;
4216
+ }
4217
+ sqrt.rootIndex = rootIndex.chain;
4218
+ }
4219
+ const scripts = attachScripts(node, sqrt);
4220
+ if (scripts) {
4221
+ return scripts;
4222
+ }
4223
+ return { editable: true, node: sqrt };
4224
+ }
4225
+ if (node.name === "\\boxed" && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 1) {
4226
+ const boxed = createBoxedNode();
4227
+ const inner = chainToEditorChain(node.mandatoryArgs[0]);
4228
+ if (!inner.editable) {
4229
+ return inner;
4230
+ }
4231
+ boxed.innerExpr = inner.chain;
4232
+ const scripts = attachScripts(node, boxed);
4233
+ return scripts ?? { editable: true, node: boxed };
4234
+ }
4235
+ if (node.name === "\\overset" && node.mandatoryArgs.length >= 2) {
4236
+ const overset = createOversetNode();
4237
+ const overExpr = chainToEditorChain(node.mandatoryArgs[0]);
4238
+ const baseExpr = chainToEditorChain(node.mandatoryArgs[1]);
4239
+ if (!overExpr.editable) {
4240
+ return overExpr;
4241
+ }
4242
+ if (!baseExpr.editable) {
4243
+ return baseExpr;
4244
+ }
4245
+ overset.overExpr = overExpr.chain;
4246
+ overset.baseExpr = baseExpr.chain;
4247
+ const scripts = attachScripts(node, overset);
4248
+ if (scripts) {
4249
+ return scripts;
4250
+ }
4251
+ return { editable: true, node: overset };
4252
+ }
4253
+ if (node.name === "\\underset" && node.mandatoryArgs.length >= 2) {
4254
+ const underset = createUndersetNode();
4255
+ const underExpr = chainToEditorChain(node.mandatoryArgs[0]);
4256
+ const baseExpr = chainToEditorChain(node.mandatoryArgs[1]);
4257
+ if (!underExpr.editable) {
4258
+ return underExpr;
4259
+ }
4260
+ if (!baseExpr.editable) {
4261
+ return baseExpr;
4262
+ }
4263
+ underset.underExpr = underExpr.chain;
4264
+ underset.baseExpr = baseExpr.chain;
4265
+ const scripts = attachScripts(node, underset);
4266
+ if (scripts) {
4267
+ return scripts;
4268
+ }
4269
+ return { editable: true, node: underset };
4270
+ }
4271
+ const accentId = accentCommandIdFromTex(node.name);
4272
+ if (accentId && node.mandatoryArgs.length >= 1) {
4273
+ const accent = createAccentNode(accentId);
4274
+ const baseExpr = chainToEditorChain(node.mandatoryArgs[0]);
4275
+ if (!baseExpr.editable) {
4276
+ return baseExpr;
4277
+ }
4278
+ accent.baseExpr = baseExpr.chain;
4279
+ const scripts = attachScripts(node, accent);
4280
+ if (scripts) {
4281
+ return scripts;
4282
+ }
4283
+ return { editable: true, node: accent };
4284
+ }
4285
+ const wrappedAtomicId = wrappedAtomicCommandId(node);
4286
+ if (wrappedAtomicId) {
4287
+ const atomic = createEditorNode("atomicCommand", wrappedAtomicId);
4288
+ const scripts = attachScripts(node, atomic);
4289
+ if (scripts) {
4290
+ return scripts;
4291
+ }
4292
+ return { editable: true, node: atomic };
4293
+ }
4294
+ const wrapper = editableWrapperCommand(node);
4295
+ if (wrapper) {
4296
+ return wrapper;
4297
+ }
4298
+ const atomicId = commandIdForTex(node.name);
4299
+ if (atomicId && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 0) {
4300
+ const atomic = createEditorNode("atomicCommand", atomicId);
4301
+ const scripts = attachScripts(node, atomic);
4302
+ if (scripts) {
4303
+ return scripts;
4304
+ }
4305
+ return { editable: true, node: atomic };
4306
+ }
4307
+ const operatorId = operatorCommandIdForTex(node.name);
4308
+ if (operatorId && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 0) {
4309
+ const atomicOperator = createEditorNode("atomicOperatorCommand", operatorId);
4310
+ if (node.name === "\\le" || node.name === "\\ge") atomicOperator.sourceLatex = node.name;
4311
+ const scripts = attachScripts(node, atomicOperator);
4312
+ if (scripts) {
4313
+ return scripts;
4314
+ }
4315
+ return { editable: true, node: atomicOperator };
4316
+ }
4317
+ if (isStandardCommandTex(node.name) && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 0) {
4318
+ const standard = createEditorNode("standardCommand", node.name);
4319
+ const scripts = attachScripts(node, standard);
4320
+ if (scripts) {
4321
+ return scripts;
4322
+ }
4323
+ return { editable: true, node: standard };
4324
+ }
4325
+ const textLike = charFromTextLikeCommand(node);
4326
+ if (textLike) {
4327
+ return textLike;
4328
+ }
4329
+ return { editable: false, reason: `\u0623\u0645\u0631 \u0631\u064A\u0627\u0636\u064A \u063A\u064A\u0631 \u0645\u062F\u0639\u0648\u0645 \u062D\u0627\u0644\u064A\u0627: ${node.name}` };
4330
+ }
4331
+ function astNodeToEditorNode(node) {
4332
+ if (node instanceof CharNode) {
4333
+ const normalized = normalizeCharImportExpr(node.expr);
4334
+ const editorNode = createEditorNode("char", normalized.expr);
4335
+ if (normalized.characterFont !== "default") {
4336
+ editorNode.characterFont = normalized.characterFont;
4337
+ }
4338
+ const scripts = attachScripts(node, editorNode);
4339
+ return scripts ?? { editable: true, node: editorNode };
4340
+ }
4341
+ if (node instanceof NumberNode) {
4342
+ const editorNode = createEditorNode("number", node.expr);
4343
+ const scripts = attachScripts(node, editorNode);
4344
+ return scripts ?? { editable: true, node: editorNode };
4345
+ }
4346
+ if (node instanceof OperatorNode) {
4347
+ return { editable: true, node: createEditorNode("operator", node.expr) };
4348
+ }
4349
+ if (node instanceof DelimiterNode) {
4350
+ const editorNode = createDelimiterNode(node.leftDelimExpr, node.rightDelimExpr);
4351
+ const inner = chainToEditorChain(node.innerExpr);
4352
+ if (!inner.editable) {
4353
+ return inner;
4354
+ }
4355
+ editorNode.innerExpr = inner.chain;
4356
+ const scripts = attachScripts(node, editorNode);
4357
+ return scripts ?? { editable: true, node: editorNode };
4358
+ }
4359
+ if (node instanceof CommandNode) {
4360
+ return commandToEditorNode(node);
4361
+ }
4362
+ if (node instanceof EnvNode) {
4363
+ return envToEditorNode(node);
4364
+ }
4365
+ return { editable: false, reason: `\u0639\u0642\u062F\u0629 \u0631\u064A\u0627\u0636\u064A\u0629 \u063A\u064A\u0631 \u0645\u062F\u0639\u0648\u0645\u0629 \u062D\u0627\u0644\u064A\u0627: ${node.nodeType}` };
4366
+ }
4367
+ var VERTICAL_DELIMITER_COMMAND_PAIRS = {
4368
+ "\\vert": "\\vert",
4369
+ "\\lvert": "\\rvert",
4370
+ "\\Vert": "\\Vert",
4371
+ "\\lVert": "\\rVert",
4372
+ "\\|": "\\|"
4373
+ };
4374
+ function isBareCommand(node, name) {
4375
+ return node instanceof CommandNode && node.name === name && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 0;
4376
+ }
4377
+ function normalizeVerticalDelimiterCommands(chain) {
4378
+ const normalized = [];
4379
+ for (let index = 0; index < chain.chain.length; index += 1) {
4380
+ const left = chain.chain[index];
4381
+ if (!(left instanceof CommandNode) || left.superscript || left.subscript) {
4382
+ normalized.push(left);
4383
+ continue;
4384
+ }
4385
+ const rightName = VERTICAL_DELIMITER_COMMAND_PAIRS[left.name];
4386
+ if (!rightName || left.optionalArgs.length > 0 || left.mandatoryArgs.length > 0) {
4387
+ normalized.push(left);
4388
+ continue;
4389
+ }
4390
+ let rightIndex = -1;
4391
+ for (let candidate = index + 1; candidate < chain.chain.length; candidate += 1) {
4392
+ if (isBareCommand(chain.chain[candidate], rightName)) {
4393
+ rightIndex = candidate;
4394
+ break;
4395
+ }
4396
+ }
4397
+ if (rightIndex < 0) {
4398
+ normalized.push(left);
4399
+ continue;
4400
+ }
4401
+ const right = chain.chain[rightIndex];
4402
+ const delimiter = new DelimiterNode(
4403
+ left.name,
4404
+ new ChainNode(chain.chain.slice(index + 1, rightIndex)),
4405
+ right.name
4406
+ );
4407
+ delimiter.superscript = right.superscript;
4408
+ delimiter.subscript = right.subscript;
4409
+ normalized.push(delimiter);
4410
+ index = rightIndex;
4411
+ }
4412
+ return new ChainNode(normalized);
4413
+ }
4414
+ function chainToEditorChain(chain, script = false) {
4415
+ if (script && chain.chain.length === 1) {
4416
+ const wrapper = chain.chain[0];
4417
+ if (wrapper instanceof CommandNode && wrapper.name === "\\mathnormal") {
4418
+ if (wrapper.optionalArgs.length || wrapper.mandatoryArgs.length !== 1) {
4419
+ return { editable: false, reason: "\u0635\u064A\u063A\u0629 \u0645\u062C\u0645\u0648\u0639\u0629 \u0627\u0644\u0641\u0647\u0627\u0631\u0633 \u063A\u064A\u0631 \u0645\u062F\u0639\u0648\u0645\u0629" };
4420
+ }
4421
+ const imported = chainToEditorChain(wrapper.mandatoryArgs[0]);
4422
+ if (!imported.editable) return imported;
4423
+ const atoms = [];
4424
+ for (const node of imported.chain.nodes) {
4425
+ if (node.kind === "number" && /^[0-9]{2,}$/.test(node.expr)) {
4426
+ atoms.push(...node.expr.split("").map((digit) => createEditorNode("number", digit)));
4427
+ } else if (node.kind === "char" && !node.sourceLatex && /^[A-Za-z]{2,}$/.test(node.expr)) {
4428
+ atoms.push(...node.expr.split("").map((letter) => createEditorNode("char", letter)));
4429
+ } else {
4430
+ atoms.push(node);
4431
+ }
4432
+ }
4433
+ imported.chain.nodes = atoms;
4434
+ if (!isValidIndexSequence(imported.chain)) {
4435
+ return { editable: false, reason: "\u0645\u062D\u062A\u0648\u0649 \u0645\u062C\u0645\u0648\u0639\u0629 \u0627\u0644\u0641\u0647\u0627\u0631\u0633 \u063A\u064A\u0631 \u0645\u062F\u0639\u0648\u0645" };
4436
+ }
4437
+ imported.chain.indexSequence = true;
4438
+ return imported;
4439
+ }
4440
+ }
4441
+ const nodes = [];
4442
+ for (const astNode of normalizeVerticalDelimiterCommands(chain).chain) {
4443
+ const converted = astNodeToEditorNode(astNode);
4444
+ if (!converted.editable) {
4445
+ return converted;
4446
+ }
4447
+ nodes.push(converted.node);
4448
+ }
4449
+ return { editable: true, chain: createEditorChain(nodes) };
4450
+ }
4451
+ function mathObjectToEditorSession(math) {
4452
+ if (math.lines.length !== 1) {
4453
+ return { editable: false, reason: "\u062A\u062D\u0631\u064A\u0631 \u0627\u0644\u0645\u0639\u0627\u062F\u0644\u0627\u062A \u0645\u062A\u0639\u062F\u062F\u0629 \u0627\u0644\u0623\u0633\u0637\u0631 \u062F\u0627\u062E\u0644 \u0627\u0644\u0645\u0633\u062A\u0646\u062F \u063A\u064A\u0631 \u0645\u062F\u0639\u0648\u0645 \u0628\u0639\u062F" };
4454
+ }
4455
+ const english = chainToEditorChain(math.lines[0]);
4456
+ if (!english.editable) {
4457
+ return english;
4458
+ }
4459
+ const arabic = cloneChainWithFreshIds(english.chain);
4460
+ const session = createEditorSession(english.chain, arabic, "english");
4461
+ session.sync = buildInitialSyncMap(session.englishTree, session.arabicTree);
4462
+ return { editable: true, session: cloneEditorSession(session) };
4463
+ }
4464
+
4465
+ // src/document/mathBridge.ts
4466
+ function mathTokenToEditorSession(math, side = "arabic") {
4467
+ if (!math) {
4468
+ return { editable: false, reason: "\u0647\u0630\u0647 \u0627\u0644\u0645\u0639\u0627\u062F\u0644\u0629 \u0645\u062D\u0641\u0648\u0638\u0629 \u0643\u0646\u0635 \u062E\u0627\u0645 \u0641\u0642\u0637 \u062D\u0627\u0644\u064A\u0627" };
4469
+ }
4470
+ const result = mathObjectToEditorSession(math);
4471
+ if (!result.editable) {
4472
+ return result;
4473
+ }
4474
+ result.session.activeSide = side;
4475
+ result.session.sync = buildInitialSyncMap(result.session.englishTree, result.session.arabicTree);
4476
+ return result;
4477
+ }
4478
+ function mathSourceFromSession(session, side, opening = "$", closing = "$", presentation = false) {
4479
+ const inner = side === "english" ? renderEnglishLatexFromSession(session) : presentation ? renderArabicPreviewLatexFromSession(session) : renderArabicLatexFromSession(session);
4480
+ if (opening === "$" || opening === "\\(") {
4481
+ return opening + inner + closing;
4482
+ }
4483
+ if (opening === "$$" || opening === "\\[") {
4484
+ return `${opening}
4485
+ ${inner}
4486
+ ${closing}`;
4487
+ }
4488
+ return `${opening}
4489
+ ${inner}
4490
+ ${closing}`;
4491
+ }
4492
+ function mathTokenSourceForSide(token, side, digitForm, presentation = false) {
4493
+ if (!token.math || token.sourceOwner === "raw") {
4494
+ return token.source;
4495
+ }
4496
+ if (!presentation && token.sourceSide === side && digitForm === void 0) {
4497
+ return token.source;
4498
+ }
4499
+ const result = mathTokenToEditorSession(token.math, side);
4500
+ if (!result.editable) {
4501
+ return token.source;
4502
+ }
4503
+ const session = digitForm === void 0 ? result.session : setCurrentDigitForm(result.session, digitForm);
4504
+ return mathSourceFromSession(session, side, token.opening, token.closing, presentation);
4505
+ }
2685
4506
 
2686
4507
  // src/document/keys.ts
2687
4508
  var DOCUMENT_KEY_PATTERN = /^[\p{L}\p{M}\p{Nd}:._-]+$/u;
@@ -2806,6 +4627,471 @@ function getDocumentReferenceIndex(document2) {
2806
4627
  };
2807
4628
  }
2808
4629
 
4630
+ // src/document/arabicPreamble.ts
4631
+ function fontOptions(digitsMapping, includeScript = true) {
4632
+ const parts = [];
4633
+ if (includeScript) {
4634
+ parts.push("Script=Arabic");
4635
+ }
4636
+ if (digitsMapping !== "digits") {
4637
+ parts.push(`Mapping=${digitsMapping}`);
4638
+ }
4639
+ if (parts.length === 0) {
4640
+ return "";
4641
+ }
4642
+ return `[${parts.join(",")}]`;
4643
+ }
4644
+ function arabicXeLatexPreamblePkg(twocolumn = false) {
4645
+ const classOptions = twocolumn ? "12pt,a4paper,notitlepage,twocolumn" : "12pt,a4paper,notitlepage";
4646
+ return `
4647
+ \\documentclass[${classOptions}]{article}
4648
+ ` + String.raw`\usepackage{amsmath,amsfonts,amssymb,mathrsfs,tikz,fancyhdr, mathtools}
4649
+ \usepackage{fontspec} % For loading OpenType fonts
4650
+ \usepackage{unicode-math} % For setting the math font
4651
+ \usepackage{polyglossia} % For Arabic support
4652
+ \usepackage{array}
4653
+ \usepackage{cancel}
4654
+ \usepackage{bidi}
4655
+ \usepackage{multirow}
4656
+ \usepackage{booktabs}
4657
+ \usepackage{graphicx} % For \reflectbox
4658
+ \usepackage{xcolor}
4659
+ \usepackage{tikz}
4660
+ \usepackage{tcolorbox} % For tcolorbox environment
4661
+ \usepackage{textcomp} % For \textrightarrow command
4662
+ \usepackage{url}
4663
+
4664
+
4665
+ % visit : https://www.symbolcopy.com/punctuation-symbol.html
4666
+ % for inversed punctuation
4667
+
4668
+ % save inverted comma for use - copy paste -> ،
4669
+ % save back tick for use - copy paste -> ` + "`";
4670
+ }
4671
+ function arabicXeLatexPreambleFont(digitsMapping = "arabicdigits") {
4672
+ const customFonts = NON_DEFAULT_CHARACTER_FONT_SPECS.filter((font) => font.latexFontCommand && font.latexFontFamily).map((font) => `\\newfontfamily${font.latexFontCommand}${fontOptions(digitsMapping)}{${font.latexFontFamily}}`).join("\n");
4673
+ const mathFontOptions = fontOptions(digitsMapping, false);
4674
+ return `
4675
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4676
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4677
+ % Persian digits: Mapping=farsidigits
4678
+ % Arabic-Indic digits: Mapping=arabicdigits
4679
+ % Western digits: omit Mapping entirely
4680
+ \\setdefaultlanguage[calendar=gregorian]{arabic} % from polyglossia
4681
+ \\setmainfont${fontOptions(digitsMapping)}{Amiri}
4682
+ ${customFonts}
4683
+ \\newfontfamily\\boldarabic${fontOptions(digitsMapping)}{Amiri Bold}
4684
+ \\newfontfamily\\italicarabic${fontOptions(digitsMapping)}{Amiri Italic}
4685
+
4686
+ % for polyglossia url I dont know, sugggested by cursor
4687
+ \\newfontfamily\\arabicfonttt${fontOptions(digitsMapping)}{Amiri}
4688
+ \\newfontfamily\\arabicfontsf${fontOptions(digitsMapping)}{Amiri}
4689
+
4690
+
4691
+ % Explicitly set math font to XITS Math
4692
+ \\setmathfont${mathFontOptions}{XITS Math} % Ensure XITS Math is correctly installed and available
4693
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4694
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4695
+ `;
4696
+ }
4697
+ function arabicXeLatexPreambleCmd() {
4698
+ 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");
4699
+ return String.raw`
4700
+ % Run with XeLaTeX compiler
4701
+ ${fontCommands}
4702
+ \newcommand{\butexmirror}[1]{\reflectbox{\(#1\)}}
4703
+
4704
+ \newcommand{\arabN}{\text{\diwanioutlineshaded{ط}}}
4705
+ \newcommand{\arabZ}{\text{\diwanioutlineshaded{ص}}}
4706
+ \newcommand{\arabQ}{\text{\diwanioutlineshaded{ن}}}
4707
+ \newcommand{\arabR}{\text{\diwanioutlineshaded{ح}}}
4708
+ \newcommand{\arabC}{\text{\diwanioutlineshaded{ع}}}
4709
+ \newcommand{\arabH}{\text{\diwanioutlineshaded{ر}}}
4710
+
4711
+
4712
+ \newcommand{\lowerscript}[1]{\raisebox{-4pt}{\scriptsize #1}}
4713
+ \newcommand{\llowerscript}[1]{\raisebox{-8pt}{\scriptsize #1}}
4714
+ \newcommand{\lllowerscript}[2]{\raisebox{#2pt}{\scriptsize #1}}
4715
+
4716
+ \newcommand{\arabdsub}[3]{\prescript{}{#1}{\prescript{}{#2}{#3}}} % arabic double subscript
4717
+ \newcommand{\arabsub}[2]{\prescript{}{#1}{#2}} % arabic single subscript
4718
+
4719
+
4720
+
4721
+ \newcommand{\upperscript}[1]{\raisebox{8pt}{\scriptsize #1}}
4722
+ \newcommand{\uupperscript}[2]{\raisebox{#2pt}{\scriptsize #1}}
4723
+ \newcommand{\vertbar}{\rule[-1ex]{0.5pt}{2.5ex}}
4724
+ \newcommand{\horzbar}{\rule[.5ex]{2.5ex}{0.5pt}}
4725
+
4726
+
4727
+ \newcommand{\arsqrt}[2][]{\reflectbox{\(\sqrt[\reflectbox{\(#1\)}]{\reflectbox{\(#2\)}}\)}}
4728
+ \newcommand{\arabsqrt}[2][]{\arsqrt[#1]{#2}}
4729
+ \newcommand{\arabvec}[1]{\reflectbox{$\vec{\reflectbox{$#1$}}$}}
4730
+
4731
+ \newcommand{\arabexp}[1]{{}^{#1}\!\raisebox{-4.5pt}{\text{\diwani{ه}}}}
4732
+ \newcommand{\arablog}[2]{\left(\text{#2}\right)\!\prescript{}{\text{#1}}{\text{\diwani{لو}}}}
4733
+ \newcommand{\arabnlog}[1]{\left(\text{#1}\right)\!\prescript{}{\text{\diwani{ه}}}{\text{\diwani{لو}}}}
4734
+
4735
+ \newcommand{\arabcos}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{جتا}}}}
4736
+ \newcommand{\arabsin}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{جا}}}}
4737
+ \newcommand{\arabtan}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{ظا}}}}
4738
+ \newcommand{\arabcot}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{ظتا}}}}
4739
+ \newcommand{\arabsec}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قا}}}}
4740
+ \newcommand{\arabcsc}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قتا}}}}
4741
+
4742
+ \newcommand{\arabacos}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قجتا}}}}
4743
+ \newcommand{\arabasin}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قجا}}}}
4744
+ \newcommand{\arabatan}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قظا}}}}
4745
+ \newcommand{\arabacot}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{قظتا}}}}
4746
+ \newcommand{\arabasec}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{ققا}}}}
4747
+ \newcommand{\arabacsc}[1]{\left(#1\right)\!\!\raisebox{-2.5pt}{\text{\diwani{ققتا}}}}
4748
+
4749
+
4750
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4751
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4752
+ % summation
4753
+ \newcommand{\arablim}[2]{\underset{#2 \leftarrow #1}{\text{نـــــها}}}
4754
+ \newcommand{\arabsum}[2]{\underset{#1}{\overset{#2}{\text{مجـــ}}}}
4755
+ \newcommand{\arabprod}[2]{\underset{#1}{\overset{#2}{\text{جـــذ}}}}
4756
+ \newcommand{\arabint}[2]{\prescript{#2}{#1\!\!\!}\int}
4757
+
4758
+
4759
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4760
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4761
+ % we define this command to make it ease for change of notation later
4762
+ \newcommand{\ad}[0]{\text{ء}} % "ad" for arabic differentiation or derivative (ء" لإشتقاق")
4763
+ \newcommand{\arpi}[0]{\!\text{\diwani{ط}}}
4764
+
4765
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4766
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4767
+ % differentials
4768
+
4769
+ \newcommand{\arabdiff}[2]{\frac{#1\ad}{#2\ad}} % arabic differential
4770
+ \newcommand{\arabddiff}[2]{\frac{#1{}^{2}\ad}{{}^{2}#2\ad}} % arabic second differential
4771
+
4772
+ \newcommand{\arabode}[2][-5pt]{\stackrel{\raisebox{#1}{$\cdot$}}{\text{#2}}}
4773
+ \newcommand{\arabodde}[2][-5pt]{\stackrel{\raisebox{#1}{$\vcenter{\hbox{$\cdot\!\cdot$}}$}}{\text{#2}}}
4774
+ \newcommand{\araboddde}[2][-5pt]{\stackrel{\raisebox{#1}{$\vcenter{\hbox{$\cdot\!\cdot\!\cdot$}}$}}{\text{#2}}}
4775
+ \newcommand{\arabpde}[1]{\prescript{}{#1\!\!}{\nabla}} % arabic partial differential equation (PDE)
4776
+
4777
+ \newcommand{\arabprime}[0]{\reflectbox{$\prime$}\!} % arabic prime notation
4778
+ \newcommand{\arabpprime}[0]{\reflectbox{$\prime$}\reflectbox{$\prime$}\!} % arabic prime notation
4779
+ \newcommand{\arabppprime}[0]{\reflectbox{$\prime$}\reflectbox{$\prime$}\reflectbox{$\prime$}\!} % arabic prime notation
4780
+
4781
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4782
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4783
+ % probability
4784
+ \newcommand{\ap}[0]{\!\text{\diwani{حـ}}} % arabic Probability - used a lot so short form
4785
+ \newcommand{\arabExpct}[0]{\text{\diwani{توقـ}}} % arabic Expectation
4786
+ \newcommand{\arabVar}[0]{\!\text{\diwani{با}}} % arabic Variance
4787
+ \newcommand{\arabCov}[0]{\!\text{\diwani{ت}}} % arabic Covariance
4788
+
4789
+
4790
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4791
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4792
+ % custom commands specific to lesson
4793
+ \newcommand{\lagrange}[2]{\left(#2\right)\!\prescript{}{#1}{\text{\diwani{لا}}}}
4794
+ \newcommand{\xii}[0]{\left(\prescript{}{\text{يـ}}{\text{س}}\right)\!}
4795
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4796
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4797
+
4798
+
4799
+ \newcommand{\arexp}[0]{\!\raisebox{-4.5pt}{\text{\diwani{ه}}}}
4800
+ \newcommand{\arlog}[0]{\!\!\text{\diwani{لو}}}
4801
+ \newcommand{\arln}[0]{\!\!\prescript{}{\text{\diwani{ه}}}{\text{\diwani{لو}}}}
4802
+ \newcommand{\ardet}[0]{\!\!\text{\diwani{محدد}}}
4803
+
4804
+ \newcommand{\arsum}[0]{\text{مجـــ}}
4805
+ \newcommand{\arprod}[0]{\text{جـــذ}}
4806
+
4807
+ \newcommand{\arlim}[0]{\text{نـــــها}}
4808
+ \newcommand{\ararg}[0]{\text{حج}}
4809
+ \newcommand{\armax}[0]{\text{أكبر}}
4810
+ \newcommand{\armin}[0]{\text{أصغر}}
4811
+ \newcommand{\arsup}[0]{\text{أعلى}}
4812
+ \newcommand{\arinf}[0]{\text{أدنى}}
4813
+
4814
+ \newcommand{\arsin}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{جا}}}}
4815
+ \newcommand{\arcos}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{جتا}}}}
4816
+ \newcommand{\artan}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ظا}}}}
4817
+ \newcommand{\arcot}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ظتا}}}}
4818
+ \newcommand{\arsec}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قا}}}}
4819
+ \newcommand{\arcsc}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قتا}}}}
4820
+
4821
+ \newcommand{\arasin}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قجا}}}}
4822
+ \newcommand{\aracos}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قجتا}}}}
4823
+ \newcommand{\aratan}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قظا}}}}
4824
+ \newcommand{\aracot}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قظتا}}}}
4825
+ \newcommand{\arasec}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ققا}}}}
4826
+ \newcommand{\aracsc}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ققتا}}}}
4827
+
4828
+ \newcommand{\arsinh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{جزا}}}}
4829
+ \newcommand{\arcosh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{جتزا}}}}
4830
+ \newcommand{\artanh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ظزا}}}}
4831
+ \newcommand{\arcoth}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ظتزا}}}}
4832
+ \newcommand{\arsech}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قزا}}}}
4833
+ \newcommand{\arcsch}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قتزا}}}}
4834
+
4835
+ \newcommand{\arasinh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قجزا}}}}
4836
+ \newcommand{\aracosh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قجتزا}}}}
4837
+ \newcommand{\aratanh}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قظزا}}}}
4838
+ \newcommand{\aracoth}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{قظتزا}}}}
4839
+ \newcommand{\arasech}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ققزا}}}}
4840
+ \newcommand{\aracsch}[0]{\!\!\raisebox{-2.5pt}{\text{\diwani{ققتزا}}}}
4841
+
4842
+ \newcommand{\unit}[1]{\text{#1}}
4843
+ \newcommand{\idx}[1]{#1}
4844
+ \newcommand{\arbinom}[2]{\left(\begin{array}{c} #1 \\ #2 \end{array} \right)}
4845
+ `;
4846
+ }
4847
+ function getArabicXeLatexPreamble(digitsMappingOrOptions = "arabicdigits") {
4848
+ const options = typeof digitsMappingOrOptions === "string" ? { digitsMapping: digitsMappingOrOptions } : digitsMappingOrOptions;
4849
+ const digitsMapping = options.digitsMapping ?? "arabicdigits";
4850
+ const twocolumn = options.twocolumn === true;
4851
+ return arabicXeLatexPreamblePkg(twocolumn) + arabicXeLatexPreambleFont(digitsMapping) + arabicXeLatexPreambleCmd();
4852
+ }
4853
+
4854
+ // src/document/exportLatex.ts
4855
+ function editorMathLatexForCompile(token) {
4856
+ const source = token.math && token.sourceSide === "arabic" && token.source.includes("\\begin{cases}") ? mathTokenSourceForSide(token, "arabic", void 0, true) : token.source;
4857
+ return mirrorBuTeXOperatorsInTex(source, { target: "compile" });
4858
+ }
4859
+ function mathBodyLatex(token) {
4860
+ if (token.sourceOwner === "editor") {
4861
+ return stripDisplayMathDelimiters(editorMathLatexForCompile(token));
4862
+ }
4863
+ if (!token.math || token.sourceOwner === "raw") {
4864
+ return stripDisplayMathDelimiters(token.source);
4865
+ }
4866
+ const rendered = renderMathNodeLatex(token.math);
4867
+ return stripDisplayMathDelimiters(rendered);
4868
+ }
4869
+ function styledTextLatex(text, style) {
4870
+ let output = text;
4871
+ if (style?.bold) {
4872
+ output = `\\textbf{${output}}`;
4873
+ }
4874
+ if (style?.italic) {
4875
+ output = `\\textit{${output}}`;
4876
+ }
4877
+ if (style?.underline) {
4878
+ output = `\\underline{${output}}`;
4879
+ }
4880
+ return output;
4881
+ }
4882
+ function semanticRefPrefix(kind) {
4883
+ if (kind === "fig") {
4884
+ return "\u0627\u0644\u0634\u0643\u0644";
4885
+ }
4886
+ if (kind === "tab") {
4887
+ return "\u0627\u0644\u062C\u062F\u0648\u0644";
4888
+ }
4889
+ return "\u0627\u0644\u0645\u0639\u0627\u062F\u0644\u0629";
4890
+ }
4891
+ function semanticRefNames(kind) {
4892
+ if (kind === "fig") {
4893
+ return ["\u0627\u0644\u0634\u0643\u0644", "\u0634\u0643\u0644", "Figure", "figure"];
4894
+ }
4895
+ if (kind === "tab") {
4896
+ return ["\u0627\u0644\u062C\u062F\u0648\u0644", "\u062C\u062F\u0648\u0644", "Table", "table"];
4897
+ }
4898
+ return ["\u0627\u0644\u0645\u0639\u0627\u062F\u0644\u0629", "\u0645\u0639\u0627\u062F\u0644\u0629", "Equation", "equation"];
4899
+ }
4900
+ function previousTextAlreadyNamesKind(previousToken, kind) {
4901
+ if (previousToken?.kind !== "text") {
4902
+ return false;
4903
+ }
4904
+ const text = previousToken.text.trimEnd();
4905
+ return semanticRefNames(kind).some((name) => text.endsWith(name));
4906
+ }
4907
+ function refTokenLatexForDocument(token, labelKinds, previousToken) {
4908
+ const reference = refTokenLatex(token.keys, token.refCommand);
4909
+ if (!labelKinds || token.keys.length !== 1) {
4910
+ return reference;
4911
+ }
4912
+ const kind = labelKinds.get(token.keys[0]);
4913
+ if (!kind || previousTextAlreadyNamesKind(previousToken, kind)) {
4914
+ return reference;
4915
+ }
4916
+ return `${semanticRefPrefix(kind)}~${reference}`;
4917
+ }
4918
+ function tokenLatex(token, labelKinds, previousToken, unitId) {
4919
+ if (token.kind === "text") {
4920
+ return styledTextLatex(token.text, token.style);
4921
+ }
4922
+ if (token.kind === "cite") {
4923
+ return citeTokenLatex(token.keys);
4924
+ }
4925
+ if (token.kind === "ref") {
4926
+ return refTokenLatexForDocument(token, labelKinds, previousToken);
4927
+ }
4928
+ if (isNumberedEquation(token)) {
4929
+ const body = mathBodyLatex(token);
4930
+ const autoKey = implicitReferenceKey("eq", token.id, unitId);
4931
+ const aliases = [autoKey];
4932
+ if (token.labelEnabled && token.label?.trim() && token.label.trim() !== autoKey) aliases.push(token.label.trim());
4933
+ return "\\begin{equation}\n" + body + "\n" + aliases.map((key) => "\\label{" + key + "}").join("\n") + "\n\\end{equation}";
4934
+ }
4935
+ if (token.display && token.numbered === false && token.opening === "\\begin{equation}") {
4936
+ return "\\[" + mathBodyLatex(token) + "\\]";
4937
+ }
4938
+ if (token.sourceOwner === "editor") {
4939
+ return editorMathLatexForCompile(token);
4940
+ }
4941
+ if (!token.math || token.sourceOwner === "raw") {
4942
+ return token.source;
4943
+ }
4944
+ return renderMathNodeLatex(token.math);
4945
+ }
4946
+ function inlineFieldLatexWithLabelKinds(field, labelKinds, unitId) {
4947
+ return field.tokens.map((token, index) => tokenLatex(token, labelKinds, field.tokens[index - 1], unitId)).join("");
4948
+ }
4949
+ function textBlockLatex(block, labelKinds, unitId) {
4950
+ const content = inlineFieldLatexWithLabelKinds(block.field, labelKinds, unitId);
4951
+ const body = block.command === "\\paragraph" ? `\\par
4952
+ ${content}` : `${block.command}{${content}}`;
4953
+ if (block.command !== "\\paragraph") {
4954
+ const keys = unitId ? [implicitHeadingReferenceKey(block.command.slice(1), block.id, unitId)] : [];
4955
+ if (block.label?.trim() && !keys.includes(block.label.trim())) keys.push(block.label.trim());
4956
+ return [body, ...keys.map((key) => `\\label{${key}}`)].join("\n");
4957
+ }
4958
+ if (block.command === "\\paragraph" && block.centered) {
4959
+ return `\\begin{center}
4960
+ ${body}
4961
+ \\end{center}`;
4962
+ }
4963
+ return body;
4964
+ }
4965
+ function indent(value) {
4966
+ return value.split("\n").map((line) => ` ${line}`).join("\n");
4967
+ }
4968
+ function listBlockLatex(block, references, labelKinds, fixedFloats, unitId) {
4969
+ const items = block.items.map((item) => {
4970
+ const nested = item.blocks.map((child) => "\n" + indent(blockLatex(child, references, labelKinds, fixedFloats, unitId))).join("");
4971
+ return ` \\item ${inlineFieldLatexWithLabelKinds(item.field, labelKinds, unitId)}${nested}`;
4972
+ }).join("\n");
4973
+ return `${block.command}
4974
+ ${items}
4975
+ ${block.closing}`;
4976
+ }
4977
+ function defaultGridColumnSpec(block) {
4978
+ const compact = block.columns.replace(/\s+/g, "");
4979
+ const columnCount = block.rows[0]?.length ?? 0;
4980
+ if (columnCount === 0 || compact.length !== columnCount || !/^[lcr]+$/.test(compact)) {
4981
+ return null;
4982
+ }
4983
+ return `|${compact.split("").join("|")}|`;
4984
+ }
4985
+ function tabularInnerLatex(block, labelKinds, unitId) {
4986
+ const rows = block.rows.map(
4987
+ (row) => ` ${row.map((cell) => inlineFieldLatexWithLabelKinds(cell, labelKinds, unitId)).join(" & ")}`
4988
+ );
4989
+ const gridColumns = defaultGridColumnSpec(block);
4990
+ if (gridColumns) {
4991
+ const griddedRows = rows.map((row) => `${row} \\\\ \\hline`).join("\n");
4992
+ return `${block.command}{${gridColumns}}
4993
+ \\hline
4994
+ ${griddedRows}
4995
+ ${block.closing}`;
4996
+ }
4997
+ return `${block.command}{${block.columns}}
4998
+ ${rows.join(" \\\\\n")}
4999
+ ${block.closing}`;
5000
+ }
5001
+ function floatCaptionLabelLines(block, counter, labelKinds, unitId) {
5002
+ const lines = [];
5003
+ const caption = inlineFieldLatexWithLabelKinds(block.captionField, labelKinds, unitId).trim();
5004
+ const hasCaption = block.captionEnabled && caption.length > 0;
5005
+ if (hasCaption) {
5006
+ lines.push(` \\caption{${caption}}`);
5007
+ }
5008
+ const hasManualLabel = block.labelEnabled && block.label.trim().length > 0;
5009
+ if (hasCaption || hasManualLabel) {
5010
+ if (!hasCaption) lines.push(" \\refstepcounter{" + counter + "}");
5011
+ const autoKey = implicitReferenceKey(counter === "figure" ? "fig" : "tab", block.id, unitId);
5012
+ lines.push(" \\label{" + autoKey + "}");
5013
+ if (hasManualLabel && block.label.trim() !== autoKey) lines.push(" \\label{" + block.label.trim() + "}");
5014
+ }
5015
+ return lines;
5016
+ }
5017
+ function tableBlockLatex(block, labelKinds, fixedFloats, unitId) {
5018
+ const placement = fixedFloats ? "H" : "htbp";
5019
+ const lines = [`\\begin{table}[${placement}]`];
5020
+ if (block.centered) {
5021
+ lines.push(" \\centering");
5022
+ }
5023
+ lines.push(...floatCaptionLabelLines(block, "table", labelKinds, unitId));
5024
+ lines.push(indent(tabularInnerLatex(block, labelKinds, unitId)));
5025
+ lines.push("\\end{table}");
5026
+ return lines.join("\n");
5027
+ }
5028
+ function remapImageWidthForColumns(value) {
5029
+ return value.replace(/\\textwidth\b/g, "\\columnwidth");
5030
+ }
5031
+ function imageOptionsLatex(block, constrainToColumn) {
5032
+ const entries = Object.entries(block.options).map(([key, value]) => {
5033
+ if (constrainToColumn && key === "width") {
5034
+ return [key, remapImageWidthForColumns(value)];
5035
+ }
5036
+ return [key, value];
5037
+ });
5038
+ if (entries.length === 0) {
5039
+ return "";
5040
+ }
5041
+ return `[${entries.map(([key, value]) => `${key}=${value}`).join(",")}]`;
5042
+ }
5043
+ function imageBlockLatex(block, labelKinds, fixedFloats, unitId) {
5044
+ const placement = fixedFloats ? "H" : "htbp";
5045
+ const lines = [`\\begin{figure}[${placement}]`];
5046
+ if (block.centered) {
5047
+ lines.push(" \\centering");
5048
+ }
5049
+ lines.push(` ${block.command}${imageOptionsLatex(block, true)}{${block.value}}`);
5050
+ lines.push(...floatCaptionLabelLines(block, "figure", labelKinds, unitId));
5051
+ lines.push("\\end{figure}");
5052
+ return lines.join("\n");
5053
+ }
5054
+ function blockLatex(block, references, labelKinds, fixedFloats, unitId) {
5055
+ if (block.kind === "textBlock") {
5056
+ return textBlockLatex(block, labelKinds, unitId);
5057
+ }
5058
+ if (block.kind === "list") {
5059
+ return listBlockLatex(block, references, labelKinds, fixedFloats, unitId);
5060
+ }
5061
+ if (block.kind === "table") {
5062
+ return tableBlockLatex(block, labelKinds, fixedFloats, unitId);
5063
+ }
5064
+ if (block.kind === "image") {
5065
+ return imageBlockLatex(block, labelKinds, fixedFloats, unitId);
5066
+ }
5067
+ if (block.kind === "bibliography") {
5068
+ const width = String(Math.max(references.length, 9));
5069
+ const items = references.map((reference) => ` ${bibliographyEntryLatex(reference)}`).join("\n");
5070
+ return `${block.command}{${width}}
5071
+ ${items}
5072
+ ${block.closing}`;
5073
+ }
5074
+ return block.value;
5075
+ }
5076
+ function documentLabelKindMap(document2) {
5077
+ const map = /* @__PURE__ */ new Map();
5078
+ for (const [key, entry] of labelNumberMap(document2)) {
5079
+ map.set(key, entry.kind);
5080
+ }
5081
+ return map;
5082
+ }
5083
+ function documentContentLatex(document2, context) {
5084
+ if (!context?.unitId?.trim()) throw new Error("book-content export requires a stable unitId");
5085
+ const labelKinds = documentLabelKindMap(document2);
5086
+ for (const target of context?.targets ?? []) {
5087
+ if (target.kind === "fig" || target.kind === "tab" || target.kind === "eq") {
5088
+ labelKinds.set(target.key, target.kind);
5089
+ if (target.manualKey) labelKinds.set(target.manualKey, target.kind);
5090
+ }
5091
+ }
5092
+ return document2.blocks.filter((block) => block.kind !== "bibliography").map((block) => blockLatex(block, document2.references, labelKinds, false, context?.unitId)).filter((part) => part.length > 0).join("\n\n");
5093
+ }
5094
+
2809
5095
  // src/book/utils.ts
2810
5096
  var ID = /^[A-Za-z0-9_-]{1,128}$/;
2811
5097
  function safeId(id) {
@@ -3242,6 +5528,7 @@ function bookContextForUnit(snapshot, unitId) {
3242
5528
  kind: t.kind,
3243
5529
  ...t.caption !== void 0 ? { caption: t.caption } : {},
3244
5530
  ...t.displayLabel !== void 0 ? { displayLabel: t.displayLabel } : {},
5531
+ ...t.ordinal !== void 0 ? { ordinal: t.ordinal } : {},
3245
5532
  ...t.manualKey !== void 0 ? { manualKey: t.manualKey } : {}
3246
5533
  })) };
3247
5534
  }
@@ -3255,10 +5542,222 @@ function validateBookSnapshot(snapshot) {
3255
5542
  const resolution = resolveBookSnapshot(snapshot);
3256
5543
  return { valid: resolution.issues.every((x) => x.severity !== "error"), issues: resolution.issues };
3257
5544
  }
5545
+
5546
+ // src/book/exportLatex.ts
5547
+ var SAFE_PATH = /^[A-Za-z0-9][A-Za-z0-9._-]*(\/[A-Za-z0-9][A-Za-z0-9._-]*){0,3}$/;
5548
+ var IMAGE_EXT = /\.(?:png|jpe?g|pdf)$/i;
5549
+ function escapeLatex(value) {
5550
+ return value.replace(/[\\{}%#$&_~^]/g, (char) => ({
5551
+ "\\": "\\textbackslash{}",
5552
+ "{": "\\{",
5553
+ "}": "\\}",
5554
+ "%": "\\%",
5555
+ "#": "\\#",
5556
+ "$": "\\$",
5557
+ "&": "\\&",
5558
+ "_": "\\_",
5559
+ "~": "\\textasciitilde{}",
5560
+ "^": "\\textasciicircum{}"
5561
+ })[char] ?? char);
5562
+ }
5563
+ function visitAssets(blocks, collect) {
5564
+ for (const block of blocks) {
5565
+ if (block.command === "\\includegraphics") {
5566
+ if (!block.asset_id || typeof block.value !== "string") {
5567
+ throw new BookContractError("Book images require an asset_id and relative image path");
5568
+ }
5569
+ collect(block.asset_id, block.value);
5570
+ }
5571
+ for (const item of block.items ?? []) {
5572
+ visitAssets(item.blocks ?? [], collect);
5573
+ }
5574
+ }
5575
+ }
5576
+ function fingerprint(files, assets) {
5577
+ let value = 2166136261;
5578
+ const payload = JSON.stringify({ files, assets });
5579
+ for (const byte of new TextEncoder().encode(payload)) {
5580
+ value = Math.imul(value ^ byte, 16777619) >>> 0;
5581
+ }
5582
+ return "fnv1a32:" + value.toString(16).padStart(8, "0");
5583
+ }
5584
+ function heading(entry, resolution) {
5585
+ return resolution.outline.find((item) => item.id === entry.id)?.display_label ?? entry.title;
5586
+ }
5587
+ function unitBoundary(entry, projection, unnumbered) {
5588
+ const numbered = (entry.type === "chapter" || entry.type === "appendix") && entry.numbered;
5589
+ const lines = [];
5590
+ if (numbered) {
5591
+ const target = projection.targets.find((t) => t.unitId === entry.id && t.ownerId === entry.id);
5592
+ if (!target?.ordinal) throw new BookContractError("Missing Book numbering projection for " + entry.id);
5593
+ lines.push(
5594
+ "\\renewcommand{\\thechapter}{" + target.ordinal + "}",
5595
+ "\\refstepcounter{chapter}",
5596
+ "\\renewcommand{\\thesection}{\\thechapter.\\arabic{section}}"
5597
+ );
5598
+ } else {
5599
+ lines.push(
5600
+ "\\setcounter{section}{0}",
5601
+ "\\renewcommand{\\thesection}{\\arabic{section}}"
5602
+ );
5603
+ }
5604
+ for (const [kind, counter] of [["fig", "figure"], ["tab", "table"], ["eq", "equation"]]) {
5605
+ lines.push("\\setcounter{" + counter + "}{" + (numbered ? "0" : String(unnumbered[kind])) + "}");
5606
+ lines.push("\\renewcommand{\\the" + counter + "}{" + (numbered ? "\\thechapter." : "") + "\\arabic{" + counter + "}}");
5607
+ }
5608
+ const title = escapeLatex(heading(entry, projection));
5609
+ lines.push("\\chapter*{" + title + "}");
5610
+ if (entry.include_in_toc) {
5611
+ lines.push("\\addcontentsline{toc}{chapter}{" + title + "}");
5612
+ }
5613
+ if (numbered) {
5614
+ const target = projection.targets.find((t) => t.unitId === entry.id && t.ownerId === entry.id);
5615
+ if (target) lines.push("\\label{" + target.key + "}");
5616
+ if (entry.label && entry.label !== target?.key) lines.push("\\label{" + entry.label + "}");
5617
+ } else if (entry.label) {
5618
+ lines.push("\\label{" + entry.label + "}");
5619
+ }
5620
+ return lines.join("\n");
5621
+ }
5622
+ function bookPreamble(snapshot) {
5623
+ const arabicDigits = snapshot.manifest.meta.numbering?.digit_form !== "western";
5624
+ const articlePreamble = getArabicXeLatexPreamble({
5625
+ digitsMapping: arabicDigits ? "arabicdigits" : "digits"
5626
+ });
5627
+ const withoutClass = articlePreamble.replace(/\\documentclass\[[^\]]*\]\{article\}/, "");
5628
+ if (withoutClass === articlePreamble) throw new BookContractError("Arabic preamble class seam has changed");
5629
+ return [
5630
+ "\\NeedsTeXFormat{LaTeX2e}",
5631
+ "\\ProvidesPackage{book}[2026/11/14 BuTeX Arabic Book]",
5632
+ withoutClass.replace(/\\usepackage/g, "\\RequirePackage"),
5633
+ "\\renewcommand{\\figurename}{\u0627\u0644\u0634\u0643\u0644}",
5634
+ "\\renewcommand{\\tablename}{\u0627\u0644\u062C\u062F\u0648\u0644}",
5635
+ "\\renewcommand{\\contentsname}{\u0627\u0644\u0645\u062D\u062A\u0648\u064A\u0627\u062A}"
5636
+ ].join("\n");
5637
+ }
5638
+ function normalizeBookEquationLabels(content, unitId, projection) {
5639
+ const aliases = /* @__PURE__ */ new Map();
5640
+ let latex = content;
5641
+ for (const target of projection.targets) {
5642
+ if (target.kind !== "eq" || !target.manualKey || target.manualKey === target.key) continue;
5643
+ aliases.set(target.manualKey, target.key);
5644
+ if (target.unitId === unitId) {
5645
+ const automatic = "\\label{" + target.key + "}";
5646
+ const manual = "\\label{" + target.manualKey + "}";
5647
+ latex = latex.replace(automatic + "\n" + manual, automatic);
5648
+ }
5649
+ }
5650
+ if (!aliases.size) return latex;
5651
+ return latex.replace(/\\(eqref|ref)\{([^}]*)\}/g, (_whole, command, keys) => "\\" + command + "{" + keys.split(",").map((key) => aliases.get(key.trim()) ?? key).join(",") + "}");
5652
+ }
5653
+ function book2Latex(raw, _options = {}) {
5654
+ const snapshot = normalizeBookSnapshot(raw);
5655
+ const projection = resolveBookSnapshot(snapshot);
5656
+ const fatal = projection.issues.filter((issue2) => issue2.severity === "error");
5657
+ if (fatal.length) {
5658
+ throw new BookContractError("Book export blocked: " + fatal[0].code + " at " + fatal[0].path);
5659
+ }
5660
+ const files = {};
5661
+ const assets = [];
5662
+ const paths = /* @__PURE__ */ new Map();
5663
+ const addAsset = (assetId, path) => {
5664
+ const tail = path.split("/").at(-1) ?? "";
5665
+ const extensionless = !tail.includes(".");
5666
+ if (!SAFE_PATH.test(path) || path.split("/").some((part) => part.startsWith(".")) || !(IMAGE_EXT.test(path) || extensionless)) {
5667
+ throw new BookContractError("Unsafe or unsupported Book image path: " + path);
5668
+ }
5669
+ const alias = path.toLowerCase();
5670
+ const prior = paths.get(alias);
5671
+ if (prior && prior !== assetId) {
5672
+ throw new BookContractError("Multiple Book assets claim the same image path: " + path);
5673
+ }
5674
+ paths.set(alias, assetId);
5675
+ if (!assets.some((a) => a.asset_id === assetId && a.output_path === path)) {
5676
+ assets.push({ asset_id: assetId, output_path: path });
5677
+ }
5678
+ };
5679
+ const meta = snapshot.manifest.meta;
5680
+ const main = [
5681
+ "\\documentclass[12pt,a4paper]{book}",
5682
+ "\\usepackage{book}",
5683
+ "\\begin{document}"
5684
+ ];
5685
+ const unnumbered = { fig: 0, tab: 0, eq: 0 };
5686
+ let hasBibliography = false;
5687
+ let hasToc = false;
5688
+ for (const entry of snapshot.manifest.entries) {
5689
+ if (entry.kind === "generated") {
5690
+ if (entry.generated === "title-page") {
5691
+ main.push(
5692
+ "\\begin{titlepage}\\centering",
5693
+ "{\\Huge " + escapeLatex(meta.title) + "\\par}",
5694
+ "\\vspace{2cm}",
5695
+ ...meta.authors.map((author) => escapeLatex(author) + "\\par"),
5696
+ ...meta.date ? [escapeLatex(meta.date) + "\\par"] : [],
5697
+ "\\end{titlepage}"
5698
+ );
5699
+ } else if (entry.generated === "table-of-contents") {
5700
+ hasToc = true;
5701
+ main.push("\\tableofcontents");
5702
+ } else if (entry.generated === "list-of-figures") {
5703
+ main.push("\\listoffigures");
5704
+ } else if (entry.generated === "list-of-tables") {
5705
+ main.push("\\listoftables");
5706
+ } else if (entry.generated === "bibliography") {
5707
+ hasBibliography = true;
5708
+ main.push("\\input{references.tex}");
5709
+ }
5710
+ continue;
5711
+ }
5712
+ const unitPath = "units/" + entry.id + ".tex";
5713
+ const doc = snapshot.documents[entry.id];
5714
+ visitAssets(doc.blocks, addAsset);
5715
+ const context = {
5716
+ unitId: entry.id,
5717
+ references: snapshot.references.references,
5718
+ targets: projection.targets
5719
+ };
5720
+ const content = normalizeBookEquationLabels(documentContentLatex(fromDocumentJson(doc), context), entry.id, projection);
5721
+ files[unitPath] = [unitBoundary(entry, projection, unnumbered), content, ""].join("\n\n");
5722
+ main.push("\\input{" + unitPath + "}");
5723
+ if (!((entry.type === "chapter" || entry.type === "appendix") && entry.numbered)) {
5724
+ for (const kind of ["fig", "tab", "eq"]) {
5725
+ unnumbered[kind] += projection.targets.filter((t) => t.unitId === entry.id && t.kind === kind && t.numbered).length;
5726
+ }
5727
+ }
5728
+ }
5729
+ if (!hasToc && _options.include_toc_if_missing) {
5730
+ main.splice(3, 0, "\\tableofcontents");
5731
+ }
5732
+ if (snapshot.references.references.length) {
5733
+ const entries = snapshot.references.references.map((ref) => " " + bibliographyEntryLatex(referenceFromJson(ref)));
5734
+ files["references.tex"] = [
5735
+ "\\begin{thebibliography}{" + String(Math.max(9, entries.length)) + "}",
5736
+ ...entries,
5737
+ "\\end{thebibliography}",
5738
+ ""
5739
+ ].join("\n");
5740
+ if (!hasBibliography) main.push("\\input{references.tex}");
5741
+ } else if (hasBibliography) {
5742
+ files["references.tex"] = "% No shared references\n";
5743
+ }
5744
+ main.push("\\end{document}", "");
5745
+ files["main.tex"] = main.join("\n\n");
5746
+ files["book.sty"] = bookPreamble(snapshot);
5747
+ const ordered = Object.fromEntries(Object.entries(files).sort(([a], [b]) => a.localeCompare(b)));
5748
+ return {
5749
+ main_file: "main.tex",
5750
+ files: ordered,
5751
+ assets,
5752
+ diagnostics: projection.issues,
5753
+ fingerprint: fingerprint(ordered, assets)
5754
+ };
5755
+ }
3258
5756
  // Annotate the CommonJS export names for ESM import in node:
3259
5757
  0 && (module.exports = {
3260
5758
  BookContractError,
3261
5759
  applyBookCommand,
5760
+ book2Latex,
3262
5761
  bookContextForUnit,
3263
5762
  bookOutline,
3264
5763
  getBookReferenceIndex,