/usr/share/perl5/LaTeXML/Post/MathML.pm is in latexml 0.8.1-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 | # /=====================================================================\ #
# | LaTeXML::Post::MathML | #
# | MathML generator for LaTeXML | #
# |=====================================================================| #
# | Part of LaTeXML: | #
# | Public domain software, produced as part of work done by the | #
# | United States Government & not subject to copyright in the US. | #
# |---------------------------------------------------------------------| #
# | Bruce Miller <bruce.miller@nist.gov> #_# | #
# | http://dlmf.nist.gov/LaTeXML/ (o o) | #
# \=========================================================ooo==U==ooo=/ #
package LaTeXML::Post::MathML;
use strict;
use warnings;
use LaTeXML::Common::XML;
use LaTeXML::Post;
use List::Util qw(max);
use base qw(LaTeXML::Post::MathProcessor);
use base qw(Exporter);
our @EXPORT = (
qw( &DefMathML ),
qw( &pmml &pmml_scriptsize &pmml_smaller
&pmml_mi &pmml_mo &pmml_mn &pmml_bigop
&pmml_punctuate &pmml_parentesize
&pmml_infix &pmml_script &pmml_summation),
qw( &cmml &cmml_share &cmml_shared &cmml_ci
&cmml_or_compose &cmml_synth_not &cmml_synth_complement),
);
require LaTeXML::Post::MathML::Presentation;
require LaTeXML::Post::MathML::Content;
my $mmlURI = "http://www.w3.org/1998/Math/MathML"; # CONSTANT
# ================================================================================
# LaTeXML::MathML Base-level Math Formatter for LaTeXML's Parsed Math.
# Cooperate with the parsed math structure generated by LaTeXML::Math and
# convert into presentation & content MathML.
# (See LaTeXML::Post::MathML::Presentation, LaTeXML::Post::MathML::Content)
# ================================================================================
# Some clarity to work out:
# We're trying to convert either parsed or unparsed math (sometimes intertwined).
# How clearly do these have to be separated?
# at least, sub/superscripts do not attach to anything meaningful.
# ================================================================================
#================================================================================
# Useful switches when creating a converter with special needs.
# plane1 : use Unicode plane 1 characters for math letters
# hackplane1 : use a hybrid of plane1 for script and fraktur,
# otherwise regular chars with mathvariant
# usemfenced : whether to use mfenced instead of mrow
# this would be desired for MathML-CSS profile,
# but (I think) mrow usually gets better handling in firefox,..?
#================================================================================
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Top level
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
sub preprocess {
my ($self, $doc, @nodes) = @_;
# Set up rational, modern, defaults.
$$self{hackplane1} = 0 unless $$self{hackplane1};
$$self{plane1} = 1 if $$self{hackplane1} || !defined $$self{plane1};
$doc->adjust_latexml_doctype('MathML'); # Add MathML if LaTeXML dtd.
$doc->addNamespace($mmlURI, 'm');
return; }
# Works for pmml, cmml
sub outerWrapper {
my ($self, $doc, $xmath, $mml) = @_;
my $math = $xmath->parentNode;
my $mode = $math->getAttribute('mode') || 'inline';
my @img = ();
if (my $src = $math->getAttribute('imagesrc')) {
my $depth = $math->getAttribute('imagedepth');
@img = (altimg => $src,
'altimg-width' => $math->getAttribute('imagewidth'),
'altimg-height' => $math->getAttribute('imageheight'),
'altimg-valign' => ($depth ? -$depth : undef)); } # Note the sign!
my $wrapped = ['m:math', { display => ($mode eq 'display' ? 'block' : 'inline'),
class => $math->getAttribute('class'),
alttext => $math->getAttribute('tex'),
@img },
$mml];
# Associate the generated node with the source XMath node, but don't cross-reference
$self->associateNode($wrapped, $xmath, 1);
return $wrapped; }
# Map mimetype to Official MathML encodings
our %ENCODINGS = (
'application/mathml-presentation+xml' => 'MathML-Presentation',
'application/mathml-content+xml' => 'MathML-Content',
'image/svg+xml' => 'SVG1.1',
);
sub rawIDSuffix {
return '.msvg'; }
# This works for either pmml or cmml.
sub combineParallel {
my ($self, $doc, $xmath, $primary, @secondaries) = @_;
my $id = $xmath->getAttribute('fragid');
my @alt = ();
foreach my $secondary (@secondaries) {
my $mimetype = $$secondary{mimetype} || 'unknown';
my $encoding = $ENCODINGS{$mimetype} || $mimetype;
if ($mimetype =~ /^application\/mathml/) { # Some flavor of MathML? simple case
push(@alt, ['m:annotation-xml', { encoding => $encoding },
$$secondary{xml}]); }
elsif (my $xml = $$secondary{xml}) { # Other XML? may need wrapping.
push(@alt, ['m:annotation-xml', { encoding => $encoding },
$$secondary{processor}->outerWrapper($doc, $xmath, $xml)]); }
elsif (my $src = $$secondary{src}) { # something referred to by a file? Image, maybe?
push(@alt, ['m:annotation', { encoding => $encoding, src => $src }]); }
elsif (my $string = $$secondary{string}) { # simple string data?
push(@alt, ['m:annotation', { encoding => $encoding }, $string]); }
# anything else ignore?
}
# Perhaps should be it's own processor?
my $math = $xmath->parentNode;
if (my $tex = $math && isElementNode($math) && $math->getAttribute('tex')) {
push(@alt, ['m:annotation', { encoding => 'application/x-tex' }, $tex]); }
return { processor => $self, mimetype => $$primary{mimetype},
xml => ['m:semantics', {}, $$primary{xml}, @alt] }; }
# $self->convertNode($doc,$node);
# will be handled by specific Presentation or Content MathML converters; See at END.
# $self->translateNode($doc,$XMath,$style,$embedding)
# returns the translation of the XMath node (but doesn't insert it)
# $style will be either 'display' or 'text' (if relevant),
# The result should be wrapped as necessary for the result to
# be embedded within the tag $embedding.
# Eg. for parallel markup.
# See END for presentation, content and parallel versions.
sub getQName {
my ($node) = @_;
return $LaTeXML::Post::DOCUMENT->getQName($node); }
# Add a cross-reference linkage (eg. xref) onto $node to refer to the given $id.
# (presumably $id is the id of a node created by another Math Postprocessor
# from the same source XMath node that generated $node)
sub addCrossref {
my ($self, $node, $id) = @_;
$node->setAttribute(xref => $id);
return; }
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# General translation utilities.
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
sub realize {
my ($node) = @_;
return (ref $node) ? $LaTeXML::Post::DOCUMENT->realizeXMNode($node) : $node; }
# For a node that is a (possibly embellished) operator,
# find the underlying role.
my %EMBELLISHING_ROLE = ( # CONSTANT
SUPERSCRIPTOP => 1, SUBSCRIPTOP => 1, STACKED => 1,
OVERACCENT => 1, UNDERACCENT => 1, MODIFIER => 1, MODIFIEROP => 1);
sub getOperatorRole {
my ($node) = @_;
if (!$node) {
return; }
elsif (my $role = $node->getAttribute('role')) {
return $role; }
elsif (getQName($node) eq 'ltx:XMApp') {
my ($op, $base) = element_nodes($node);
return ($EMBELLISHING_ROLE{ $op->getAttribute('role') || '' }
? getOperatorRole($base)
: undef); } }
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Table of Translators for presentation|content
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# All translators take XMath XML::LibXML nodes as arguments,
# and return an intermediate form (ie. array form) of MathML to be added.
# DANGER!!! These accumulate all the DefMathML declarations.
# They're fixed after the module has been loaded, so are Daemon Safe,
# but probably should be going into (post) STATE, so that they are extensible.
# IN FACT, I'm already taking baby-steps to export DefMathML (and needed helpers),
# in order to assist these extensions, so that will bring up daemon issues pretty quick.
our $MMLTable_P = {};
our $MMLTable_C = {};
sub DefMathML {
my ($key, $presentation, $content) = @_;
$$MMLTable_P{$key} = $presentation if $presentation;
$$MMLTable_C{$key} = $content if $content;
return; }
sub lookupPresenter {
my ($mode, $role, $name) = @_;
$name = '?' unless $name;
$role = '?' unless $role;
return $$MMLTable_P{"$mode:$role:$name"} || $$MMLTable_P{"$mode:?:$name"}
|| $$MMLTable_P{"$mode:$role:?"} || $$MMLTable_P{"$mode:?:?"}; }
sub lookupContent {
my ($mode, $role, $name) = @_;
$name = '?' unless $name;
$role = '?' unless $role;
return $$MMLTable_C{"$mode:$role:$name"} || $$MMLTable_C{"$mode:?:$name"}
|| $$MMLTable_C{"$mode:$role:?"} || $$MMLTable_C{"$mode:?:?"}; }
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Various needed maps
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
my %stylestep = ( # CONSTANT
display => 'text', text => 'script',
script => 'scriptscript', scriptscript => 'scriptscript');
my %style_script_step = ( # CONSTANT
display => 'script', text => 'script',
script => 'scriptscript', scriptscript => 'scriptscript');
my %stylemap = ( # CONSTANT
display => { text => [displaystyle => 'false'],
script => [displaystyle => 'false', scriptlevel => '+1'],
scriptscript => [displaystyle => 'false', scriptlevel => '+2'] },
text => { display => [displaystyle => 'true'],
script => [scriptlevel => '+1'],
scriptscript => [scriptlevel => '+2'] },
script => { display => [displaystyle => 'true', scriptlevel => '-1'],
text => [scriptlevel => '-1'],
scriptscript => [scriptlevel => '+1'] },
scriptscript => { display => [displaystyle => 'true', scriptlevel => '-2'],
text => [scriptlevel => '-2'],
script => [scriptlevel => '-1'] });
# Mappings between (normalized) internal fonts & sizes.
# Default math font is roman|medium|upright.
my %mathvariants = ( # CONSTANT
'upright' => 'normal',
'serif' => 'normal',
'medium' => 'normal',
'bold' => 'bold',
'italic' => 'italic',
'medium italic' => 'italic',
'bold italic' => 'bold-italic',
'doublestruck' => 'double-struck',
'blackboard' => 'double-struck',
'fraktur' => 'fraktur',
'fraktur italic' => 'fraktur', # all collapse
'fraktur bold' => 'bold-fraktur',
'script' => 'script',
'script italic' => 'script', # all collapse
'script bold' => 'bold-script',
'caligraphic' => 'script', # all collapse; NOTE: In TeX caligraphic is NOT script!
'caligraphic bold' => 'bold-script',
'sansserif' => 'sans-serif',
'sansserif bold' => 'bold-sans-serif',
'sansserif italic' => 'sans-serif-italic',
'sansserif bold italic' => 'sans-serif-bold-italic',
'typewriter' => 'monospace',
'typewriter bold' => 'monospace',
'typewriter italic' => 'monospace',
'typewriter bold italic' => 'monospace',
);
# The font differences (from the containing context) have been deciphered
# into font, size and color attributes. The font should match
# one of the above... (?)
# Given a font string (joining the components)
# reduce it to a "sane" font. Note that MathML uses a single mathvariant
# to name the font, and doesn't inherit font components like italic or bold.
# Thus the font should be "complete", but also we can ignore components with
# default values like medium or upright (unless that is the only component).
sub mathvariantForFont {
my ($font) = @_;
$font =~ s/slanted/italic/; # equivalent in math
$font =~ s/serif\s//; # Not needed (unless alone)
$font =~ s/\supright//; # Not needed (unless 1st element)
$font =~ s/\smedium//; # Not needed (unless 1st element)
my $variant;
return $variant if $variant = $mathvariants{$font};
# $font =~ s/\sitalic//; # try w/o italic ?
# return $variant if $variant = $mathvariants{$font};
# $font =~ s/\sbold//; # try w/o bold ?
# return $variant if $variant = $mathvariants{$font};
return 'normal'; }
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Support functions for Presentation MathML
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
sub pmml_top {
my ($self, $node, $style) = @_;
# These bindings reflect the style, font, size & color that we are displaying in.
# Ie. if you want to draw in that size & color, you'll get it automatically.
local $LaTeXML::MathML::STYLE = $style || 'text';
local $LaTeXML::MathML::FONT = find_inherited_attribute($node, 'font');
# $LaTeXML::MathML::FONT = undef
# if $LaTeXML::MathML::FONT && !$mathvariants{$LaTeXML::MathML::FONT}; # verify sane font
local $LaTeXML::MathML::SIZE = find_inherited_attribute($node, 'fontsize');
local $LaTeXML::MathML::COLOR = find_inherited_attribute($node, 'color');
local $LaTeXML::MathML::BGCOLOR = find_inherited_attribute($node, 'backgroundcolor');
local $LaTeXML::MathML::OPACITY = find_inherited_attribute($node, 'opacity');
my @result = map { pmml($_) } element_nodes($node);
return (scalar(@result) > 1 ? ['m:mrow', {}, @result] : $result[0]); }
sub find_inherited_attribute {
my ($node, $attribute) = @_;
# Check for inherited style attributes, but stop at non-LaTeXML nodes
# [or at least be aware that the attribute may have totally different format or even meaning!]
while ($node && isElementNode($node) && ($node->namespaceURI eq 'http://dlmf.nist.gov/LaTeXML')) {
if (my $value = $node->getAttribute($attribute)) {
return $value; }
$node = $node->parentNode; }
return; }
# Convert a node that will automatically be made smaller, due to its context,
# such as in the numerator or denominator of a fraction.
sub pmml_smaller {
my ($node) = @_;
local $LaTeXML::MathML::STYLE = $stylestep{$LaTeXML::MathML::STYLE};
return pmml($node); }
# Convert a node that will automatically be made scriptsize,
# such as sub- or superscripts.
sub pmml_scriptsize {
my ($script) = @_;
local $LaTeXML::MathML::STYLE = $style_script_step{$LaTeXML::MathML::STYLE};
return ($script ? pmml($script) : ['m:none']); }
sub pmml {
my ($node) = @_;
# [since we follow split/scan, use the fragid, not xml:id! TO SOLVE LATER]
# Do the core conversion.
# Fetch the "real" node, if this is an XMRef to one; also use the OTHER's id!
my $refr;
if (getQName($node) eq 'ltx:XMRef') {
$refr = $node;
$node = realize($node); }
# Establish the source XMath node to be used for associating generated MathML
# A bit of heuristic is used (see the code)
local $LaTeXML::MathML::SOURCENODE = findPresentationSourceNode($node);
# Bind any other style information from the refering node or the current node
# so that any tokens synthesized from strings recover that style.
local $LaTeXML::MathML::SIZE = _getattr($refr, $node, 'fontsize') || $LaTeXML::MathML::SIZE;
local $LaTeXML::MathML::COLOR = _getattr($refr, $node, 'color') || $LaTeXML::MathML::COLOR;
local $LaTeXML::MathML::BGCOLOR = _getattr($refr, $node, 'backgroundcolor')
|| $LaTeXML::MathML::BGCOLOR;
local $LaTeXML::MathML::OPACITY = _getattr($refr, $node, 'opacity') || $LaTeXML::MathML::OPACITY;
my $result = pmml_internal($node);
# Let customization annotate the result.
# Now possibly wrap the result in a row, enclose, etc, if needed
my $o = _getattr($refr, $node, 'open');
my $c = _getattr($refr, $node, 'close');
my $e = _getattr($refr, $node, 'enclose');
my $p = _getattr($refr, $node, 'punctuation');
# these should COMBINE!
my $l = _getspace($refr, $node, 'lpadding');
my $r = _getspace($refr, $node, 'rpadding');
my $cl = join(' ', grep { $_ } $refr && $refr->getAttribute('class'), $node->getAttribute('class'));
# Handle generic things: open/close delimiters, punctuation
$result = pmml_parenthesize($result, $o, $c) if $o || $c;
$result = ['m:menclose', { notation => $e }, $result] if $e;
$result = ['m:mrow', {}, $result, pmml_mo($p)] if $p;
# Add spacing last; outside parens & enclosing (?)
if (!(((ref $result) eq 'ARRAY') && ($$result[0] eq 'm:mo')) # mo will already have gotten spacing!
&& ($r || $l)) {
my $w = ($l && $r ? $l + $r : ($l ? $l : $r));
$result = ['m:mpadded', { ($l ? (lspace => $l . "pt") : ()),
($w ? (width => ($w =~ /^-/ ? $w : '+' . $w) . "pt") : ()) }, $result]; }
if ($cl && ((ref $result) eq 'ARRAY')) { # Add classs, if any and different
my $ocl = $$result[1]{class};
$$result[1]{class} = (!$ocl || ($ocl eq $cl) ? $cl : "$ocl $cl"); }
# Associate the generated node with the source XMath node.
$LaTeXML::Post::MATHPROCESSOR->associateNode($result, $LaTeXML::MathML::SOURCENODE);
return $result; }
sub first_element {
my ($node) = @_;
my $c = $node->firstChild;
while ($c) {
return $c if $c->nodeType == XML_ELEMENT_NODE;
$c = $c->nextSibling; }
return; }
# Establish the source XMath node to be used for associating generated MathML
sub findPresentationSourceNode {
my ($node) = @_;
# if it is visible from the content side, we'll consider it the source.
return $node if $node->getAttribute('_cvis');
# Otherwise, dig a bit deeper if it seems to be an applied token.
if ((getQName($LaTeXML::MathML::SOURCENODE) || 'unknown') eq 'ltx:XMDual') {
my $sn = first_element($LaTeXML::MathML::SOURCENODE);
my $q = getQName($sn) || 'unknown';
return $sn if $q eq 'ltx:XMTok';
if ($q eq 'ltx:XMApp') {
return first_element($sn); } }
return $LaTeXML::MathML::SOURCENODE; }
sub _getattr {
my ($refr, $node, $attribute) = @_;
return ($refr && $refr->getAttribute($attribute)) || $node->getAttribute($attribute); }
sub _getspace {
my ($refr, $node, $attribute) = @_;
my $refspace = $refr && $refr->getAttribute($attribute);
my $nodespace = $node->getAttribute($attribute);
return ($refspace ? getXMHintSpacing($refspace) : 0)
+ ($nodespace ? getXMHintSpacing($nodespace) : 0); }
# Needs to be a utility somewhere...
sub getXMHintSpacing {
my ($width) = @_;
if ($width && ($width =~ /^([\d\.\+\-]+)(pt|mu)(\s+plus\s+[\d\.]+pt)?(\s+minus\s+[\d\.]+pt)?$/)) {
return ($2 eq 'mu' ? $1 / 1.8 : $1); }
else {
return 0; } }
my $NBSP = pack('U', 0xA0); # CONSTANT
sub pmml_internal {
my ($node) = @_;
return ['m:merror', {}, ['m:mtext', {}, "Missing Subexpression"]] unless $node;
my $tag = getQName($node);
my $role = $node->getAttribute('role');
if ($tag eq 'ltx:XMath') {
return pmml_row(map { pmml($_) } element_nodes($node)); } # Really multiple nodes???
elsif ($tag eq 'ltx:XMDual') {
my ($content, $presentation) = element_nodes($node);
return pmml($presentation); }
elsif (($tag eq 'ltx:XMWrap') || ($tag eq 'ltx:XMArg')) { # Only present if parsing failed!
return pmml_row(map { pmml($_) } element_nodes($node)); }
elsif ($tag eq 'ltx:XMApp') {
my ($op, @args) = element_nodes($node);
if (!$op) {
return ['m:merror', {}, ['m:mtext', {}, "Missing Operator"]]; }
elsif ($role && ($role =~ /^(FLOAT|POST)(SUB|SUPER)SCRIPT$/)) {
# (FLOAT|POST)(SUB|SUPER)SCRIPT's should NOT remain in successfully parsed math.
# This conversion creates something "presentable", though doubtfully correct (empty mi?)
# Really should mark & make a fake parsing pass to & group open/close pairs & attach scripts
return [($2 eq 'SUB' ? 'm:msub' : 'm:msup'), {}, ['m:mi'],
pmml_scriptsize($op)]; }
else {
my $rop = realize($op); # NOTE: Could loose open/close on XMRef ???
my $style = $rop->getAttribute('mathstyle') || $op->getAttribute('mathstyle');
my $styleattr = $style && $stylemap{$LaTeXML::MathML::STYLE}{$style};
local $LaTeXML::MathML::STYLE
= ($style && $stylestep{$style} ? $style : $LaTeXML::MathML::STYLE);
my $result = &{ lookupPresenter('Apply', getOperatorRole($rop), $rop->getAttribute('meaning'))
}($op, @args);
$result = ['m:mstyle', {@$styleattr}, $result] if $styleattr;
return $result; } }
elsif ($tag eq 'ltx:XMTok') {
return &{ lookupPresenter('Token', $role, $node->getAttribute('meaning')) }($node); }
elsif ($tag eq 'ltx:XMHint') {
return &{ lookupPresenter('Hint', $role, $node->getAttribute('meaning')) }($node); }
elsif ($tag eq 'ltx:XMArray') {
my $style = $node->getAttribute('mathstyle');
my $vattach = $node->getAttribute('vattach');
$vattach = 'axis' if !$vattach || ($vattach eq 'middle'); # roughly MathML's axis?
my $styleattr = $style && $stylemap{$LaTeXML::MathML::STYLE}{$style};
local $LaTeXML::MathML::STYLE
= ($style && $stylestep{$style} ? $style : $LaTeXML::MathML::STYLE);
my @rows = ();
foreach my $row (element_nodes($node)) {
my @cols = ();
foreach my $col (element_nodes($row)) {
my $a = $col->getAttribute('align');
my $b = $col->getAttribute('border');
my $bc = ($b ? join(' ', map { 'ltx_border_' . $_ } split(/\s/, $b)) : $b);
my $h = (($col->getAttribute('thead') || '') eq 'true') && 'thead';
my $cl = $col->getAttribute('class');
my $c = ($bc ? ($h ? "$bc $h" : $bc) : $h);
my $cs = $col->getAttribute('colspan');
my $rs = $col->getAttribute('rowspan');
push(@cols, ['m:mtd', { ($a ? (columnalign => $a) : ()),
($c || $cl ? (class => ($c && $cl ? "$c $cl" : $c || $cl)) : ()),
($cs ? (columnspan => $cs) : ()),
($rs ? (rowspan => $rs) : ()) },
map { pmml($_) } element_nodes($col)]); }
push(@rows, ['m:mtr', {}, @cols]); }
### We shouldn't use a blanket (row|column)spacing!!!
### Either it should scale with font size, or be recorded when creating the alignment!
#### my $result = ['m:mtable', { rowspacing => "0.2ex", columnspacing => "0.4em", align => $vattach }, @rows];
my $result = ['m:mtable', { ($vattach ne 'axis' ? (align => $vattach) : ()),
# Mozilla seems to need some encouragement?
($LaTeXML::MathML::STYLE eq 'display' ? (displaystyle => 'true') : ()) },
@rows];
$result = ['m:mstyle', {@$styleattr}, $result] if $styleattr;
return $result; }
elsif ($tag eq 'ltx:XMText') {
my @c = $node->childNodes;
# HEURISTIC? To remove leading & trailing blanknodes
if ($c[0] && ($c[0]->nodeType == XML_TEXT_NODE) && ($c[0] =~ /^\s*$/)) {
shift(@c); }
if ($c[-1] && ($c[-1]->nodeType == XML_TEXT_NODE) && ($c[-1] =~ /^\s*$/)) {
pop(@c); }
return pmml_row(map { pmml_text_aux($_) } @c); }
elsif ($tag eq 'ltx:ERROR') {
my $cl = $node->getAttribute('class');
return ['m:merror', { class => join(' ', grep { $_ } 'ltx_ERROR', $cl) },
['m:mtext', {}, $node->textContent]]; }
else {
my $text = $node->textContent; # Spaces are significant here
$text =~ s/^\s+/$NBSP/;
$text =~ s/\s+$/$NBSP/;
return ['m:mtext', {}, $text]; } }
sub pmml_row {
my (@items) = @_;
@items = grep { $_ } @items;
return (scalar(@items) == 1 ? $items[0] : ['m:mrow', {}, @items]); }
sub pmml_unrow {
my ($mml) = @_;
if ($mml && (ref $mml) && ($$mml[0] eq 'm:mrow') && !scalar(keys %{ $$mml[1] })) {
my ($tag, $attr, @children) = @$mml;
return @children; }
else {
return ($mml); } }
sub pmml_parenthesize {
my ($item, $open, $close) = @_;
if (!$open && !$close) {
return $item; }
# OR, maybe we should just use mfenced?
# mfenced is better for CSS profile.
# when the insides are line-broken, induces a less traditional appearance
# (however, line-breaking inside of a mrow w/parens needs some special treatment too! scripts!!)
elsif ($$LaTeXML::Post::MATHPROCESSOR{usemfenced}) {
return ['m:mfenced', { open => ($open || ''), close => ($close || '') }, $item]; }
## Maybe better not open the contained mrow; seems to affect bracket size in Moz.???
# elsif($item && (ref $item) && ($item->[0] eq 'm:mrow')){
# my($tag,$attr,@children)=@$item;
# ['m:mrow',$attr,
# ($open ? (pmml_mo($open)):()),
# @children,
# ($close ? (pmml_mo($close)):())]; }
else {
return ['m:mrow', {},
($open ? (pmml_mo($open, role => 'OPEN')) : ()),
$item,
($close ? (pmml_mo($close, role => 'CLOSE')) : ())]; } }
sub pmml_punctuate {
my ($separators, @items) = @_;
$separators = '' unless defined $separators;
my $lastsep = ', ';
my @arglist;
if (@items) {
push(@arglist, shift(@items));
while (@items) {
if ($separators =~ s/^(.*?)( |$)//) { # delimited by SINGLE SPACE!!
$lastsep = $1 if $1; }
push(@arglist, pmml_mo($lastsep, role => 'PUNCT'), shift(@items)); } }
return pmml_row(@arglist); }
# args are XMath nodes
# This is suitable for use as an Apply handler.
sub pmml_infix {
my ($op, @args) = @_;
$op = realize($op) if ref $op;
return ['m:mrow', {}] unless $op && @args; # ??
my @items = ();
if (scalar(@args) == 1) { # Infix with 1 arg is presumably Prefix!
push(@items, (ref $op ? pmml($op) : pmml_mo($op)), pmml($args[0])); }
else {
## push(@items, pmml(shift(@args)));
# Experiment at flattening?
my $role = (ref $op ? getOperatorRole($op) : 'none');
my $arg1 = realize(shift(@args));
if (($role eq 'ADDOP')
&& (getQName($arg1) eq 'ltx:XMApp')
&& !$arg1->getAttribute('open') && !$arg1->getAttribute('close')
&& (getOperatorRole((element_nodes($arg1))[0]) eq $role)) {
push(@items, pmml_unrow(pmml($arg1))); }
else {
push(@items, pmml($arg1)); }
while (@args) {
push(@items, (ref $op ? pmml($op) : pmml_mo($op)));
push(@items, pmml(shift(@args))); } }
return pmml_row(@items); }
sub UTF {
my ($code) = @_;
return pack('U', $code); }
sub makePlane1Map {
my ($latin, $GREEK, $greek, $digits) = @_;
return (
(map { (UTF(ord('A') + $_) => UTF($latin + $_)) } 0 .. 25),
(map { (UTF(ord('a') + $_) => UTF($latin + 26 + $_)) } 0 .. 25),
($GREEK ? (map { (UTF(0x0391 + $_) => UTF($GREEK + $_)) } 0 .. 24) : ()),
($greek ? (map { (UTF(0x03B1 + $_) => UTF($greek + $_)) } 0 .. 24) : ()),
($digits ? (map { (UTF(ord('0') + $_) => UTF($digits + $_)) } 0 .. 9) : ())); }
my %plane1map = ( # CONSTANT
'bold' => { makePlane1Map(0x1D400, 0x1D6A8, 0x1D6C2, 0x1D7CE) },
'italic' => { makePlane1Map(0x1D434, 0x1D6E2, 0x1D6FC, undef),
h => "\x{210E}" },
'bold-italic' => { makePlane1Map(0x1D468, 0x1D71C, 0x1D736, undef) },
'sans-serif' => { makePlane1Map(0x1D5A0, undef, undef, 0x1D7E2) },
'bold-sans-serif' => { makePlane1Map(0x1D5D4, 0x1D756, 0x1D770, 0x1D7EC) },
'sans-serif-italic' => { makePlane1Map(0x1D608, undef, undef, undef) },
'sans-serif-bold-italic' => { makePlane1Map(0x1D63C, 0x1D790, 0x1D7AA, undef) },
'monospace' => { makePlane1Map(0x1D670, undef, undef, 0x1D7F6) },
'script' => { makePlane1Map(0x1D49C, undef, undef, undef),
B => "\x{212C}", E => "\x{2130}", F => "\x{2131}", H => "\x{210B}", I => "\x{2110}",
L => "\x{2112}", M => "\x{2133}", R => "\x{211B}",
e => "\x{212F}", g => "\x{210A}", o => "\x{2134}" },
'bold-script' => { makePlane1Map(0x1D4D0, undef, undef, undef) },
'fraktur' => { makePlane1Map(0x1D504, undef, undef, undef),
C => "\x{212D}", H => "\x{210C}", I => "\x{2111}", R => "\x{211C}", Z => "\x{2128}" },
'bold-fraktur' => { makePlane1Map(0x1D56C, undef, undef, undef) },
'double-struck' => { makePlane1Map(0x1D538, undef, undef, 0x1D7D8),
C => "\x{2102}", H => "\x{210D}", N => "\x{2115}", P => "\x{2119}", Q => "\x{211A}",
R => "\x{211D}", Z => "\x{2124}" }
);
my %plane1hack = ( # CONSTANT
script => $plane1map{script}, 'bold-script' => $plane1map{script},
fraktur => $plane1map{fraktur}, 'bold-fraktur' => $plane1map{fraktur},
'double-struck' => $plane1map{'double-struck'});
# Given an item (string or token element w/attributes) and latexml attributes,
# convert the string to the appropriate unicode (possibly plane1)
# & MathML presentation attributes (mathvariant, mathsize, mathcolor, stretchy)
# $mihack is a boolean whether to apply mi's special case rule for single character identifier.
sub stylizeContent {
my ($item, $mihack, %attr) = @_;
my $iselement = (ref $item) eq 'XML::LibXML::Element';
my $role = ($iselement ? $item->getAttribute('role') : 'ID');
my $font = ($iselement ? $item->getAttribute('font') : $attr{font})
|| $LaTeXML::MathML::FONT;
my $size = ($iselement ? $item->getAttribute('fontsize') : $attr{fontsize})
|| $LaTeXML::MathML::SIZE;
my $color = ($iselement ? $item->getAttribute('color') : $attr{color})
|| $LaTeXML::MathML::COLOR;
my $bgcolor = ($iselement ? $item->getAttribute('backgroundcolor') : $attr{backgroundcolor})
|| $LaTeXML::MathML::BGCOLOR;
my $opacity = ($iselement ? $item->getAttribute('opacity') : $attr{opacity})
|| $LaTeXML::MathML::OPACITY;
my $class = ($iselement ? $item->getAttribute('class') : $attr{class});
my $text = (ref $item ? $item->textContent : $item);
my $variant = ($font ? mathvariantForFont($font) : '');
my $stretchy = ($iselement ? $item->getAttribute('stretchy') : $attr{stretchy});
$size = undef if ($stretchy || 'false') eq 'true'; # Ignore size, if we're stretching.
$size = undef if $size && ($size eq $LaTeXML::MathML::STYLE);
my $stretchyhack = undef;
if ($size) {
# Note that symmetric is only allowed when stretchy, which looks crappy for specific sizes
# so we'll pretend that delimiters are still stretchy, but restrict size by minsize & maxsize
# (Thanks Peter Krautzberger)
if (($role eq 'OPEN') || ($role eq 'CLOSE')) {
$stretchyhack = 1;
$stretchy = undef; }
else {
$stretchy = 'false' } }; # Conversely, if size was specifically set, we shouldn't stretch it!
# Failsafe for empty tokens?
if ((!defined $text) || ($text eq '')) {
$text = ($iselement ? $item->getAttribute('name') || $item->getAttribute('meaning') || $role : '?');
$color = 'red'; }
if ($font && !$variant) {
Warn('unexpected', $font, undef, "Unrecognized font variant '$font'"); $variant = ''; }
# Special case for single char identifiers?
if ($mihack && ($text =~ /^.$/)) { # Single char in mi?
if ($variant eq 'italic') { $variant = undef; } # Defaults to italic
elsif (!$variant) { $variant = 'normal'; } } # must say so explicitly.
# Use class (css) to patchup some weak translations
if (!$font) { }
elsif ($font =~ /caligraphic/) {
# Note that this is unlikely to have effect when plane1 chars are used!
$class = ($class ? $class . ' ' : '') . 'ltx_font_mathcaligraphic'; }
elsif ($font =~ /script/) {
$class = ($class ? $class . ' ' : '') . 'ltx_font_mathscript'; }
elsif (($font =~ /fraktur/) && ($text =~ /^[\+\-\d\.]*$/)) { # fraktur number?
$class = ($class ? $class . ' ' : '') . 'ltx_font_oldstyle'; }
# Should we map to Unicode's Plane 1 blocks for Mathematical Alphanumeric Symbols?
# Only upper & lower case latin & greek, and also numerals can be mapped.
# For each mathvariant, and for each of those 5 groups, there is a linear mapping,
# EXCEPT for chars defined before Plain 1, which already exist in lower blocks.
my $mapping;
# Get desired mapping strategy
my $plane1 = $$LaTeXML::Post::MATHPROCESSOR{plane1};
my $plane1hack = $$LaTeXML::Post::MATHPROCESSOR{hackplane1};
if ($variant
&& ($plane1 || $plane1hack)
&& ($mapping = ($plane1hack ? $plane1hack{$variant} : $plane1map{$variant}))) {
my @c = map { $$mapping{$_} } split(//, $text);
if (!grep { !defined $_ } @c) { # Only if ALL chars in the token could be mapped... ?????
$text = join('', @c);
$variant = ($plane1hack && ($variant =~ /^bold/) ? 'bold' : undef); } }
return ($text,
($variant ? (mathvariant => $variant) : ()),
($size ? ($stretchyhack
? (minsize => $size, maxsize => $size)
: (mathsize => $size))
: ()),
($color ? (mathcolor => $color) : ()),
($bgcolor ? (mathbackground => $bgcolor) : ()),
($opacity ? (style => "opacity:$opacity") : ()), # ???
($stretchy ? (stretchy => $stretchy) : ()),
($class ? (class => $class) : ())
); }
# These are the strings that should be known as fences in a normal operator dictionary.
my %fences = ( # CONSTANT
'(' => 1, ')' => 1, '[' => 1, ']' => 1, '{' => 1, '}' => 1, "\x{201C}" => 1, "\x{201D}" => 1,
"\`" => 1, "'" => 1, "<" => 1, ">" => 1,
"\x{2329}" => 1, "\x{232A}" => 1, # angle brackets; NOT mathematical, but balance in case they show up.
"\x{27E8}" => 1, "\x{27E9}" => 1, # angle brackets (preferred)
"\x{230A}" => 1, "\x{230B}" => 1, "\x{2308}" => 1, "\x{2309}" => 1);
my %punctuation = (',' => 1, ';' => 1, "\x{2063}" => 1); # CONSTANT
# Generally, $item in the following ought to be a string.
sub pmml_mi {
my ($item, %attr) = @_;
my ($text, %mmlattr) = stylizeContent($item, 1, %attr);
return ['m:mi', {%mmlattr}, $text]; }
# Really, the same issues as with mi.
sub pmml_mn {
my ($item, %attr) = @_;
my ($text, %mmlattr) = stylizeContent($item, 0, %attr);
return ['m:mn', {%mmlattr}, $text]; }
# Note that $item should be either a string, or at most, an XMTok
sub pmml_mo {
my ($item, %attr) = @_;
my ($text, %mmlattr) = stylizeContent($item, 0, %attr);
my $role = (ref $item ? $item->getAttribute('role') : $attr{role});
my $isfence = $role && ($role =~ /^(OPEN|CLOSE)$/);
my $ispunct = $role && ($role eq 'PUNCT');
my $islargeop = $role && ($role =~ /^(SUMOP|INTOP)$/);
my $lpad = $attr{lpadding}
|| ((ref $item) && $item->getAttribute('lpadding'))
|| ($role && ($role eq 'MODIFIEROP') && 'mediummathspace');
my $rpad = $attr{rpadding}
|| ((ref $item) && $item->getAttribute('rpadding'))
|| ($role && ($role eq 'MODIFIEROP') && 'mediummathspace');
my $pos = (ref $item && $item->getAttribute('scriptpos')) || 'post';
return ['m:mo', { %mmlattr,
($isfence && !$fences{$text} ? (fence => 'true') : ()),
($ispunct && !$punctuation{$text} ? (separator => 'true') : ()),
($islargeop ? (largeop => 'true') : ()),
($islargeop ? (symmetric => 'true') : ()), # Not sure this is strictly correct...
# Note that lspace,rspace is the left & right space that replaces Op.Dictionary
# what we've recorded is _padding_, so we have to adjust the unknown OpDict entry!
# Just assume something between mediummathspace = 4/18em = 2.222pt
# and thickmathspace = 5/18em = 2.7777pt, so 2.5pt.
($lpad ? (lspace => max(0, (2.5 + getXMHintSpacing($lpad))) . 'pt') : ()),
($rpad ? (rspace => max(0, (2.5 + getXMHintSpacing($rpad))) . 'pt') : ()),
# If an operator has specifically located it's scripts,
# don't let mathml move them.
(($pos =~ /mid/) || $LaTeXML::MathML::NOMOVABLELIMITS
? (movablelimits => 'false') : ()) },
$text]; }
sub pmml_bigop {
my ($op) = @_;
my $style = $op->getAttribute('mathstyle');
my $styleattr = $style && $stylemap{$LaTeXML::MathML::STYLE}{$style};
local $LaTeXML::MathML::STYLE
= ($style && $stylestep{$style} ? $style : $LaTeXML::MathML::STYLE);
my $mml = pmml_mo($op);
$mml = ['m:mstyle', {@$styleattr}, $mml] if $styleattr;
return $mml; }
# Since we're keeping track of display style, under/over vs. sub/super
# We've got to keep track of MathML's desire to do it for us,
# and be prepared to override it.
# When we encounter a script, we've got to look into the possibly embellished
# operator for more scripts, and attempt to decipher (based on scriptpos attribute)
# the various positionings (pre, mid, post) and determine whether
# prescripts, multiscripts, munderover or msubsup should be used.
#
# Depending on which order the pre/post sub/super/over/under scripts appear,
# we may end up with a multiscript, or scripts applied to embellished operators.
# In particular, we may end up with postscripts applied to an object with over/under;
# OR, the other way around.
# In the latter case, we may have limits on a primed sum, in which case
# we will want to adjust the spacing so the limits center on the sum WITHOUT the primes!!!!
#
# Moreoever, the inner operator may be a largeop and need to be displaystyle;
# since mstyle doesn't nest well inside the scripts, we'll handle that too.
# We also make sure the eventual inner operator (if any) has movablelimits disabled.
sub pmml_script {
my ($op, $base, $script) = @_;
# disentangle base & pre/post-scripts
my ($innerbase, $prescripts, $midscripts, $postscripts, $emb_left, $emb_right)
= pmml_script_decipher($op, $base, $script);
# check if base needs displaystyle.
my $style = $innerbase->getAttribute('mathstyle');
if ($style && ($style ne $LaTeXML::MathML::STYLE)) {
local $LaTeXML::MathML::STYLE = $style;
return ['m:mstyle', { displaystyle => ($style eq 'display' ? 'true' : 'false') },
pmml_script_multi_layout(
pmml_script_mid_layout($innerbase, $midscripts, $emb_left, $emb_right),
$prescripts, $postscripts)]; }
else {
return pmml_script_multi_layout(
pmml_script_mid_layout($innerbase, $midscripts, $emb_left, $emb_right),
$prescripts, $postscripts); } }
sub pmml_script_mid_layout {
my ($base, $midscripts, $emb_left, $emb_right) = @_;
if (scalar(@$midscripts) == 0) {
return pmml($base); }
else {
if (scalar(@$midscripts) > 1) {
Error("unexpected", $base, "Multiple mid-level (limit) scripts; extras are DROPPED!",
map { @$_ } @$midscripts); }
{ local $LaTeXML::MathML::NOMOVABLELIMITS = 1;
$base = pmml($base); }
# Get the (possibly padded) over & under scripts (if any)
my $under = (!defined $$midscripts[0][0] ? undef
: pmml_scriptsize_padded($$midscripts[0][0], $emb_left, $emb_right));
my $over = (!defined $$midscripts[0][1] ? undef
: pmml_scriptsize_padded($$midscripts[0][1], $emb_left, $emb_right));
if (!defined $over) {
return ['m:munder', {}, $base, $under]; }
elsif (!defined $under) {
return ['m:mover', {}, $base, $over]; }
else {
return ['m:munderover', {}, $base, $under, $over]; } } }
# Convert an over or under script to scriptsize,
# but pad by phantoms of the base's embellishments, if any.
# This is to handle primed sums, etc....
sub pmml_scriptsize_padded {
my ($script, $emb_left, $emb_right) = @_;
return ($emb_left || $emb_right
? ['m:mrow', {},
($emb_left ? (['m:mphantom', {}, pmml_scriptsize($emb_left)]) : ()),
pmml_scriptsize($script),
($emb_right ? (['m:mphantom', {}, pmml_scriptsize($emb_right)]) : ())]
: pmml_scriptsize($script)); }
# base is already converted
sub pmml_script_multi_layout {
my ($base, $prescripts, $postscripts) = @_;
if (scalar(@$prescripts) > 0) {
return ['m:mmultiscripts', {},
$base,
(map { (pmml_scriptsize($_->[0]), pmml_scriptsize($_->[1])) } @$postscripts),
['m:mprescripts'],
(map { (pmml_scriptsize($_->[0]), pmml_scriptsize($_->[1])) } @$prescripts)]; }
elsif (scalar(@$postscripts) > 1) {
return ['m:mmultiscripts', {},
$base,
(map { (pmml_scriptsize($_->[0]), pmml_scriptsize($_->[1])) } @$postscripts)]; }
elsif (scalar(@$postscripts) == 0) {
return $base; }
elsif (!defined $$postscripts[0][1]) {
return ['m:msub', {}, $base, pmml_scriptsize($$postscripts[0][0])]; }
elsif (!defined $$postscripts[0][0]) {
return ['m:msup', {}, $base, pmml_scriptsize($$postscripts[0][1])]; }
else {
return ['m:msubsup', {}, $base,
pmml_scriptsize($$postscripts[0][0]), pmml_scriptsize($$postscripts[0][1])]; } }
# Various pre, post and even mid scripts can be wrapped around a base element.
# Try to decipher such a nesting (in the XMath element) to collect these separate groups
# They propbably shouldn't be stirred up, but appear in pre, mid,post order,
# otherwise it's not at all clear how this was expected to look; likely an upstream error?
# Nor should there be more than a single sub & single sup mid positioned script!
sub pmml_script_decipher {
my ($op, $base, $script) = @_;
my (@pres, @mids, @posts);
my ($prelevel, $midlevel, $postlevel) = (0, 0, 0);
my $sawmid = 0;
my ($emb_left, $emb_right) = (undef, undef); # embellishments of base on left & right
my ($y) = ($op->getAttribute('role') || '') =~ /^(SUPER|SUB)SCRIPTOP$/;
my ($pos, $level) = ($op->getAttribute('scriptpos') || 'post0')
=~ /^(pre|mid|post)?(\d+)?$/;
if ($pos eq 'pre') {
if ($y eq 'SUB') {
push(@pres, [$script, undef]); $prelevel = $level; }
elsif ($y eq 'SUPER') {
push(@pres, [undef, $script]); $prelevel = $level; } }
elsif ($pos eq 'mid') {
$sawmid = 1;
if ($y eq 'SUB') {
push(@mids, [$script, undef]); $midlevel = $level; }
elsif ($y eq 'SUPER') {
push(@mids, [undef, $script]); $midlevel = $level; } }
else { # else it's post
if ($y eq 'SUB') {
push(@posts, [$script, undef]); $postlevel = $level; }
elsif ($y eq 'SUPER') {
push(@posts, [undef, $script]); $postlevel = $level; } }
# Examine $base to see if there are nested scripts.
# We'll fold them together they seem to be on the appropriate levels
# Keep from having multiple scripts when $loc is stack!!!
while (1) {
last unless getQName($base) eq 'ltx:XMApp';
last if $base->getAttribute('open') || $base->getAttribute('close');
my ($xop, $xbase, $xscript) = element_nodes($base);
last unless (getQName($xop) eq 'ltx:XMTok');
my ($ny) = ($xop->getAttribute('role') || '') =~ /^(SUPER|SUB)SCRIPTOP$/;
last unless $ny;
my ($nx, $nl) = ($xop->getAttribute('scriptpos') || 'post0')
=~ /^(pre|mid|post)?(\d+)?$/;
my $spos = ($ny eq 'SUB' ? 0 : 1);
if ($nx eq 'pre') {
push(@pres, [undef, undef]) # New empty pair (?)
if ($prelevel ne $nl) || $pres[-1][$spos];
$pres[-1][$spos] = $xscript; $prelevel = $nl; }
elsif ($nx eq 'mid') {
$sawmid = 1;
unshift(@mids, [undef, undef]) # New empty pair (?)
if ($midlevel ne $nl) || $mids[0][$spos];
$mids[0][$spos] = $xscript; $midlevel = $nl; }
else {
if ($sawmid) { # If we already saw mid-scripts (over/under); check for embellishmnt
$emb_right = $xscript;
last; }
unshift(@posts, [undef, undef]) # New empty pair (?)
if ($postlevel ne $nl) || $posts[0][$spos];
$posts[0][$spos] = $xscript; $postlevel = $nl; }
$base = $xbase;
}
return ($base, [@pres], [@mids], [@posts], $emb_left, $emb_right); }
# Handle text contents.
# Note that (currently) MathML doesn't allow math nested in m:mtext,
# nor in fact any other markup within m:mtext,
# but LaTeXML creates that, if the document is structured that way.
# Here we try to flatten the contents to strings, but keep the math as math
sub pmml_text_aux {
my ($node, %attr) = @_;
return () unless $node;
my $type = $node->nodeType;
if ($type == XML_TEXT_NODE) {
my ($string, %mmlattr) = stylizeContent($node, 0, %attr);
$string =~ s/^\s/$NBSP/; $string =~ s/\s$/$NBSP/;
return ['m:mtext', {%mmlattr}, $string]; }
elsif ($type == XML_DOCUMENT_FRAG_NODE) {
return map { pmml_text_aux($_, %attr) } $node->childNodes; }
elsif ($type == XML_ELEMENT_NODE) {
if (my $font = $node->getAttribute('font')) { $attr{font} = $font; }
if (my $size = $node->getAttribute('fontsize')) { $attr{fontsize} = $size; }
if (my $color = $node->getAttribute('color')) { $attr{color} = $color; }
if (my $bgcolor = $node->getAttribute('backgroundcolor')) { $attr{backgroundcolor} = $bgcolor; }
if (my $opacity = $node->getAttribute('opacity')) { $attr{opacity} = $opacity; }
my $tag = getQName($node);
if ($tag eq 'ltx:Math') {
# [NOTE BUG!!! we're not passing through the context... (but maybe pick it up anyway)]
# If XMath still there, convert it now.
if (my $xmath = $LaTeXML::Post::DOCUMENT->findnode('ltx:XMath', $node)) {
return pmml($xmath); }
# Otherwise, may already have gotten converted ? return that
elsif (my $mml = $LaTeXML::Post::DOCUMENT->findnode('m:math', $node)) {
return $mml->childNodes; }
else { # ???
return (); } }
elsif ($tag eq 'ltx:text') { # ltx:text element is fine, if we can manage the attributes!
return map { pmml_text_aux($_, %attr) } $node->childNodes; }
else {
# We could just recurse on raw content like this, but it loses a lot...
### map(pmml_text_aux($_,%attr), $node->childNodes); }}
# So, let's just include the raw latexml markup, let the xslt convert it
# And hope that the ultimate agent can deal with it!
my ($ignore, %mmlattr) = stylizeContent($node, 0, %attr);
delete $mmlattr{stretchy}; # not useful (not too sure
Warn('unexpected', 'nested-math', $node,
"We're getting m:math nested within an m:mtext")
if $LaTeXML::Post::DOCUMENT->findnodes('.//ltx:Math', $node);
return ['m:mtext', {%mmlattr}, $LaTeXML::Post::DOCUMENT->cloneNode($node, 'nest')]; } }
else {
return (); } }
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Support functions for Content MathML
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
sub cmml_top {
my ($self, $node) = @_;
local $LaTeXML::MathML::STYLE = 'text';
local $LaTeXML::MathML::FONT = find_inherited_attribute($node, 'font');
local $LaTeXML::MathML::SIZE = find_inherited_attribute($node, 'fontsize');
local $LaTeXML::MathML::COLOR = find_inherited_attribute($node, 'color');
local $LaTeXML::MathML::BGCOLOR = find_inherited_attribute($node, 'backgroundcolor');
local $LaTeXML::MathML::OPACITY = find_inherited_attribute($node, 'opacity');
return cmml_contents($node); }
sub cmml {
my ($node) = @_;
if (getQName($node) eq 'ltx:XMRef') {
$node = realize($node); }
# Establish the source XMath node to be used for associating generated MathML
local $LaTeXML::MathML::SOURCENODE = ($node->getAttribute('_pvis') && $node)
|| $LaTeXML::MathML::SOURCENODE;
my $result = cmml_internal($node);
# Associate the generated node with the source XMath node.
$LaTeXML::Post::MATHPROCESSOR->associateNode($result, $LaTeXML::MathML::SOURCENODE);
return $result; }
sub cmml_internal {
my ($node) = @_;
return ['m:merror', {}, ['m:mtext', {}, "Missing Subexpression"]] unless $node;
$node = realize($node) if getQName($node) eq 'ltx:XMRef';
my $tag = getQName($node);
if ($tag eq 'ltx:XMDual') {
my ($content, $presentation) = element_nodes($node);
return cmml($content); }
elsif (($tag eq 'ltx:XMWrap') || ($tag eq 'ltx:XMArg')) { # Only present if parsing failed!
return cmml_contents($node); }
elsif ($tag eq 'ltx:XMApp') {
# Experiment: If XMApp has role ID, we treat it as a "Decorated Symbol"
if (($node->getAttribute('role') || '') eq 'ID') {
return cmml_decoratedSymbol($node); }
else {
my ($op, @args) = element_nodes($node);
if (!$op) {
return ['m:merror', {}, ['m:mtext', {}, "Missing Operator"]]; }
else {
my $rop = realize($op); # NOTE: Could loose open/close on XMRef ???
return &{ lookupContent('Apply', $rop->getAttribute('role'), $rop->getAttribute('meaning')) }($op, @args); } } }
elsif ($tag eq 'ltx:XMTok') {
return &{ lookupContent('Token', $node->getAttribute('role'), $node->getAttribute('meaning')) }($node); }
elsif ($tag eq 'ltx:XMHint') { # ????
return &{ lookupContent('Hint', $node->getAttribute('role'), $node->getAttribute('meaning')) }($node); }
elsif ($tag eq 'ltx:XMArray') {
return &{ lookupContent('Array', $node->getAttribute('role'), $node->getAttribute('meaning')) }($node); }
else {
return ['m:mtext', {}, $node->textContent]; } }
# Convert the contents of a node, which normally should contain a single child.
# It may be empty (assumed to be an error),
# or contain multiple nodes (presumably not properly parsed).
# We really should use m:cerror here, but need to find appropriate csymbol cd:name
sub cmml_contents {
my ($node) = @_;
my ($item, @rest) = element_nodes($node);
if (!$item) {
return ['m:cerror', {}, ['m:csymbol', { cd => 'ambiguous' }, 'missing-subexpression']]; }
elsif (@rest) {
return cmml_unparsed($item, @rest); }
else {
return cmml($item); } }
sub cmml_unparsed {
my (@nodes) = @_;
return ['m:cerror', {},
['m:csymbol', { cd => 'ambiguous' }, 'fragments'],
map { ((getQName($_) eq 'ltx:XMTok') && (($_->getAttribute('role') || 'UNKNOWN') eq 'UNKNOWN')
? ['m:csymbol', { cd => 'unknown' }, $_->textContent]
: cmml($_)) }
@nodes]; }
# Or csymbol if there's some kind of "defining" attribute?
sub cmml_ci {
my ($item) = @_;
if (my $meaning = (ref $item) && $item->getAttribute('meaning')) {
my $cd = $item->getAttribute('omcd') || 'latexml';
return ['m:csymbol', { cd => $cd }, $meaning]; }
else {
my ($content, %mmlattr) = stylizeContent($item, 1);
if (my $mv = $mmlattr{mathvariant}) {
$content = $mv . "-" . $content; }
return ['m:ci', {}, $content]; } }
# Experimental; for an XMApp with role=ID, we treat it as a ci
# or ultimately as csymbol, if it had defining attributes,
# but we format its contents as pmml
sub cmml_decoratedSymbol {
my ($item) = @_;
return ['m:ci', {}, pmml($item)]; }
# Return the NOT of the argument.
sub cmml_not {
my ($arg) = @_;
return ['m:apply', {}, ['m:not', {}], cmml($arg)]; }
sub cmml_synth_not {
my ($op, @args) = @_;
return ['m:apply', {}, ['m:not', {}], ['m:apply', {}, [$op, {}], map { cmml($_) } @args]]; }
# Return the result of converting the arguments, but reversed.
sub cmml_synth_complement {
my ($op, @args) = @_;
return ['m:apply', {}, [$op, {}], map { cmml($_) } reverse(@args)]; }
# Given an XMath node, Make sure it has an id so it can be shared, then convert to cmml
sub cmml_shared {
my ($node) = @_;
$LaTeXML::Post::DOCUMENT->generateNodeID($node, 'sh');
return cmml($node); }
# Given an XMath node, convert to cmml share form
sub cmml_share {
my ($node) = @_;
return ['m:share', { href => '#' . $node->getAttribute('fragid') . $LaTeXML::Post::MATHPROCESSOR->IDSuffix }]; }
sub cmml_or_compose {
my ($operators, @args) = @_;
my @operators = @$operators;
if (scalar(@operators) == 1) {
return ['m:apply', {}, [shift(@operators), {}], map { cmml($_) } @args]; }
else {
my @parts = (['m:apply', {}, [shift(@operators), {}], map { cmml_shared($_) } @args]);
foreach my $op (@operators) {
push(@parts, ['m:apply', {}, [shift(@operators), {}], map { cmml_share($_) } @args]); }
return ['m:or', {}, @parts]; } }
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Tranlators
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Organized according to the MathML Content element lists.
# As a general rule, presentation conversions are based on role
# (eg "Token:role:?"), whereas content conversions are based
# on meaning or name (eg. "Token:?:meaning").
#======================================================================
# Token elements:
# cn, ci, csymbol
DefMathML("Token:?:?", \&pmml_mi, \&cmml_ci);
DefMathML("Token:PUNCT:?", \&pmml_mo, undef);
DefMathML("Token:PERIOD:?", \&pmml_mo, undef);
DefMathML("Token:OPEN:?", \&pmml_mo, undef);
DefMathML("Token:CLOSE:?", \&pmml_mo, undef);
DefMathML("Token:MIDDLE:?", \&pmml_mo, undef);
DefMathML("Token:VERTBAR:?", \&pmml_mo, undef);
DefMathML("Token:ARROW:?", \&pmml_mo, undef);
DefMathML("Token:OVERACCENT:?", \&pmml_mo, undef);
DefMathML("Token:UNDERACCENT:?", \&pmml_mo, undef);
DefMathML("Token:NUMBER:?", \&pmml_mn, sub {
my $n = $_[0]->textContent;
return ['m:cn', { type => ($n =~ /^[+-]?\d+$/ ? 'integer' : 'float') }, $n]; });
DefMathML("Token:?:absent", sub { return ['m:mi', {}] }); # Not m:none!
# Hints normally would have disappeared during parsing
# (turned into punctuation or padding?)
# but if they survive (unparsed?) turn them into space
DefMathML('Hint:?:?', sub {
my ($node) = @_;
if (my $w = $node->getAttribute('width')) {
$w = getXMHintSpacing($w) . "pt";
['m:mspace', { width => $w }]; }
else {
undef } },
sub { undef; }); # Should Disappear from cmml!
# At presentation level, these are essentially adorned tokens.
# args are (accent,base)
DefMathML('Apply:OVERACCENT:?', sub {
my ($accent, $base) = @_;
if (getQName($base) eq 'ltx:XMApp') {
my ($xaccent, $xbase) = element_nodes($base);
if ((getQName($xaccent) eq 'ltx:XMTok')
&& (($xaccent->getAttribute('role') || '') eq 'UNDERACCENT')) {
return ['m:munderover', { accent => 'true', accentunder => 'true' },
pmml($xbase), pmml_scriptsize($xaccent), pmml_scriptsize($accent)]; } }
return ['m:mover', { accent => 'true' }, pmml($base), pmml_scriptsize($accent)]; });
DefMathML('Apply:UNDERACCENT:?', sub {
my ($accent, $base) = @_;
if (getQName($base) eq 'ltx:XMApp') {
my ($xaccent, $xbase) = element_nodes($base);
if ((getQName($xaccent) eq 'ltx:XMTok')
&& (($xaccent->getAttribute('role') || '') eq 'OVERACCENT')) {
return ['m:munderover', { accent => 'true', accentunder => 'true' },
pmml($xbase), pmml_scriptsize($accent), pmml_scriptsize($xaccent)]; } }
return ['m:munder', { accentunder => 'true' }, pmml($base), pmml_scriptsize($accent)]; });
DefMathML('Apply:ENCLOSE:?', sub {
my ($op, $base) = @_;
my $enclosure = $op->getAttribute('enclose');
my $color = $op->getAttribute('color') || $LaTeXML::MathML::COLOR;
return ['m:menclose', { notation => $enclosure, mathcolor => $color },
($color ? ['m:mstyle', { mathcolor => $LaTeXML::MathML::COLOR || 'black' }, pmml($base)]
: pmml($base))]; });
#======================================================================
# Basic Content elements:
# apply, interval, inverse, sep, condition, declare, lambda, compose, ident,
# domain, codomain, image, domainofapplication, piecewise, piece, otherwise
DefMathML("Token:APPLYOP:?", \&pmml_mo, undef); # APPLYOP is (only) \x{2061}; FUNCTION APPLICATION
DefMathML("Token:OPERATOR:?", \&pmml_mo, undef);
DefMathML('Apply:?:?', sub {
my ($op, @args) = @_;
return ['m:mrow', {},
pmml($op), pmml_mo("\x{2061}"), # FUNCTION APPLICATION
pmml_parenthesize(pmml_punctuate($op->getAttribute('separators'), map { pmml($_) } @args),
$op->getAttribute('argopen'), $op->getAttribute('argclose'))]; },
sub {
my ($op, @args) = @_;
return ['m:apply', {}, cmml($op), map { cmml($_) } @args]; });
DefMathML('Apply:COMPOSEOP:?', \&pmml_infix, undef);
DefMathML("Token:DIFFOP:?", \&pmml_mo, undef);
DefMathML("Apply:DIFFOP:?", sub {
my ($op, @args) = @_;
return ['m:mrow', {}, map { pmml($_) } $op, @args]; },
undef);
# In pragmatic CMML, these are containers
DefMathML("Apply:?:open-interval", undef, sub {
my ($op, @args) = @_;
return ['m:interval', { closure => "open" }, map { cmml($_) } @args]; });
DefMathML("Apply:?:closed-interval", undef, sub {
my ($op, @args) = @_;
return ['m:interval', { closure => "closed" }, map { cmml($_) } @args]; });
DefMathML("Apply:?:closed-open-interval", undef, sub {
my ($op, @args) = @_;
return ['m:interval', { closure => "closed-open" }, map { cmml($_) } @args]; });
DefMathML("Apply:?:open-closed-interval", undef, sub {
my ($op, @args) = @_;
return ['m:interval', { closure => "open-closed" }, map { cmml($_) } @args]; });
DefMathML("Token:?:inverse", undef, sub { return ['m:inverse']; });
DefMathML("Token:?:lambda", undef, sub { return ['m:lambda']; });
DefMathML("Token:?:compose", undef, sub { return ['m:compose']; });
DefMathML("Token:?:identity", undef, sub { return ['m:ident']; });
DefMathML("Token:?:domain", undef, sub { return ['m:domain']; });
DefMathML("Token:?:codomain", undef, sub { return ['m:codomain']; });
DefMathML("Token:?:image", undef, sub { return ['m:image']; });
# m:piece, m:piecewise & m:otherwise are generated as part of a cases construct
DefMathML("Array:?:cases", undef, sub {
my ($node) = @_;
my @rows = ();
my @otherwises;
foreach my $row (element_nodes($node)) {
my @items = element_nodes($row);
my $n = scalar(@items);
if ($n == 0) { } # empty row, just skip
elsif ($n == 1) { # No condition? Perhaps it means "otherwise" ?
push(@otherwises, $items[0]); }
elsif ($items[1]->textContent eq 'otherwise') { # more robust test?
push(@otherwises, $items[0]); }
else { # Really, the 2nd cell needs to be "Looked at"; may contain "if","when" or "unless"?!?!
push(@rows, ['m:piece', {}, cmml_contents($items[0]), cmml_contents($items[1])]); } }
if (@otherwises) {
if (@otherwises > 1) {
Warn('unexpected', 'otherwise', $node,
"Cases statement seems to have multiple otherwise clauses",
@otherwises); }
push(@rows, ['m:otherwise', {}, cmml_contents($otherwises[0])]); }
return ['m:piecewise', {}, @rows]; });
#======================================================================
# Arithmetic, Algebra and Logic:
# quotient, factorial, divide, max, min, minus, plus, power, rem, times, root
# gcd, and, or, xor, not, implies, forall, exists, abs, conjugate, arg, real,
# imaginary, lcm, floor, ceiling.
# BRM:
DefMathML("Token:ADDOP:?", \&pmml_mo, undef);
DefMathML("Token:ADDOP:plus", undef, sub { return ['m:plus']; });
DefMathML("Token:ADDOP:minus", undef, sub { return ['m:minus']; });
DefMathML('Apply:ADDOP:?', \&pmml_infix, undef);
DefMathML("Token:MULOP:?", \&pmml_mo, undef);
DefMathML('Apply:MULOP:?', \&pmml_infix, undef);
# REALLY shouldn't conflate "divide" with MULOP, here... Use FRACOP
DefMathML('Apply:?:divide', sub {
my ($op, $num, $den, @more) = @_;
my $style = $op->getAttribute('mathstyle');
my $thickness = $op->getAttribute('thickness');
my $color = $op->getAttribute('color') || $LaTeXML::MathML::COLOR;
my $optext = $op->textContent;
# ['m:mfrac',{($thickness ? (linethickness=>$thickness):()),
# ($style && ($style eq 'inline') ? (bevelled=>'true'):())},
# pmml_smaller($num),pmml_smaller($den)]; });
# Bevelled looks crappy (operands too small) in Mozilla, so just open-code it.
if ($optext || ($style && ($style eq 'inline')) || @more) {
# Shouldn't end up with multiple denominators unless using an infix op w/visible content.
# but better check, rather than have it disappear...
$op = '/' unless $optext;
return pmml_infix($op, $num, $den, @more); }
else {
return ['m:mfrac', { ($thickness ? (linethickness => $thickness) : ()),
($color ? (mathcolor => $color) : ()) },
pmml_smaller($num), pmml_smaller($den)]; } });
DefMathML('Apply:FRACOP:?', sub {
my ($op, $num, $den, @more) = @_;
my $thickness = $op->getAttribute('thickness');
my $color = $op->getAttribute('color') || $LaTeXML::MathML::COLOR;
return ['m:mfrac', { ($thickness ? (linethickness => $thickness) : ()),
($color ? (mathcolor => $color) : ()) },
pmml_smaller($num), pmml_smaller($den)]; });
DefMathML('Apply:MODIFIEROP:?', \&pmml_infix, undef);
DefMathML("Token:MODIFIEROP:?", \&pmml_mo, undef);
DefMathML('Apply:MIDDLE:?', \&pmml_infix, undef);
DefMathML("Token:SUPOP:?", \&pmml_mo, undef);
DefMathML('Apply:SUPERSCRIPTOP:?', \&pmml_script, undef);
DefMathML('Apply:SUBSCRIPTOP:?', \&pmml_script, undef);
DefMathML('Token:SUPERSCRIPTOP:?', undef, sub {
return ['m:csymbol', { cd => 'ambiguous' }, 'superscript']; });
DefMathML('Token:SUBSCRIPTOP:?', undef, sub {
return ['m:csymbol', { cd => 'ambiguous' }, 'subscript']; });
DefMathML('Apply:POSTFIX:?', sub { # Reverse presentation, no @apply
return ['m:mrow', {}, pmml($_[1]), pmml($_[0])]; });
DefMathML("Token:POSTFIX:?", sub { pmml_mo($_[0], lpadding => '-4pt', rpadding => '1pt'); }, undef);
DefMathML('Apply:?:square-root',
sub {
my $color = $_[0]->getAttribute('color') || $LaTeXML::MathML::COLOR;
return ['m:msqrt', { ($color ? (mathcolor => $color) : ()) }, pmml($_[1])]; },
sub { return ['m:apply', {}, ['m:root', {}], cmml($_[1])]; });
DefMathML('Apply:?:nth-root',
sub {
my $color = $_[0]->getAttribute('color') || $LaTeXML::MathML::COLOR;
return ['m:mroot', { ($color ? (mathcolor => $color) : ()) }, pmml($_[2]), pmml_smaller($_[1])]; },
sub { return ['m:apply', {}, ['m:root', {}], ['m:degree', {}, cmml($_[1])], cmml($_[2])]; });
# Note MML's distinction between quotient and divide: quotient yeilds an integer
DefMathML("Token:?:quotient", undef, sub { return ['m:quotient']; });
DefMathML("Token:?:factorial", undef, sub { return ['m:factorial']; });
DefMathML("Token:?:divide", undef, sub { return ['m:divide']; });
DefMathML("Token:?:maximum", undef, sub { return ['m:max']; });
DefMathML("Token:?:minimum", undef, sub { return ['m:min']; });
DefMathML("Token:?:minus", undef, sub { return ['m:minus']; });
DefMathML("Token:?:uminus", undef, sub { return ['m:uminus']; });
DefMathML("Token:?:plus", undef, sub { return ['m:plus']; });
DefMathML("Token:?:power", undef, sub { return ['m:power']; });
DefMathML("Token:?:remainder", undef, sub { return ['m:rem']; });
DefMathML("Token:?:times", undef, sub { return ['m:times']; });
DefMathML("Token:?:gcd", undef, sub { return ['m:gcd']; });
DefMathML("Token:?:and", undef, sub { return ['m:and']; });
DefMathML("Token:?:or", undef, sub { return ['m:or']; });
DefMathML("Token:?:xor", undef, sub { return ['m:xor']; });
DefMathML("Token:?:not", undef, sub { return ['m:not']; });
DefMathML("Token:?:implies", undef, sub { return ['m:implies']; });
DefMathML("Token:?:forall", undef, sub { return ['m:forall']; });
DefMathML("Token:?:exists", undef, sub { return ['m:exists']; });
DefMathML("Token:?:absolute-value", undef, sub { return ['m:abs']; });
DefMathML("Token:?:conjugate", undef, sub { return ['m:conjugate']; });
DefMathML("Token:?:argument", undef, sub { return ['m:arg']; });
DefMathML("Token:?:real-part", undef, sub { return ['m:real']; });
DefMathML("Token:?:imaginary-part", undef, sub { return ['m:imaginary']; });
DefMathML("Token:?:lcm", undef, sub { return ['m:lcm']; });
DefMathML("Token:?:floor", undef, sub { return ['m:floor']; });
DefMathML("Token:?:ceiling", undef, sub { return ['m:ceiling']; });
#======================================================================
# Relations:
# eq, neq, gt, lt, geq, leq, equivalent, approx, factorof
DefMathML("Token:RELOP:?", \&pmml_mo);
DefMathML("Token:?:equals", undef, sub { return ['m:eq']; });
DefMathML("Token:?:not-equals", undef, sub { return ['m:neq']; });
DefMathML("Token:?:greater-than", undef, sub { return ['m:gt']; });
DefMathML("Token:?:less-than", undef, sub { return ['m:lt']; });
DefMathML("Token:?:greater-than-or-equals", undef, sub { return ['m:geq']; });
DefMathML("Token:?:less-than-or-equals", undef, sub { return ['m:leq']; });
DefMathML("Token:?:equivalent-to", undef, sub { return ['m:equivalent']; });
DefMathML("Token:?:approximately-equals", undef, sub { return ['m:approx']; });
DefMathML("Apply:?:not-approximately-equals", undef, sub {
my ($op, @args) = @_;
return cmml_synth_not('m:approx', @args); });
DefMathML("Apply:?:less-than-or-approximately-equals", undef, sub {
my ($op, @args) = @_;
return cmml_or_compose(['m:lt', 'm:approx'], @args); });
DefMathML("Token:?:factor-of", undef, sub { return ['m:factorof']; });
DefMathML("Token:METARELOP:?", \&pmml_mo);
DefMathML('Apply:RELOP:?', \&pmml_infix);
DefMathML('Apply:METARELOP:?', \&pmml_infix);
# Top level relations
DefMathML('Apply:?:formulae', sub {
my ($op, @elements) = @_;
return pmml_punctuate($op->getAttribute('separators'), map { pmml($_) } @elements); },
sub {
my ($op, @elements) = @_;
return ['m:apply', {},
['m:csymbol', { cd => 'ambiguous' }, 'formulae-sequence'],
map { cmml($_) } @elements];
});
# TRICKY: How should this get converted to cmml ???
# DefMathML('Apply:?:multirelation',
# sub {
# my($op,@elements)=@_;
# pmml_row(map(pmml($_),@elements)); },
# sub {
# my($op,@elements)=@_;
# my @stuff=();
# my $a = cmml(shift(@elements));
# return $a unless @elements;
# while(@elements){
# my $rel = cmml(shift(@elements));
# my $b=cmml(shift(@elements));
# my $id = generate_id('sh');
# $$b[1]{'xml:id'}=$id;
# push(@stuff,['m:apply',{},$rel,$a,$b]);
# $a = ['m:share',{href=>'#'.$id}]; }
# (scalar(@stuff) > 1 ? ['m:and',{},@stuff] : $stuff[0]); }
# );
DefMathML('Apply:?:multirelation',
sub {
my ($op, @elements) = @_;
# This presumes that the relational operators scattered through here
# will be recognized as such by pmml and turned into m:mo
return pmml_row(map { pmml($_) } @elements); },
sub {
my ($op, @elements) = @_;
my $lhs = cmml(shift(@elements));
return $lhs unless @elements;
my @relations = ();
while (@elements) {
my $rel = shift(@elements);
my $rhs = shift(@elements);
push(@relations, ['m:apply', {}, cmml($rel), $lhs, cmml_shared($rhs)]);
$lhs = cmml_share($rhs); }
return (scalar(@relations) > 1 ? ['m:apply', {}, ['m:and', {}], @relations] : $relations[0]); }
);
#======================================================================
# Calculus and Vector Calculus:
# int, diff, partialdiff, lowlimit, uplimit, bvar, degree,
# divergence, grad, curl, laplacian.
DefMathML("Token:INTOP:?", \&pmml_bigop);
DefMathML("Token:LIMITOP:?", \&pmml_mo);
DefMathML('Apply:ARROW:?', \&pmml_infix);
DefMathML("Token:?:integral", undef, sub { return ['m:int']; });
DefMathML("Token:?:differential", undef, sub { return ['m:diff']; });
DefMathML("Token:?:partial-differential", undef, sub { return ['m:partialdiff']; });
# lowlimit, uplimit, degree ?
DefMathML("Token:?:divergence", undef, sub { return ['m:divergence']; });
DefMathML("Token:?:gradient", undef, sub { return ['m:grad']; });
DefMathML("Token:?:curl", undef, sub { return ['m:curl']; });
DefMathML("Token:?:laplacian", undef, sub { return ['m:laplacian']; });
#======================================================================
# Theory of Sets,
# set, list, union, intersect, in, notin, subset, prsubset, notsubset, notprsubset,
# setdiff, card, cartesianproduct.
DefMathML("Apply:?:set", undef, sub {
my ($op, @args) = @_;
return ['m:set', {}, map { cmml($_) } @args]; });
DefMathML("Apply:?:list", undef, sub {
my ($op, @args) = @_;
return ['m:list', {}, map { cmml($_) } @args]; });
DefMathML("Token:?:union", undef, sub { return ['m:union']; });
DefMathML("Token:?:intersection", undef, sub { return ['m:intersect']; });
DefMathML("Token:?:element-of", undef, sub { return ['m:in']; });
DefMathML("Token:?:not-element-of", undef, sub { return ['m:notin']; });
DefMathML("Apply:?:contains", undef, sub {
my ($op, @args) = @_;
return cmml_synth_complement('m:in', @args); });
DefMathML("Apply:?:not-contains", undef, sub {
my ($op, @args) = @_;
return cmml_synth_complement('m:notin', @args); });
DefMathML("Token:?:subset-of", undef, sub { return ['m:subset']; });
DefMathML("Token:?:subset-of-or-equals", undef, sub { return ['m:subset']; });
DefMathML("Token:?:subset-of-and-not-equals", undef, sub { return ['m:prsubset']; });
DefMathML("Apply:?:superset-of", undef, sub {
my ($op, @args) = @_;
return cmml_synth_complement('m:subset', @args); });
DefMathML("Apply:?:superset-of-or-equals", undef, sub {
my ($op, @args) = @_;
return cmml_synth_complement('m:subset', @args); });
DefMathML("Apply:?:superset-of-and-not-equals", undef, sub {
my ($op, @args) = @_;
return cmml_synth_complement('m:prsubset', @args); });
DefMathML("Token:?:set-minus", undef, sub { return ['m:setdiff']; });
DefMathML("Token:?:cardinality", undef, sub { return ['m:card']; });
DefMathML("Token:?:cartesian-product", undef, sub { return ['m:cartesianproduct']; });
#======================================================================
# Sequences and Series:
# sum, product, limit, tendsto
# (but see calculus for limit too!!)
DefMathML("Token:BIGOP:?", \&pmml_bigop);
DefMathML("Token:SUMOP:?", \&pmml_bigop);
# ?? or something....
sub pmml_summation {
my ($op, $body) = @_;
return ['m:mrow', {}, pmml($op), pmml($body)]; }
DefMathML('Apply:BIGOP:?', \&pmml_summation);
DefMathML('Apply:INTOP:?', \&pmml_summation);
DefMathML('Apply:SUMOP:?', \&pmml_summation);
DefMathML('Apply:?:limit-from', sub {
my ($op, $arg, $dir) = @_;
['m:mrow', {}, pmml($arg), pmml($dir)]; });
DefMathML('Apply:?:annotated', sub {
my ($op, $var, $annotation) = @_;
return ['m:mrow', {}, pmml($var),
['m:mspace', { width => 'veryverythickmathspace' }],
pmml($annotation)]; });
DefMathML('Apply:?:evaluated-at', sub {
my ($op, $expr, $value1, $value2) = @_;
if ($value2) {
return ['m:msubsup', {},
pmml_parenthesize(pmml($expr), '', '|'),
pmml_scriptsize($value1), pmml_scriptsize($value2)]; }
else {
return ['m:msub', {},
pmml_parenthesize(pmml($expr), '', '|'),
pmml_scriptsize($value1)]; } });
DefMathML("Token:?:sum", undef, sub { return ['m:sum']; });
DefMathML("Token:?:prod", undef, sub { return ['m:prod']; });
DefMathML("Token:?:limit", undef, sub { return ['m:limit']; });
DefMathML("Token:?:tends-to", undef, sub { return ['m:tendsto']; });
#======================================================================
# Elementary Classical Functions,
# exp, ln, log, sin, cos tan, sec, csc, cot, sinh, cosh, tanh, sech, csch, coth,
# arcsin, arccos, arctan, arccosh, arccot, arccoth, arccsc, arccsch, arcsec, arcsech,
# arcsinh, arctanh
DefMathML("Token:?:exponential", undef, sub { return ['m:exp']; });
DefMathML("Token:?:natural-logarithm", undef, sub { return ['m:ln']; });
DefMathML("Token:?:logarithm", undef, sub { return ['m:log']; });
DefMathML("Token:?:sine", undef, sub { return ['m:sin']; });
DefMathML("Token:?:cosine", undef, sub { return ['m:cos']; });
DefMathML("Token:?:tangent", undef, sub { return ['m:tan']; });
DefMathML("Token:?:secant", undef, sub { return ['m:sec']; });
DefMathML("Token:?:cosecant", undef, sub { return ['m:csc']; });
DefMathML("Token:?:cotangent", undef, sub { return ['m:cot']; });
DefMathML("Token:?:hyperbolic-sine", undef, sub { return ['m:sinh']; });
DefMathML("Token:?:hyperbolic-cosine", undef, sub { return ['m:cosh']; });
DefMathML("Token:?:hyperbolic-tangent", undef, sub { return ['m:tanh']; });
DefMathML("Token:?:hyperbolic-secant", undef, sub { return ['m:sech']; });
DefMathML("Token:?:hyperbolic-cosecant", undef, sub { return ['m:csch']; });
DefMathML("Token:?:hyperbolic-cotantent", undef, sub { return ['m:coth']; });
DefMathML("Token:?:inverse-sine", undef, sub { return ['m:arcsin']; });
DefMathML("Token:?:inverse-cosine", undef, sub { return ['m:arccos']; });
DefMathML("Token:?:inverse-tangent", undef, sub { return ['m:arctan']; });
DefMathML("Token:?:inverse-secant", undef, sub { return ['m:arcsec']; });
DefMathML("Token:?:inverse-cosecant", undef, sub { return ['m:arccsc']; });
DefMathML("Token:?:inverse-cotangent", undef, sub { return ['m:arccot']; });
DefMathML("Token:?:inverse-hyperbolic-sine", undef, sub { return ['m:arcsinh']; });
DefMathML("Token:?:inverse-hyperbolic-cosine", undef, sub { return ['m:arccosh']; });
DefMathML("Token:?:inverse-hyperbolic-tangent", undef, sub { return ['m:arctanh']; });
DefMathML("Token:?:inverse-hyperbolic-secant", undef, sub { return ['m:arcsech']; });
DefMathML("Token:?:inverse-hyperbolic-cosecant", undef, sub { return ['m:arccsch']; });
DefMathML("Token:?:inverse-hyperbolic-cotangent", undef, sub { return ['m:arccoth']; });
#======================================================================
# Statistics:
# mean, sdev, variance, median, mode, moment, momentabout
DefMathML("Token:?:mean", undef, sub { return ['m:mean']; });
DefMathML("Token:?:standard-deviation", undef, sub { return ['m:sdev']; });
DefMathML("Token:?:variance", undef, sub { return ['m:var']; });
DefMathML("Token:?:median", undef, sub { return ['m:median']; });
DefMathML("Token:?:mode", undef, sub { return ['m:mode']; });
DefMathML("Token:?:moment", undef, sub { return ['m:moment']; });
# momentabout ???
#======================================================================
# Linear Algebra:
# vector, matrix, matrixrow, determinant, transpose, selector,
# vectorproduct, scalarproduct, outerproduct.
DefMathML("Apply:?:vector", undef, sub {
my ($op, @args) = @_;
return ['m:vector', {}, map { cmml($_) } @args]; });
#DefMathML("Token:?:matrix", undef, sub { return ['m:matrix']; });
DefMathML("Token:?:determinant", undef, sub { return ['m:determinant']; });
DefMathML("Token:?:transpose", undef, sub { return ['m:transpose']; });
DefMathML("Token:?:selector", undef, sub { return ['m:selector']; });
DefMathML("Token:?:vector-product", undef, sub { return ['m:vectorproduct']; });
DefMathML("Token:?:scalar-product", undef, sub { return ['m:scalarproduct']; });
DefMathML("Token:?:outer-product", undef, sub { return ['m:outerproduct']; });
# So by default any Array is a Matrix? hmmm....
DefMathML("Array:?:?", undef, sub {
my ($node) = @_;
return ['m:matrix', {},
map { ['m:matrixrow', {}, map { cmml_contents($_) } element_nodes($_)] }
element_nodes($node)]; });
#======================================================================
# Semantic Mapping Elements
# annotation, semantics, annotation-xml
#======================================================================
# Constant and Symbol Elements
# integers, reals, rationals, naturalnumbers, complexes, primes,
# exponentiale, imaginaryi, notanumber, true, false, emptyset, pi,
# eulergamma, infinity
DefMathML("Token:ID:integers", undef, sub { return ['m:integers']; });
DefMathML("Token:ID:reals", undef, sub { return ['m:reals']; });
DefMathML("Token:ID:rationals", undef, sub { return ['m:rationals']; });
DefMathML("Token:ID:numbers", undef, sub { return ['m:naturalnumbers']; });
DefMathML("Token:ID:complexes", undef, sub { return ['m:complexes']; });
DefMathML("Token:ID:primes", undef, sub { return ['m:primes']; });
DefMathML("Token:ID:exponential-e", undef, sub { return ['m:exponentiale']; });
DefMathML("Token:ID:imaginary-i", undef, sub { return ['m:imaginaryi']; });
DefMathML("Token:ID:notanumber", undef, sub { return ['m:notanumber']; });
DefMathML("Token:ID:true", undef, sub { return ['m:true']; });
DefMathML("Token:ID:false", undef, sub { return ['m:false']; });
DefMathML("Token:ID:empty-set", undef, sub { return ['m:emptyset']; });
DefMathML("Token:ID:circular-pi", undef, sub { return ['m:pi']; });
DefMathML("Token:ID:Euler-constant", undef, sub { return ['m:eulergamma']; });
DefMathML("Token:ID:infinity", undef, sub { return ['m:infinity']; });
#======================================================================
# Purely presentational constructs.
# An issue here:
# Some constructs are pretty purely presentational. Hopefully, these would
# only appear in XWrap's or in the presentation branch of an XMDual, so we won't
# attempt to convert them to content. But if we do, should we warn?
DefMathML('Apply:FENCED:?', sub {
my ($op, @elements) = @_;
return pmml_parenthesize(pmml_punctuate($op->getAttribute('separators'),
map { pmml($_) } @elements),
$op->getAttribute('argopen'), $op->getAttribute('argclose')); });
# Note how annoyingly MML's arrays don't change the style the same
# way TeX does!
# This stacks any number of items, one per row.
DefMathML('Apply:STACKED:?', sub {
my ($op, @items) = @_;
my $c = $op->getAttribute('class');
my $align = $c && ($c eq 'alignl' ? 'left'
: ($c eq 'alignc' ? 'center'
: ($c eq 'alignl' ? 'right' : undef)));
my $stack = ['m:mtable', { rowspacing => "0.2ex", columnspacing => "0.4em",
($align ? (columnalign => $align) : ()) },
map { ['m:mtr', {}, ['m:mtd', {}, pmml($_)]] } @items];
if ($LaTeXML::MathML::STYLE =~ /^(text|script)$/) {
return ['m:mstyle', { scriptlevel => '+1' }, $stack]; }
else {
return $stack; } });
# ================================================================================
# More exotic things
# ================================================================================
# cfrac! Ugh!
# Have to deal w/ screwy structure:
# If denom is a sum/diff then last summand can be: cdots, cfrac
# or invisibleTimes of cdots and something which could also be a cfrac!
# There is some really messy manipulation of display/text style...probably not all correct.
sub do_cfrac {
my ($numer, $denom) = @_;
if (getQName($denom) eq 'ltx:XMApp') { # Denominator is some kind of application
my ($denomop, @denomargs) = element_nodes($denom);
if ((($denomop->getAttribute('role') || '') eq 'ADDOP') # Is it a sum or difference?
|| (($denomop->textContent || '') eq "\x{22EF}")) { # OR a \cdots
my $last = pop(@denomargs); # Check last operand in denominator.
# this is the current contribution to the cfrac (if we match the last term)
my $curr;
{ local $LaTeXML::MathML::STYLE = 'text';
$curr = ['m:mfrac', {}, pmml($numer),
['m:mrow', {},
(@denomargs > 1 ? pmml_infix($denomop, @denomargs) : pmml($denomargs[0])),
pmml($denomop)]]; }
$curr = ['m:mstyle', { displaystyle => 'true' }, $curr]
unless $LaTeXML::MathML::STYLE eq 'display';
if (($last->textContent || '') eq "\x{22EF}") { # Denom ends w/ \cdots
return ($curr, pmml($last)); } # bring dots up to toplevel
elsif (getQName($last) eq 'ltx:XMApp') { # Denom ends w/ application --- what kind?
my ($lastop, @lastargs) = element_nodes($last);
if (($lastop->getAttribute('meaning') || '') eq 'continued-fraction') { # Denom ends w/ cfrac, pull it to toplevel
return ($curr, do_cfrac(@lastargs)); }
elsif ((($lastop->textContent || '') eq "\x{2062}") # Denom ends w/ * (invisible)
&& (scalar(@lastargs) == 2) && (($lastargs[0]->textContent || '') eq "\x{22EF}")) {
my ($n, $d);
$n = pmml($lastargs[0]);
{ local $LaTeXML::MathML::STYLE = 'text'; # Trick into being treated as display.
$d = pmml($lastargs[1]) }
return ($curr, $n, $d); } } } }
## (['m:mfrac',{},pmml_smaller($numer),pmml_smaller($denom)]); }
if ($LaTeXML::MathML::STYLE eq 'display') {
return ['m:mfrac', {}, pmml_smaller($numer), pmml_smaller($denom)]; }
else {
local $LaTeXML::MathML::STYLE = 'display'; # Trick into being treated as display.
return (['m:mstyle', { displaystyle => 'true' },
['m:mfrac', {}, pmml_smaller($numer), pmml_smaller($denom)]]); } }
DefMathML('Apply:?:continued-fraction', sub {
my ($op, $numer, $denom) = @_;
my $style = $op->getAttribute('mathstyle') || 'display';
if ($style eq 'inline') {
return pmml_row(do_cfrac($numer, $denom)); }
else {
local $LaTeXML::MathML::STYLE = 'text';
return ['m:mfrac', {}, pmml($numer), pmml($denom)]; } });
#================================================================================
1;
__END__
=pod
=head1 NAME
C<LaTeXML::Post::MathML> - Post-Processing modules for converting math to MathML.
=head1 SYNOPSIS
C<LaTeXML::Post::MathML> is the abstract base class for the MathML Postprocessor;
C<LaTeXML::Post::MathML::Presentation> and C<LaTeXML::Post::MathML::Content>
convert XMath to either Presentation or Content MathML, or with that format
as the principle branch for Parallel markup.
=head1 DESCRIPTION
The conversion is carried out primarly by a tree walk of the C<XMath> expression;
appropriate handlers are selected and called depending on the operators and forms encountered.
Handlers can be defined on applications of operators, or on tokens;
when a token is applied, it's application handler takes precedence over it's token handler
=head2 C<< DefMathML($key,$presentation,$content); >>
Defines presentation and content handlers for C<$key>.
C<$key> is of the form C<TYPE:ROLE:MEANING>, where
TYPE : is one either C<Token> or C<Apply> (or C<Hint> ?)
ROLE : is a grammatical role (on XMath tokens)
MEANING : is the meaning attribute (on XMath tokens)
Any of these can be C<?> to match any role or meaning;
matches of both are preferred, then match of meaning
or role, or neither.
The subroutine handlers for presentation and content are given
by C<$presentation> and C<$content>, respectively.
Either can be C<undef>, in which case some other matching
handler will be invoked.
For C<Token> handlers, the arguments passed are the token node;
for C<Apply> handler, the arguments passed are the operator node
and any arguments.
However, it looks like some C<TOKEN> handlers are being defined
to take C<$content,%attributes> being the string content of the token,
and the token's attributes!
=head2 Presentation Conversion Utilties
=over
=item C<< $mmlpost->pmml_top($node,$style); >>
This is the top-level converter applied to an C<XMath> node.
It establishes a local context for font, style, size, etc.
It generally does the bulk of the work for a PresentationMathML's C<translateNode>,
although the latter wraps the actual C<m:math> element around it.
(C<style> is display or text).
=item C<pmml($node)>, C<pmml_smaller($node)>, C<pmml_scriptsizsize($node)>
Converts the C<XMath> C<$node> to Presentation MathML.
The latter two are used when the context calls for smaller (eg. fraction parts)
or scriptsize (eg sub or superscript) size or style, so that the size encoded
within C<$node> will be properly accounted for.
=item C<pmml_mi($node,%attributes)>, C<pmml_mn($node,%attributes)>, C<pmml_mo($node,%attributes)>
These are C<Token> handlers, to create C<m:mi>, C<m:mn> and C<m:mo> elements,
respectively. When called as a handler, they will be supplied only with an C<XMath>
node (typically an C<XMTok>). For convenient reuse, these functions may also be called
on a 'virtual' token: with C<$node> being a string (that would have been the text
content of the C<XMTok>), and the C<%attributes> that would have been the token's attributes.
=item C<pmml_infix($op,@args)>, C<pmml_script($op,@args)>, C<pmml_bigop($op,@args)>
These are C<Apply> handlers, for handling general infix, sub or superscript,
or bigop (eg. summations) constructs. They are called with the operator
token, followed by the arguments; all are C<XMath> elements.
=item C<pmml_row(@items)>
This wraps an C<m:mrow> around the already converted C<@items> if neeed;
That is, if there is only a single item it is returned without the C<m:mrow>.
=item C<pmml_unrow($pmml)>
This perverse utility takes something that has already been converted
to Presentation MathML. If the argument is an C<m:mrow>, it returns a list of the
mathml elements within that row, otherwise it returns a list containing
the single element C<$pmml>.
=item C<pmml_parenthesize($item,$open,$close)>
This utility parenthesizes the (already converted MathML) C<$item> with the string delimiters
C<$open> and C<$close>. These are converted to an C<m:mrow> with C<m:mo> for the fences,
unless the C<usemfenced> switch is set, in which case C<m:mfenced> is used.
=item C<pmml_punctuate($separators,@items) >
This utility creates an C<m:mrow> by interjecting the punctuation
between suceessive items in the list of already converted C<@items>.
If there are more than one character in C<$separators> the first
is used between the first pair, the next between the next pair;
if the separators is exhausted, the last is repeated between remaining pairs.
C<$separators> defaults to (repeated) comma.
=back
=head2 Content Conversion Utilties
=over
=item C<$mmlpost->cmml_top($node); >
This is the top-level converter applied to an C<XMath> node.
It establishes a local context for font, style, size, etc (were it needed).
It generally does the bulk of the work for a ContentMathML's C<translateNode>,
although the latter wraps the actual C<m:math> element around it.
=item C<cmml($node)>
Converts the C<XMath> C<$node> to Content MathML.
=item C<cmml_ci($token)>
Converts the C<XMath> token to an C<m:ci>.
(This may evolve to generate a C<m:csymbol>, under appropriate circumstances)
=item C<cmml_decoratedSymbol($item)>
Similar to C<cmml_ci>, but used when an operator is itself, apparently, an application.
This converts C<$item> to Presentation MathML to use for the content of the C<m:ci>.
=item C<cmml_not($arg)>
Construct the not of the argument C<$arg>.
=item C<cmml_synth_not($op,@args)>
Synthesize an operator by applying C<m:not> to another operator (C<$op>) applied to its C<@args>
(C<XMath> elements that will be converted to Content MathML).
This is useful to define a handler for, eg., c<not-approximately-equals> in terms
of c<m:approx>.
=item C<cmml_synth_complement($op,@args)>
Synthesize an operator by applying a complementary operator (C<$op>) to the reverse of its C<@args>
(C<XMath> elements that will be converted to Content MathML).
This is useful to define a handler for, eg. C<superset-of-or-equals> using C<m:subset>.
=item C<cmml_or_compose($operators,@args)>
Synthesize an operator that stands for the C<or> of several other operators
(eg. c<less-than-or-similar-to-or-approximately-equals>) by composing it
of the C<m:or> of applying each of C<m:less> and C<m:approx> to the arguments.
The first operator is applied to the converted arguments, while the rest
are applied to C<m:share> elements referring to the previous ones.
=item C<cmml_share($node)>
Converts the C<XMath> C<$node> to Content MathML, after assuring that it has an id,
so that it can be shared.
=item C<cmml_shared($node)>
Generates a C<m:share> element referting to C<$node>, which should have
an id (such as after calling C<cmml_share>).
=back
=head1 Math Processors, Generally.
We should probably formalize the idea of a Math Processor as an
abstract class, but let this description provide a starting overview.
A MathProcessor follows the API of C<LaTeXML::Post> processors, by
handling C<process>, which invokes C<processNode> on all C<Math> nodes;
That latter inserts the result of either C<translateNode> or
C<translateParallel>, applied to the C<XMath> representation, into the C<Math> node.
Parallel translation is done whenever additional MathProcessors have
been specified, via the C<setParallel> method; these are simply other
MathProcessors following the same API.
=cut
|