This file is indexed.

/usr/share/perl5/LaTeXML/Package/amsmath.sty.ltxml is in latexml 0.8.0-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
# -*- CPERL -*-
# /=====================================================================\ #
# |  amsmath                                                            | #
# | Implementation 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::Package::Pool;
use strict;
use warnings;
use LaTeXML::Package;

#**********************************************************************
# See amsldoc

# Currently only a random collection of things I need for DLMF chapters.
# Eventually, go through the doc and implement it all.
#**********************************************************************

# TODO:
#   Interesting options for limits placement
#   And TESTING!!!!!

# sub-packages:
RequirePackage('amsbsy');
RequirePackage('amstext');
RequirePackage('amsopn');

# Optional packages
#   amscd
#   amsxtra

DefMacroI('\AmSfont', undef, Tokens());
DefMacroI('\AmS',     undef, "AmS");

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Section 3:  Displayed equations
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# General implementation comments:
#   Some of these environments are intended for breaking up single equations
# into multiple lines, while others are for presenting several equations in a group.
# [some environments may be more ambiguous]
# In any case, there may be specific relative alignment expected between the lines.
#
# Our primary objective, in LaTeXML, is to get at the semantics of the document,
# and secondarily, to preserve enough of the author's intent to generate
# presentation MathML that has the originally desired appearance.

# Thus, our first concern is to recognize the portions of the input which represent
# individual equations.  These sequences can then be passed to the math parser
# and hopefully recognized.
#
# We'll try to leverage the equationgroup/equation/MathFork arrangement
# to achieve the secondary objective.
# Where this doesn't work out, we'll insert additional hint or punctuation tokens
# that indicate the requested alignment points or linebreaks.
#  Currently hints are discarded before parsing.

Let('\notag', '\nonumber');

## Seemingly wants digested arg? (ie. expanded before seeing arg)
### DefConstructor('\tag OptionalMatch:* {}', '',
DefConstructor('\tag OptionalMatch:* Digested', '',
  afterDigest => sub {
    AssignValue(EQUATIONROW_NUMBER => ToString($_[2]), 'global'); },
  mode => 'text');

# Note that \intertext may or may not be preceded by an explicit \\, with no apparent difference in TeX.
# latexml, however, can end up with 2, which end up incrementing coutners twice!
# Of course, that means we're doing something quite wrong, but we've at least got to recover the effect!!!
DefMacro('\@ams@intertext{}',
  '\@ams@newline\multicolumn{\@alignment@ncolumns}{l}{\@@ams@intertext{#1}}\nonumber\@ams@newline');
DefConstructor('\@@ams@intertext{}',
  "<ltx:p class='ltx_intertext'>#1</ltx:p>", mode => 'text');

DefMacroI('\@ams@newline', undef, sub {
    my ($gullet) = @_;
    readNewlineArgs($gullet);
    $gullet->skipSpaces();
    my $next = $gullet->readToken();
    if ($next && $next->equals(T_CS('\intertext'))) {
      ($next); }
    else {
      (T_CS('\@alignment@newline@noskip'), $next); } });

