lib/LaTeXML/Post/MathML.pm untested

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