sub amsalignBindings {
  my ($template, %properties) = @_;
  AssignValue(Alignment => LaTeXML::Core::Alignment->new(
      template => $template,
      openContainer => sub { my %attr = RefStepID('@equationgroup');
        $attr{'xml:id'} = $attr{id}; delete $attr{id};
        $_[0]->openElement('ltx:equationgroup', %attr, @_[1 .. $#_]); },
      closeContainer => sub { $_[0]->closeElement('ltx:equationgroup'); },
      openRow        => sub { $_[0]->openElement('ltx:equation', @_[1 .. $#_]); },
      closeRow       => sub { $_[0]->closeElement('ltx:equation'); },
      openColumn     => sub { $_[0]->openElement('ltx:_Capture_', @_[1 .. $#_]); },
      closeColumn    => sub { $_[0]->closeElement('ltx:_Capture_'); },
      properties => {%properties}));
  Let(T_ALIGN,       '\@alignment@align');
  Let("\\\\",        '\@ams@newline');
  Let('\cr',         '\@alignment@cr');
  Let('\@open@row',  '\@equationgroup@open@row');
  Let('\@close@row', '\@equationgroup@close@row');
  Let('\intertext',  '\@ams@intertext');
  return; }

#======================================================================
# Section 3.1 introduction

#======================================================================
# Section 3.2 Single equations

#  equation, equation*

# Note that amsmath respects \nonumber !!!!
# So, we've got to delay the properties
DefEnvironment('{equation}',
  "<ltx:equation xml:id='#id' refnum='#refnum' frefnum='#frefnum' rrefnum='#rrefnum'>"
    . "<ltx:Math mode='display'>"
    . "<ltx:XMath>"
    . "#body"
    . "</ltx:XMath>"
    . "</ltx:Math>"
    . "</ltx:equation>",
  mode => 'display_math',
  # NOT this
  #  properties => sub { RefStepCounter('equation') },
  # BUT this:
  beforeDigest => sub {
    AssignValue(EQUATIONROW_NUMBER => '_AUTO_', 'global');
    return; },
  afterDigest => sub {
    my ($stomach, $whatsit) = @_;
    my $num   = LookupValue('EQUATIONROW_NUMBER');
    my %props = ();
    if    (!$num)            { %props = RefStepID('equation'); }
    elsif ($num eq '_AUTO_') { %props = RefStepCounter('equation'); }
    else {
      %props = RefStepID('equation');
      $props{refnum} = $num; }
    $whatsit->setProperties(%props);
    return; },
  locked => 1);

#======================================================================
# Section 3.3 Split equations without alignment

# Multiline is for SINGLE equations,
# but split on multiple lines, using \\ to separate lines. (there are no &)
# Justifies the 1st line left, last line right, and middle ones centered.
# Very useful when you are trying to fit a long equation into a known space,
# but preserving the alignment seems less useful in the vaguer XML context,
# particularly since there's no real alignment of columns that convey symmetry.
# So... For now, we'll just turn into a single equation, ignoring the line breaks.
# There is at most a single equation number, so MathFork isn't strictly required
# here, but could be useful...
DefEnvironment('{multline}',
  "<ltx:equation refnum='#refnum' frefnum='#frefnum' rrefnum='#rrefnum' xml:id='#id'>"
    . "<ltx:Math mode='display'>"
    . "<ltx:XMath>#body</ltx:XMath>"
    . "</ltx:Math>"
    . "</ltx:equation>",
  mode => 'display_math',
  beforeDigest => sub { Let(T_MATH, '\@dollar@in@mathmode'); },
  properties => sub { RefStepCounter('equation') });
DefEnvironment('{multline*}',
  "<ltx:equation>"
    . "<ltx:Math mode='display'>"
    . "<ltx:XMath>#body</ltx:XMath>"
    . "</ltx:Math>"
    . "</ltx:equation>",
  beforeDigest => sub { Let(T_MATH, '\@dollar@in@mathmode'); },
  mode => 'display_math');

#======================================================================
# Section 3.4 Split equations with alignment

# split is for SINGLE equations,
# split is used WITHIN other math environments to provide line breaks and alignment.
# Since it's already within math, the MathFork branching doesn't work here.
# Should we use a math alignment stucture?
# [in which case it is XMDual sufficient to capture the high-level
# presentation vs. semantic?]
# Or just turn the markup into XMHint's; effectively ignoring them.
# The latter, for now.
DefEnvironment('{split}',
  "<ltx:XMHint name='split-begin'/>#body<ltx:XMHint name='split-end'/>",
  beforeDigest => sub {
    # Just dummy up these definitions; they shouldn't do much special now.
    DefConstructor("&", "<ltx:XMHint name='align'/>");
    DefConstructor("\\\\", "<ltx:XMHint name='newline'/>",
      reversion => Tokens(T_CS("\\\\"), T_CR));
    DefConstructor('\intertext{}',
      "<ltx:p class='ltx_intertext'>#1</ltx:p>", mode => 'text'); });

#======================================================================
# Section 3.5 Equation groups without alignment
# gather is for several equations, one per line, separated by \\ (& is not used)
# Why isn't this simply a direct equationgroup?
# but note that \intertext IS allowed....
# [or see dlmf code for equationgroup (but with optional implicit alignment)]
# NOTE: Does this need provision to deal with metadata?
DefConstructor('\@@amsgather SkipSpaces DigestedBody',
  '#1',
  beforeDigest => sub { $_[0]->bgroup; },
  afterConstruct => sub { rearrangeAMSGather($_[0], $_[0]->getNode->lastChild); });

DefPrimitive('\end@amsgather', sub { $_[0]->egroup; });

# Set up single centered column.
DefPrimitive('\@amsgather@bindings', sub {
    my $col = { before => Tokens(T_CS('\hfil'), T_MATH, T_CS('\displaystyle')),
      after => Tokens(T_MATH, T_CS('\hfil')) };
    amsalignBindings(LaTeXML::Core::Alignment::Template->new(columns => [$col]),
      attributes => { class => 'ltx_eqn_gather' }); });

# Each equation row (except intertext) consists of single equation.
# Since each equation is single column, w/ no alignment, we'll skip the MathFork stuff,
# and just pull the math content up past the _Capture_
#[maybe we could have avoided creating the capture in the first place?]
sub rearrangeAMSGather {
  my ($document, $equationgroup) = @_;
  foreach my $equation ($document->findnodes('ltx:equation', $equationgroup)) {
    my @cells = $document->findnodes('ltx:_Capture_', $equation);
    my @cell1cont = $document->getChildElements($cells[0]);
    # Check if this equation is really an intertext
    if ((scalar(@cells) == 1) && (scalar(@cell1cont) == 1)
      && (($cell1cont[0]->getAttribute('class') || '') =~ /\b(ltx_intertext)\b/)) {
      $equation->replaceNode($cell1cont[0]); }    # Replace equation with the block.
    elsif ((scalar(@cells) == 1) && (scalar(@cell1cont) == 0)) {    # Empty row? Remove it!
      $equationgroup->removeChild($equation); }
    else {
      map { $document->unwrapNodes($_) } $document->getChildElements($equation); } }
  return; }

# Note that some people use align or gather inside equation, which seems to "work"
# So, we'll treat align as aligned in such cases.
DefMacro('\gather',
  '\ifmmode\let\endgather\endgathered\gathered\else'
    . '\@amsgather@bindings\@@amsgather\@equationgroup@number\@start@alignment\fi');
DefMacro('\endgather',
  '\@finish@alignment\end@amsgather');
DefMacro('\csname gather*\endcsname',
  '\ifmmode\expandafter\let\csname endgather*\endcsname\endgathered\gathered\else'
    . '\@amsgather@bindings\@@amsgather\@equationgroup@nonumber\@start@alignment\fi');
DefMacro('\csname endgather*\endcsname',
  '\@finish@alignment\end@amsgather');

#======================================================================
# Section 3.6 Equation groups with mutual alignment

# This environment can contain multiple columns, but apparently the intension is
# that each pair should constitute an equation:
#    lhs & = rhs & lhs & = rhs ...
# where each lhs is right aligned, and rhs is left aligned.
# We'll use the equationgroup/equation/MathFork mechanism
# similar to eqnarray.
DefConstructor('\@@amsalign SkipSpaces DigestedBody',
  '#1',
  beforeDigest => sub { $_[0]->bgroup; },
  afterConstruct => sub { rearrangeAMSAlign($_[0], $_[0]->getNode->lastChild); });
DefPrimitive('\end@amsalign', sub { $_[0]->egroup; });

# Set up repeated pairs of columns.
DefPrimitive('\@amsalign@bindings', sub {
    my $col1 = { before => Tokens(T_CS('\hfil'), T_MATH, T_CS('\displaystyle')),
      after => Tokens(T_MATH) };
    my $col2 = { before => Tokens(T_MATH, T_CS('\displaystyle')),
      after => Tokens(T_MATH, T_CS('\hfil')) };
    amsalignBindings(LaTeXML::Core::Alignment::Template->new(repeated => [$col1, $col2]),
      attributes => { class => 'ltx_eqn_align' });
});

# Each equation row (except intertext) consists of pairs (LHS, =RHS); group accordingly.
sub rearrangeAMSAlign {
  my ($document, $equationgroup) = @_;
  foreach my $equation ($document->findnodes('ltx:equation', $equationgroup)) {
    my @cells = $document->findnodes('ltx:_Capture_', $equation);
    my @cell1cont = $document->getChildElements($cells[0]);
    # Check if this equation is really an intertext
    if ((scalar(@cells) == 1) && (scalar(@cell1cont) == 1)
      && (($cell1cont[0]->getAttribute('class') || '') =~ /\b(ltx_intertext)\b/)) {
      $equation->replaceNode($cell1cont[0]); }    # Replace equation with the block.
    elsif ((scalar(@cells) == 1) && (scalar(@cell1cont) == 0)) {    # Empty row? Remove it!
      $equationgroup->removeChild($equation); }
    else {
      equationgroupJoinCols($document, 2, $equation); } }
  return; }

#[Or should empty rows be removed? Numbered ones still show in print out!!!]

# Note that some people use align or gather inside equation, which seems to "work"
# So, we'll treat align as aligned in such cases.
DefMacro('\align',
  '\ifmmode\let\endalign\endaligned\aligned\else'
    . '\@amsalign@bindings\@@amsalign\@equationgroup@number\@start@alignment\fi');
DefMacro('\endalign',
  '\@finish@alignment\end@amsalign');
DefMacro('\csname align*\endcsname',
  '\ifmmode\expandafter\let\csname endalign*\endcsname\endaligned\aligned\else'
    . '\@amsalign@bindings\@@amsalign\@equationgroup@nonumber\@start@alignment\fi');
DefMacro('\csname endalign*\endcsname',
  '\@finish@alignment\end@amsalign');

# flalign typesets in the full column width (seems perverse to me).
# So, for the time being, it's treated exactly like align.
DefMacro('\flalign',
  '\ifmmode\let\endfalign\endaligned\aligned\else'
    . '\@amsalign@bindings\@@amsalign\@equationgroup@number\@start@alignment\fi');
DefMacro('\endflalign',
  '\@finish@alignment\end@amsalign');
DefMacro('\csname flalign*\endcsname',
  '\ifmmode\expandafter\let\csname endfalign*\endcsname\endaligned\aligned\else'
    . '\@amsalign@bindings\@@amsalign\@equationgroup@nonumber\@start@alignment\fi');
DefMacro('\csname endflalign*\endcsname',
  '\@finish@alignment\end@amsalign');

# alignat doesn't stretch the columns out as much (?)
# and takes the number of column pairs (which we don't need?)
# We'll ignore these distinctions for now.
DefMacro('\alignat{}',
  '\ifmmode\let\endalignat\endalignedat\alignedat{#1}\else'
    . '\@amsalign@bindings\@@amsalign\@equationgroup@number\@start@alignment\fi');
DefMacro('\endalignat',
  '\@finish@alignment\end@amsalign');
DefMacro('\csname alignat*\endcsname{}',
  '\ifmmode\expandafter\let\csname endalignat*\endcsname\endalignedat\alignedat{#1}\else'
    . '\@amsalign@bindings\@@amsalign\@equationgroup@nonumber\@start@alignment\fi');
DefMacro('\csname endalignat*\endcsname',
  '\@finish@alignment\end@amsalign');

DefMacro('\xalignat{}',
  '\ifmmode\let\endalignat\endalignedat\alignedat{#1}\else'
    . '\@amsalign@bindings\@@amsalign\@equationgroup@number\@start@alignment\fi');
DefMacro('\endxalignat',
  '\@finish@alignment\end@amsalign');
DefMacro('\csname xalignat*\endcsname{}',
  '\ifmmode\expandafter\let\csname endalignat*\endcsname\endalignedat\alignedat{#1}\else'
    . '\@amsalign@bindings\@@amsalign\@equationgroup@nonumber\@start@alignment\fi');
DefMacro('\csname endxalignat*\endcsname',
  '\@finish@alignment\end@amsalign');

DefMacro('\xxalignat{}',
  '\ifmmode\let\endalignat\endalignedat\alignedat{#1}\else'
    . '\@amsalign@bindings\@@amsalign\@equationgroup@number\@start@alignment\fi');
DefMacro('\endxxalignat',
  '\@finish@alignment\end@amsalign');

#======================================================================
# Section 3.7. Alignment building blocks
#    gathered, aligned alignedat
# These are intended to be used within math environments, but do they have the same
# `semanitic' intent as far as separating equations?
# aligned/alignedat perhaps do, since the alignment doesn't make much sense otherwise
# [except for a single column, but then split should be used]
# gathered could make sense as arranging a single subexpression into multiple lines within
# a larger expression.
#   On the other hand, we'll already be inside of a math environment, so delineating
# these potentially separate equations will be awkward anyway!

# So, we just leave Hint markers for & and \\
# Hmm...
DefMacro('\@noop@newline', sub {
    my ($gullet) = @_;
    readNewlineArgs($gullet);    # ignore
    (T_CS('\@noop@newline@marker')); });

DefConstructor('\@noop@newline@marker',
  "?#isMath(<ltx:XMHint name='newline'/>)(\n)",
  properties => { isSpace => 1 },
  reversion => "\\\\");

DefEnvironment('{gathered}[]',
  "<ltx:XMHint name='gathered-begin'/>"
    . "#body"
    . "<ltx:XMHint name='gathered-end'/>",
  beforeDigest => sub {
    Let('\\\\', '\@noop@newline'); });

DefMacro('\aligned[]',     '\@@amsaligned\@start@alignment');
DefMacro('\endaligned',    '\@finish@alignment\@end@amsaligned');
DefMacro('\alignedat{}[]', '\@@amsaligned\@start@alignment');
DefMacro('\endalignedat',  '\@finish@alignment\@end@amsaligned');

DefPrimitive('\@end@amsaligned', sub { $_[0]->egroup; });
DefConstructor('\@@amsaligned DigestedBody',
  '#1',
  beforeDigest => sub { $_[0]->bgroup;
    my $col1 = { before => Tokens(T_CS('\hfil'),
        T_CS('\displaystyle')) };
    my $col2 = { before => Tokens(T_CS('\displaystyle')),
      after => Tokens(T_CS('\hfil')) };
    my $template = LaTeXML::Core::Alignment::Template->new(repeated => [$col1, $col2]);
    alignmentBindings($template, undef, attributes => { name => 'aligned' });
    Let("\\\\", '\@alignment@newline@noskip');
  },
  reversion => '\begin{aligned}#1\end{aligned}');

# If an aligned is the only child of an equation,
# it seems better to rewrite the thing into an equationgroup/equation/MathFork construct!
Tag('ltx:equation', afterClose => \&rearrangeLoneAMSAligned);

sub rearrangeLoneAMSAligned {
  my ($document, $equation) = @_;
  # Test whether this is a lone aligned within the equation.
  my ($math, @more) = $document->findnodes('ltx:Math', $equation);
  if ($math && !scalar(@more)) {
    my ($array, @morenodes) = $document->getChildElements($document->getFirstChildElement($math));
    if ($array && !scalar(@morenodes) && ($document->getNodeQName($array) eq 'ltx:XMArray')
      && (($array->getAttribute('name') || '') eq 'aligned')) {
      $math->unbindNode;
      my $equationgroup = $document->renameNode($equation, 'ltx:equationgroup');
      foreach my $mtr ($document->findnodes('ltx:XMRow', $array)) {
        # new equation for each row (??? Or should it be each pair of columns?)
        my $eqn = $document->openElementAt($equationgroup, 'ltx:equation');
        if (my $id = $equation->getAttribute('xml:id')) {
          $document->setAttribute($eqn, 'xml:id' => $document->modifyID($id . "X")); }
        my @mtds = $document->findnodes('ltx:XMCell', $mtr);
        while (@mtds) {
          my ($main, $branch) = openMathFork($document, $eqn);
          my @cells;
          foreach (0, 1) {    # Add the lhs & rhs, separately.
            my $cell = shift(@mtds);
            next unless $cell;    # alignment not in pairs? Maybe we shouldn't even get this far?
            my $td = $document->openElementAt($branch, 'ltx:td',
              align => $cell->getAttribute('align'));
            if (my $stuff = $cell->firstChild) {
              push(@cells, $stuff);
              my $imath = $document->openElementAt($td, 'ltx:Math',
                _box => MathWhatsit(Digest(T_CS('\displaystyle')),
                  $document->getNodeBox($stuff)));
              my $xmath = $document->openElementAt($imath, 'ltx:XMath');
              { local $LaTeXML::Core::Document::ID_SUFFIX = '.mf';
                $document->appendClone($xmath, $stuff->childNodes); }
              $document->closeElementAt($xmath);
              $document->closeElementAt($imath); }
            $document->closeElementAt($td); }
          # Finally, move the contents of the cells into the main branch!!!
          map { $main->firstChild->appendChild($_) } map { $_->childNodes } @cells;
          # and synthesize a box from the lhs & rhs.
          $document->setNodeBox($main, MathWhatsit(map { $document->getNodeBox($_) } @cells));
          closeMathFork($document, $eqn, $main, $branch);
        } } } }
  return; }

DefMacro('\cases',    '\@@cases\@start@alignment');
DefMacro('\endcases', '\@finish@alignment\@end@cases');
DefPrimitive('\@end@cases', sub { $_[0]->egroup; });
DefConstructor('\@@cases DigestedBody',
  '#1',
  beforeDigest => sub {
    $_[0]->bgroup;
    alignmentBindings('ll', 'math', attributes => { meaning => 'cases', open => '{' });
    Let("\\\\", '\@alignment@newline@noskip'); },
  reversion => '\begin{cases}#1\end{cases}');

#======================================================================
# Section 3.8 Adjusting tag placement
DefMacro('\raisetag{Dimension}', '');    # Ignorable

#======================================================================
# Section 3.9 Vertical spacing and page breaks in multiline display
DefMacro('\displaybreak[]', '');    # Ignorable

#======================================================================
# Section 3.10 Interrupting a display

# default when not used inside an appropriate alignment.
DefConstructor('\intertext{}', "<ltx:p class='ltx_intertext'>#1</ltx:p>", mode => 'text');

#======================================================================
# Section 3.11 Equation numbering

# Section 3.11.1 Numbering hierarchy
DefPrimitive('\numberwithin[]{}{}', sub {
    my ($ignore, $format, $counter, $within) = @_;
    $format = ($format ? ToString($format) : '\arabic');
    $counter = ToString(Expand($counter)); $within = ToString(Expand($within));
    NewCounter($counter, $within);
    DefMacroI("\\the$counter", undef,
      "\\csname the$within\\endcsname.$format\{$counter\}", scope => 'global');
});

# Section 3.11.2 Cross references to equation numbers
DefConstructor('\eqref Semiverbatim', "(<ltx:ref labelref='#label'/>)",
  properties => sub { (label => CleanLabel($_[1])); });
DefMacro('\thetag{}', '{\rm #1}');

# Section 3.11.3 Subordinate numbering sequences.
DefEnvironment('{subequations}',
  "<ltx:equationgroup refnum='#refnum' frefnum='#frefnum' rrefnum='#rrefnum' xml:id='#id'>"
    . "#body"
    . "</ltx:equationgroup>",
  afterDigestBegin => sub {
    my ($stomach, $whatsit) = @_;
    my %eqn = RefStepCounter('equation');
    AssignValue(SAVED_EQUATION_NUMBER => LookupValue('\c@equation'));
    $whatsit->setProperties(%eqn);
    ResetCounter('equation');
    DefMacro('\theequation',    UnTeX($eqn{refnum}) . '\alph{equation}');
    DefMacro('\theequation@ID', UnTeX($eqn{id}) . '.\@equation@ID');
  },
  afterDigest => sub {
    AssignValue('\c@equation', LookupValue('SAVED_EQUATION_NUMBER'), 'global'); });

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Section 4: Miscellaneous mathematical features
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

#======================================================================
# Section 4.1 Matrices

DefMacro('\matrix',    '\@@matrix\@start@alignment');
DefMacro('\endmatrix', '\@finish@alignment\@end@matrix');
DefPrimitive('\@end@matrix', sub { $_[0]->egroup; });
DefConstructor('\@@matrix DigestedBody',
  '#1',
  beforeDigest => sub {
    $_[0]->bgroup;
    alignmentBindings(MatrixTemplate(), 'math', attributes => { name => 'Matrix' }); },
  reversion => '\begin{matrix}#1\end{matrix}');

DefMacro('\pmatrix',    '\@@pmatrix\@start@alignment');
DefMacro('\endpmatrix', '\@finish@alignment\@end@pmatrix');
DefPrimitive('\@end@pmatrix', sub { $_[0]->egroup; });
DefConstructor('\@@pmatrix DigestedBody',
  '#1',
  beforeDigest => sub {
    $_[0]->bgroup;
    alignmentBindings(MatrixTemplate(), 'math', attributes => { name => 'Matrix',
        open => '(', close => ')' }); },
  reversion => '\begin{pmatrix}#1\end{pmatrix}');

DefMacro('\bmatrix',    '\@@bmatrix\@start@alignment');
DefMacro('\endbmatrix', '\@finish@alignment\@end@bmatrix');
DefPrimitive('\@end@bmatrix', sub { $_[0]->egroup; });
DefConstructor('\@@bmatrix DigestedBody',
  '#1',
  beforeDigest => sub {
    $_[0]->bgroup;
    alignmentBindings(MatrixTemplate(), 'math', attributes => { name => 'Matrix',
        open => '[', close => ']' }); },
  reversion => '\begin{bmatrix}#1\end{bmatrix}');

DefMacro('\Bmatrix',    '\@@Bmatrix\@start@alignment');
DefMacro('\endBmatrix', '\@finish@alignment\@end@Bmatrix');
DefPrimitive('\@end@Bmatrix', sub { $_[0]->egroup; });
DefConstructor('\@@Bmatrix DigestedBody',
  '#1',
  beforeDigest => sub {
    $_[0]->bgroup;
    alignmentBindings(MatrixTemplate(), 'math', attributes => { name => 'Matrix',
        open => '{', close => '}' }); },
  reversion => '\begin{Bmatrix}#1\end{Bmatrix}');

DefMacro('\vmatrix',    '\@@vmatrix\@start@alignment');
DefMacro('\endvmatrix', '\@finish@alignment\@end@vmatrix');
DefPrimitive('\@end@vmatrix', sub { $_[0]->egroup; });
DefConstructor('\@@vmatrix DigestedBody',
  '#1',
  beforeDigest => sub {
    $_[0]->bgroup;
    alignmentBindings(MatrixTemplate(), 'math', attributes => { name => 'Matrix',
        open => '|', close => '|' }); },
  reversion => '\begin{vmatrix}#1\end{vmatrix}');

DefMacro('\Vmatrix',    '\@@Vmatrix\@start@alignment');
DefMacro('\endVmatrix', '\@finish@alignment\@end@Vmatrix');
DefPrimitive('\@end@Vmatrix', sub { $_[0]->egroup; });
DefConstructor('\@@Vmatrix DigestedBody',
  '#1',
  beforeDigest => sub {
    $_[0]->bgroup;
    alignmentBindings(MatrixTemplate(), 'math', attributes => { name => 'Matrix',
        open  => "\x{2225}",
        close => "\x{2225}" }); },
  reversion => '\begin{Vmatrix}#1\end{Vmatrix}');

DefMacro('\smallmatrix',    '\@hidden{\scriptsize}\@@smallmatrix\@start@alignment');
DefMacro('\endsmallmatrix', '\@finish@alignment\@end@smallmatrix');
DefPrimitive('\@end@smallmatrix', sub { $_[0]->egroup; });
DefConstructor('\@@smallmatrix DigestedBody',
  '#1',
  beforeDigest => sub {
    $_[0]->bgroup;
    alignmentBindings(MatrixTemplate(), 'math', attributes => { name => 'Matrix' }); },
  reversion => '\begin{smallmatrix}#1\end{smallmatrix}');

#======================================================================
# Section 4.2 Math spacing commands
# \, == \thinspace
# \: == \medspace
# \; == \thickspace
# \quad
# \qquad
# \! == \negthinspace
# \negmedspace
# \negthickspace
# I think only these are new

DefConstructorI('\thinspace', undef,
  "?#isMath(<ltx:XMHint name='thinspace' width='#width'/>)(\x{2009})",
  properties => { isSpace => 1, width => sub { LookupValue('\thinmuskip'); } });
DefConstructorI('\negthinspace', undef,
  "?#isMath(<ltx:XMHint name='negthinspace' width='#width'/>)()",
  properties => { isSpace => 1, width => sub { LookupValue('\thinmuskip')->negate; } });
DefConstructorI('\medspace', undef,
  "?#isMath(<ltx:XMHint name='medspace' width='#width'/>)()",
  properties => { isSpace => 1, width => sub { LookupValue('\medmuskip'); } });
DefConstructorI('\negmedspace', undef,
  "?#isMath(<ltx:XMHint name='negmedspace' width='#width'/>)()",
  properties => { isSpace => 1, width => sub { LookupValue('\medmuskip')->negate; } });
DefConstructorI('\thickspace', undef,
  "?#isMath(<ltx:XMHint name='thickspace' width='#width'/>)(\x{2004})",
  properties => { isSpace => 1, width => sub { LookupValue('\thickmuskip'); } });
DefConstructorI('\negthickspace', undef,
  "?#isMath(<ltx:XMHint name='negthickspace' width='#width'/>)(\x{2004})",
  properties => { isSpace => 1, width => sub { LookupValue('\thickmuskip')->negate; } });

DefConstructor('\mspace{MuDimension}', "<ltx:XMHint name='mspace' width='#1'/>");

#======================================================================
# Section 4.3 Dots
# Nice idea, but not sure what I really should do about it.
# In principle, a processor has access to the context....
DefMacroI('\dotsc', undef, '\ldots');    # Dots with commas
DefMacroI('\dotsb', undef, '\cdots');    # Dots with binary operators/relations
DefMacroI('\dotsm', undef, '\cdots');    # multiplication dots
DefMacroI('\dotsi', undef, '\cdots');    # Dots with integrals
DefMacroI('\dotso', undef, '\ldots');    # other dots (??)

# Not really clear when these get set to something other than \relax, in amsfonts.sty
DefMacroI('\DOTSB', undef, Tokens());
DefMacroI('\DOTSI', undef, Tokens());
DefMacroI('\DOTSX', undef, Tokens());
Let('\hdots', '\ldots');

DefMacro('\hdotsfor Number', sub {
    (map { T_CS('\hdots') } 1 .. $_[1]->valueOf); });

#======================================================================
# Section 4.4 Nonbreaking dashes
# \nobreakdash
DefMacro('\nobreakdash', '');    # Ignorable
#======================================================================
# Section 4.5 Accents in math
DefMath('\dddot{}',  "\x{02D9}\x{02D9}\x{02D9}",         operator_role => 'OVERACCENT'); # DOT ABOVE
DefMath('\ddddot{}', "\x{02D9}\x{02D9}\x{02D9}\x{02D9}", operator_role => 'OVERACCENT'); # DOT ABOVE

# In amsxtra
#  \sphat \sptilde

#======================================================================
# Section 4.6 Roots
# It would be nice to carry this info through to mathml, but ignore for now.
DefMacro('\leftroot{}', '');
DefMacro('\uproot{}',   '');

#======================================================================
# Section 4.7 Boxed formulas
DefMacro('\boxed{}', '\ifmmode\boxed@math{#1}\else\boxed@text{#1}\fi');
DefConstructor('\boxed@math{}',
  "<ltx:XMArg enclose='box'>#1</ltx:XMArg>");
DefConstructor('\boxed@text{}', sub {
    my ($document, $body, %props) = @_;
    my @new = insertBlock($document, $body);
    foreach my $node (@new) {
      $document->setAttribute($node, framed => 'rectangle'); } },    # if allowed??
  bounded      => 1,
  beforeDigest => sub {
    Let("\\\\", '\@block@cr'); });

DefMath('\implies',   "\x{27F9}", role => 'ARROW', meaning => 'implies');
DefMath('\impliedby', "\x{27F8}", role => 'ARROW', meaning => 'implied-by');

DefMath('\And', '&', role => 'ADDOP', meaning => 'and');

#======================================================================
# Section 4.8 Over and under arrows

# Should be in LaTeX (& TeX): \overrightarrow, \overleftarrow
# Note that the arrow is treated as an accent over/under the argument!
DefMath('\underrightarrow{}',     "\x{2192}", operator_role => 'UNDERACCENT');
DefMath('\underleftarrow{}',      "\x{2190}", operator_role => 'UNDERACCENT');
DefMath('\overleftrightarrow{}',  "\x{2194}", operator_role => 'OVERACCENT');
DefMath('\underleftrightarrow{}', "\x{2194}", operator_role => 'UNDERACCENT');

#======================================================================
# Section 4.9 Extensible arrows
#  \xleftarrow, \xrightarrow
# Note that these are treated primarily as arrows with stuff as accents over & maybe under.
DefConstructor('\xrightarrow[]{}',
  "?#1("
    . "<ltx:XMApp role='ARROW'>"
    . "<ltx:XMWrap role='UNDERACCENT'>#1</ltx:XMWrap>"
    . "<ltx:XMApp role='ARROW'>"
    . "<ltx:XMWrap role='OVERACCENT'>#2</ltx:XMWrap>"
    . "<ltx:XMTok name='rightarrow' role='ARROW'>\x{2192}</ltx:XMTok>"
    . "</ltx:XMApp>"
    . "</ltx:XMApp>"
    . ")("
    . "<ltx:XMApp role='ARROW'>"
    . "<ltx:XMWrap role='OVERACCENT'>#2</ltx:XMWrap>"
    . "<ltx:XMTok name='rightarrow' role='ARROW'>\x{2192}</ltx:XMTok>"
    . "</ltx:XMApp>"
    . ")",
  properties => { font => sub { LookupValue('font')->specialize("\x{2026}"); } });
DefConstructor('\xleftarrow[]{}',
  "?#1("
    . "<ltx:XMApp role='ARROW'>"
    . "<ltx:XMWrap role='UNDERACCENT'>#1</ltx:XMWrap>"
    . "<ltx:XMApp role='ARROW'>"
    . "<ltx:XMWrap role='OVERACCENT'>#2</ltx:XMWrap>"
    . "<ltx:XMTok name='leftarrow' role='ARROW'>\x{2190}</ltx:XMTok>"
    . "</ltx:XMApp>"
    . "</ltx:XMApp>"
    . ")("
    . "<ltx:XMApp role='ARROW'>"
    . "<ltx:XMWrap role='OVERACCENT'>#2</ltx:XMWrap>"
    . "<ltx:XMTok name='leftarrow' role='ARROW'>\x{2190}</ltx:XMTok>"
    . "</ltx:XMApp>"
    . ")",
  properties => { font => sub { LookupValue('font')->specialize("\x{2026}"); } });

#======================================================================
# Section 4.10 Affixing symbols to other symbols

# Note that the 1st argument is treated set as an accent over (or under) the 2nd argument.
DefConstructor('\overset{}{}',
  "<ltx:XMApp>"
    . "<ltx:XMWrap role='OVERACCENT'>#1</ltx:XMWrap>"
    . "<ltx:XMArg>#2</ltx:XMArg>"
    . "</ltx:XMApp>");
DefConstructor('\underset{}{}',
  "<ltx:XMApp>"
    . "<ltx:XMWrap role='UNDERACCENT'>#1</ltx:XMWrap>"
    . "<ltx:XMArg>#2</ltx:XMArg>"
    . "</ltx:XMApp>");

#======================================================================
# Section 4.11 Fractions and related commands

# Section 4.11.1 The \frac, \dfrac, and \tfrac commands

DefConstructor('\tfrac{}{}',
  "<ltx:XMApp>"
    . "<ltx:XMTok meaning='divide' role='MULOP' mathstyle='#mathstyle'/>"
    . "<ltx:XMArg>#1</ltx:XMArg><ltx:XMArg>#2</ltx:XMArg>"
    . "</ltx:XMApp>",
  beforeDigest => \&beforeTFrac, afterDigest => \&afterTFrac);
DefConstructor('\dfrac{}{}',
  "<ltx:XMApp>"
    . "<ltx:XMTok meaning='divide' role='MULOP' mathstyle='#mathstyle'/>"
    . "<ltx:XMArg>#1</ltx:XMArg><ltx:XMArg>#2</ltx:XMArg>"
    . "</ltx:XMApp>",
  beforeDigest => \&beforeDFrac, afterDigest => \&afterDFrac);
DefConstructor('\ifrac{}{}',
  "<ltx:XMApp>"
    . "<ltx:XMTok meaning='divide' role='MULOP' mathstyle='inline'/>"
    . "<ltx:XMArg>#1</ltx:XMArg><ltx:XMArg>#2</ltx:XMArg>"
    . "</ltx:XMApp>",
  beforeDigest => \&beforeFrac, afterDigest => \&afterFrac);

# Section 4.11.2 The \binom, \dbinom, and \tbinom commands
DefConstructor('\binom{}{}',
  "<ltx:XMApp open='(' close=')'>"
    . "<ltx:XMTok meaning='binomial' role='STACKED' mathstyle='#mathstyle'/>"
    . "<ltx:XMArg>#1</ltx:XMArg><ltx:XMArg>#2</ltx:XMArg>"
    . "</ltx:XMApp>",
  beforeDigest => \&beforeFrac, afterDigest => \&afterFrac);

DefConstructor('\tbinom{}{}',
  "<ltx:XMApp open='(' close=')'>"
    . "<ltx:XMTok meaning='binomial' role='STACKED' mathstyle='#mathstyle'/>"
    . "<ltx:XMArg>#1</ltx:XMArg><ltx:XMArg>#2</ltx:XMArg>"
    . "</ltx:XMApp>",
  beforeDigest => \&beforeTFrac, afterDigest => \&afterTFrac);
DefConstructor('\dbinom{}{}',
  "<ltx:XMApp open='(' close=')'>"
    . "<ltx:XMTok meaning='binomial' role='STACKED' mathstyle='#mathstyle'/>"
    . "<ltx:XMArg>#1</ltx:XMArg><ltx:XMArg>#2</ltx:XMArg>"
    . "</ltx:XMApp>",
  beforeDigest => \&beforeDFrac, afterDigest => \&afterDFrac);

# Annoying defaults!
DefMacro('\genfrac{}{}{}{}{}{}',
  '\if @#3@'
    . '\if.#4.\@@genfrac{#1}{#2}{#5}{#6}\else\@@genfrac{#1}{#2}{#5}{#6}[#4]\fi'
    . '\else'
    . '\if.#4.\@@genfrac{#1}{#2}[#3]{#5}{#6}\else\@@genfrac{#1}{#2}[#3]{#5}{#6}[#4]\fi'
    . '\fi');

# Section 4.11.3 The \genfrac command
DefConstructor('\@@genfrac{}{}[Dimension]{}{}[Number]',
  "<ltx:XMApp open='#open' close='#close'>"
    . "<ltx:XMTok role='#role' ?#meaning(meaning='#meaning')()"
    . " ?#thickness(thickness='#thickness')() mathstyle='#mathstyle'/>"
    . "<ltx:XMArg>#4</ltx:XMArg>"
    . "<ltx:XMArg>#5</ltx:XMArg>"
    . "</ltx:XMApp>",
  reversion   => '\genfrac{#1}{#2}{#3}{#6}{#4}{#5}',
  alias       => '\genfrac',
  afterDigest => sub {
    my ($stomach, $whatsit) = @_;
    my ($open, $close, $thickness, $num, $denom, $stylecode) = $whatsit->getArgs;
    $open = ToString($open); $close = ToString($close);
    if (my $entry = LaTeXML::Package::Pool::lookup_delimiter($open)) {
      $open = $$entry{char}; }
    if (my $entry = LaTeXML::Package::Pool::lookup_delimiter($close)) {
      $close = $$entry{char}; }
    my $role = ($thickness && ($thickness->valueOf == 0) ? 'STACKED' : 'MULOP');
    my $meaning = ($role eq 'MULOP' ? 'divide' : undef);
    $stylecode = $stylecode->valueOf if defined $stylecode;
    my $mathstyle = (!defined $stylecode ? LookupValue('mathstyle')
      : ($stylecode == 0 ? 'display'
        : ($stylecode == 1 ? 'text'
          : ($stylecode == 2 ? 'script'
            : 'scriptscript'))));
    $whatsit->setProperties(open => $open,
      close     => $close,
      role      => $role,
      meaning   => $meaning,
      thickness => $thickness,
      mathstyle => $mathstyle); });

#======================================================================
# Section 4.12 Continued fractions
# I think \cfracstyle my own invention? (I know I've redefined \cfrac in DLMFmath)
# XMDual doesn't seem quite appropriate, since the args (denominators) get
# divided up so oddly in the inline case.
# I've left it to a special case in conversion to pmml.
DefConstructor('\cfrac{}{}',
  "<ltx:XMApp>"
    . "<ltx:XMTok name='cfrac' mathstyle='#mathstyle' meaning='continued-fraction'/>"
    . "<ltx:XMArg>#1</ltx:XMArg>"
    . "<ltx:XMArg>#2</ltx:XMArg>"
    . "</ltx:XMApp>",
  beforeDigest => sub {
    $_[0]->bgroup;
    AssignValue(mathstyle => 'text'); },
  afterDigest => sub {
    $_[0]->egroup;
    $_[1]->setProperties(mathstyle => LookupValue('CFRACSTYLE')); });

AssignValue(CFRACSTYLE => 'display');
# This should get incorporated into any \cfrac's that are constructed in scope.
DefConstructor('\cfracstyle{}', '',
  afterDigest => sub {
    my $style = ToString($_[1]->getArg(1));
    $style = ($style eq 'd' ? 'display' : ($style eq 'i' ? 'inline' : $style));
    AssignValue(CFRACSTYLE => $style); });

#======================================================================
# Section 4.13 Smash options
DefConstructor('\smash[]{}', "#2");    # well, what?

#======================================================================
# Section 4.14 Delimiters

# Section 4.14.1 Delimiter sizes
# Redefinitions(?) of \bigl, \bigr, \Bigl,\Bigr, \biggl, \biggr, \Biggl, \Biggr

# Section 4.14.2 Vertical bar notations
DefMath('\lvert', '|',        role => 'OPEN');
DefMath('\lVert', "\x{2225}", role => 'OPEN');     # PARALLEL TO
DefMath('\rvert', '|',        role => 'CLOSE');
DefMath('\rVert', "\x{2225}", role => 'CLOSE');    # PARALLEL TO

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Section 5  Operator names
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

#======================================================================
# Section 5.1 Defining new operator names

# See package amsopn (included by default)

#======================================================================
# Section 5.2 \mod and it's relatives
# \bmod, \pmod which are already in LaTeX
DefMath('\mod',   'mod',  role => 'MODIFIEROP', meaning => 'modulo');
DefMath('\pod{}', '(#1)', role => 'MODIFIER',   meaning => 'modulo');    # Well, sorta postfix..

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Section 6 The \text command
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# See package amstext, included by default.

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Section 7 Integrals and sums
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

#======================================================================
# Section 7.1 Multiline subscripts and superscripts
#  \substack, \begin{subarray}
# These make the combining operator be list, but often formulae would be better
DefConstructor('\substack{}',
  "<ltx:XMApp>"
    . "<ltx:XMTok name='list' role='STACKED'/>"
    . "<ltx:XMArg>#1</ltx:XMArg>"
    . "</ltx:XMApp>",
  bounded => 1, beforeDigest => sub { DefConstructor("\\\\ OptionalMatch:* [Dimension]",
      "</ltx:XMArg><ltx:XMArg>",
      reversion => Tokens(T_CS("\\\\"), T_CR));
    Let('\cr', "\\\\"); });
DefEnvironment('{subarray}{}',
  "<ltx:XMApp>"
    . "<ltx:XMTok name='list' role='STACKED' class='ltx_align_#1'/>"
    . "<ltx:XMArg>#body</ltx:XMArg>"
    . "</ltx:XMApp>",
  beforeDigest => sub { DefConstructor("\\\\ OptionalMatch:* [Dimension]",
      "</ltx:XMArg><ltx:XMArg>",
      reversion => Tokens(T_CS("\\\\"), T_CR));
    Let('\cr', "\\\\"); });

#======================================================================
# Section 7.2 the \sideset command

# This is intended to be a modifier for \sum or \prod
# NOTE that there can be at most one subscript in each of the pre & post, ditto for superscript.
# Thus, our representation is: sideset(presub,presup,postsub,postsup,object)
# Note, also, that this is quite ugly, but since it is a rather peculiar special case.... ?
DefConstructor('\sideset{}{}{}', sub {
    my ($document, $pre, $post, $base, %props) = @_;
    my @scripts = (undef, undef, undef, undef);

    # Just to be "safe", scan for any NON scripts in the pre-scripts
    # They work with \sideset, although it isn't clear what they should mean.
    # we'll just insert them in front of the whole mess.
    foreach my $script ($pre->unlist) {
      if (!IsScript($script)) {
        Warn('expected', '<sub/supserscript>', $document,
          "Expected a sub/superscript in the prescripts of \\sideset",
          "Got " . Stringify($script));
        $document->insertElement('ltx:XMWrap', $script); } }    # Stick any non-scripts FRONT!

    my $node = $document->insertElement('ltx:XMArg', $base);
    my $ch = $document->getFirstChildElement($node);
    my ($opx, $ignore)
      = ($ch && $ch->getAttribute('scriptpos') || 'post') =~ /^(pre|mid|post)?(\d+)?$/;
    my $level = $props{level} || 0;
    foreach my $script (reverse $pre->unlist) {
      # If it's a script, handle it (non-scripts dealt with above & below)
      if (my $scriptop = IsScript($script)) {
        $node = sidesetWrap($document, $node, 'pre', $$scriptop[1], $level, $script);
        $level++ if $$scriptop[0] eq 'FLOATING';                # After node is seen!
      } }
    my @after = ();
    foreach my $script ($post->unlist) {
      # If it's a script, handle it (non-scripts dealt with above & below)
      if (my $scriptop = IsScript($script)) {
        $level++ if $$scriptop[0] eq 'FLOATING';                # Before node is seen!
        $node = sidesetWrap($document, $node, 'post', $$scriptop[1], $level, $script); }
      else {
        push(@after, $script); } }                              # Save non-scripts
    $document->setAttribute($node, scriptpos => $opx) if $opx;

    # Put any garbage in the post-scripts AFTER
    foreach my $nonscript (@after) {
      Warn('expected', '<sub/supserscript>', $document,
        "Expected a sub/superscript in the postscripts of \\sideset",
        "Got " . Stringify($nonscript));
      $document->insertElement('ltx:XMWrap', $nonscript); }     # Append, afterwards
});

sub sidesetWrap {
  my ($document, $node, $x, $y, $level, $script) = @_;
  my $new = $document->openElement('ltx:XMApp');
  $document->insertElement('ltx:XMTok', undef, role => $y . 'OP', scriptpos => "$x$level");
  $new->appendChild($node);
  $document->insertElement('ltx:XMWrap', $script->getArg(1));
  $document->closeElement('ltx:XMApp');
  return $new; }

#======================================================================
# Section 7.3 Placement of subscripts and limits
# \limits and \nolimits; already in TeX

#======================================================================
# Section 7.4 Multiple integral signs

DefMath('\iint', "\x{222C}", meaning => 'double-integral', role => 'INTOP',
  mathstyle => \&doVariablesizeOp);
DefMath('\iiint', "\x{222D}", meaning => 'triple-integral', role => 'INTOP',
  mathstyle => \&doVariablesizeOp);
DefMath('\iiiint', "\x{2A0C}", meaning => 'quadruple-integral', role => 'INTOP',
  mathstyle => \&doVariablesizeOp);
DefMath('\idotsint', "\x{222B}\x{22EF}\x{222B}", meaning => 'multiple-integral', role => 'INTOP',
  mathstyle => \&doVariablesizeOp);

DefMacro('\MultiIntegral{}', sub {
    my ($gullet, $n) = @_;
    $n = ToString($n);
    (($n == 0 ? T_CS('\idotsint') : ($n == 1 ? T_CS('\int') : ($n == 2 ? T_CS('\iint') : ($n == 3 ? T_CS('\iiint') : T_CS('\iiiint')))))); });

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Section 8 Commutative diagrams
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Separately in amscd
# CD environment
# with commands @>.., @<<<, @VVV, @AAA to give right, left, down, up arrows...

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Section 9 Using math fonts
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

#======================================================================
# Section 9.1 Introduction
# See amsfonts, euscript

#======================================================================
# Section 9.2 Recommended use of math font commands

#======================================================================
# Section 9.3 Bold math symbols
# See package amsbsy (included by default)

#======================================================================
# Section 9.4 Italic Greek letters
# I think this is sufficient:

DefMath('\varGamma',   "\x{0393}", font => { shape => 'italic' });
DefMath('\varSigma',   "\x{03A3}", font => { shape => 'italic' });
DefMath('\varDelta',   "\x{0394}", font => { shape => 'italic' });
DefMath('\varUpsilon', "\x{03A5}", font => { shape => 'italic' });
DefMath('\varTheta',   "\x{0398}", font => { shape => 'italic' });
DefMath('\varPhi',     "\x{03A6}", font => { shape => 'italic' });
DefMath('\varLambda',  "\x{039B}", font => { shape => 'italic' });
DefMath('\varPsi',     "\x{03A8}", font => { shape => 'italic' });
DefMath('\varXi',      "\x{039E}", font => { shape => 'italic' });
DefMath('\varOmega',   "\x{03A9}", font => { shape => 'italic' });
DefMath('\varPi',      "\x{03A0}", font => { shape => 'italic' });

#======================================================================
# And some random other weird naming
Let('\Hat',   '\hat');
Let('\Check', '\check');
Let('\Tilde', '\tilde');
Let('\Acute', '\acute');
Let('\Grave', '\grave');
Let('\Dot',   '\dot');
Let('\Ddot',  '\ddot');
Let('\Breve', '\breve');
Let('\Bar',   '\bar');
Let('\Vec',   '\vec');

# And where does this go?
DefPrimitive('\allowdisplaybreaks[]', undef);
#======================================================================
DefMacroI('\mintagsep',   undef, Tokens());
DefMacroI('\minalignsep', undef, "10pt");
DefRegister('\multlinegap'    => Glue('10pt'));
DefRegister('\multlinetaggap' => Glue('10pt'));
DefMacro('\primfrac{}', Tokens());

# \shoveleft, \shoveright should do something about eqn number placement?
DefMacro('\shoveleft{}',  '#1');
DefMacro('\shoveright{}', '#1');

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1;