lib/LaTeXML/Core/Alignment.pm

filter: Statementstmt 91.6% 22 / 24 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 8 / 8 Podpod n/a totaltotal 93.7% 30 / 32 CC 1 SCAR 0.4
CC
1
Cov
92%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« lib/LaTeXML/Core.pm ↑ Summary lib/LaTeXML/Core/Definition/Expandable.pm »
1 # /=====================================================================\ #
2 # | LaTeXML::Core::Alignment | #
3 # | Support for tabular/array environments | #
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 package LaTeXML::Core::Alignment;
13 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 5 ▶use LaTeXML::Global;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 5 ▶use LaTeXML::Common::Error;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 5 ▶use LaTeXML::Core::Token;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 5 ▶use LaTeXML::Core::Tokens;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 5 ▶use LaTeXML::Common::Object;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 5 ▶use LaTeXML::Common::XML;
Subroutine BEGIN: called CC=1 SCAR=2.6
21 use LaTeXML::Common::Dimension;
22 use LaTeXML::Core::Alignment::Template;
23 use List::Util qw(max sum);
24 use base qw(LaTeXML::Core::Whatsit);
25 use base qw(Exporter);
26 our @EXPORT = (qw(
27 &ReadAlignmentTemplate &MatrixTemplate));
28  
29 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
30 # An "Alignment" is an array/tabular construct as:
31 # <tabular><tr><td>...
32 # or, for math mode
33 # <XMArray><XMRow><XMCell>...
34 # (where initially, each XMCell will contain an XMArg to indicate
35 # individual parsing of each cell's content is desired)
36 #
37 # An Alignment object is a sort of fake Whatsit;
38 # It takes some magic to sneak it into the Digestion stream
39 # (see TeX.pool \@start@alignment), but it needs to be created
40 # BEFORE the contents of the alignment are digested,
41 # since we stuff a lot of information into it
42 # (row, column boxes, borders, spacing, etc...)
43 # But once it has been captured, it should otherwise act
44 # like a Whatsit and be responsible for construction (beAbsorbed),
45 # and sizing estimation (computeSize)
46 #
47 # Ultimately, this should be better tied into DefConstructor
48 # because an Alignment currently doesn't know what CS created it (debugging!);
49 # Also, it would better connect the things being constructed, reversion, etc.
50 #======================================================================
51 DebuggableFeature('alignment', "Debug guessing headers of alignments/tables");
52  
53 # Create a new Alignment.
54 # %data can contain:
55 # template : an Alignment::Template object
56 # openContainer = sub($doc,%attrib); creates the container element with given attributes
57 # closeContainer = sub($doc); closes the container
58 # openRow = sub($doc,%attrib); creates the row element with given attributes
59 # closeRow = closes the row
60 # openColumn = sub($doc,%attrib); creates the column element with given attributes
61 # closeColumn = closes the column
62 # attributes = hashref containing extra attributes for the container element.
63 sub new {
64 my ($class, %data) = @_;
65 my $self = bless {%data}, $class;
66 $$self{template} = LaTeXML::Core::Alignment::Template->new() unless $$self{template};
67 $$self{template} = parseAlignmentTemplate($$self{template}) unless ref $$self{template};
68 $$self{rows} = [];
69 $$self{current_column} = 0;
70 $$self{current_row} = undef;
71 $$self{level} = $STATE->getFrameDepth;
72 $$self{properties} = {} unless $$self{properties};
73 # Copy any attribute width, height, depth to main properties.
74 if (my $attributes = $$self{properties}{attributes}) {
75 $$self{properties}{width} = $$attributes{width} if $$attributes{width};
76 $$self{properties}{height} = $$attributes{height} if $$attributes{height};
77 $$self{properties}{depth} = $$attributes{depth} if $$attributes{depth}; }
78 return $self; }
79  
80 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
81 # Alignment specific accessors
82 sub getTemplate {
83 my ($self, $template) = @_;
84 return $$self{template}; }
85  
86 sub currentRow {
87 my ($self) = @_;
88 return $$self{current_row}; }
89  
90 sub newRow {
91 my ($self) = @_;
92 my $row = $$self{template}->clone;
93 $$self{current_row} = $row;
94 $$self{current_column} = 0;
95 push(@{ $$self{rows} }, $row);
96 return $row; }
97  
98 sub removeRow {
99 my ($self) = @_;
100 my @rows = @{ $$self{rows} };
101 if (@rows) {
102 my $row = pop(@rows);
103 $$self{rows} = [@rows];
104 return $row; }
105 else {
106 return; } }
107  
108 sub prependRows {
109 my ($self, @rows) = @_;
110 unshift(@{ $$self{rows} }, @rows);
111 return; }
112  
113 sub appendRows {
114 my ($self, @rows) = @_;
115 push(@{ $$self{rows} }, @rows);
116 return; }
117  
118 sub rows {
119 my ($self) = @_;
120 return @{ $$self{rows} }; }
121  
122 sub addLine {
123 my ($self, $border, @cols) = @_;
124 if (my $row = $$self{current_row}) {
125 if (@cols) {
126 foreach my $c (@cols) {
127 my $colspec = $row->column($c);
128 $$colspec{border} .= $border; } }
129 else {
130 foreach my $colspec (@{ $$row{columns} }) {
131 $$colspec{border} .= $border; } } }
132 return; }
133  
134 sub nextColumn {
135 my ($self) = @_;
136 return unless $$self{current_row};
137 my $colspec = $$self{current_row}->column(++$$self{current_column});
138 if (!$colspec) {
139 Error('unexpected', '&', $STATE->getStomach->getGullet, "Extra alignment tab '&'");
140 $$self{current_row}->addColumn(align => 'center');
141 $colspec = $$self{current_row}->column($$self{current_column}); }
142 return $colspec; }
143  
144 sub lastColumn {
145 my ($self) = @_;
146 my $row = $$self{current_row};
147 return unless $row;
148 $$self{current_column} = scalar @{ $$row{columns} };
149 return $row->column($$self{current_column}); }
150  
151 sub currentColumnNumber {
152 my ($self) = @_;
153 return $$self{current_column}; }
154  
155 sub currentRowNumber {
156 my ($self) = @_;
157 my $n = 0;
158 foreach my $row (@{ $$self{rows} }) {
159 $n++ unless $$row{pseudorow}; }
160 return $n; }
161  
162 sub currentColumn {
163 my ($self) = @_;
164 return $$self{current_row} && $$self{current_row}->column($$self{current_column}); }
165  
166 sub getColumn {
167 my ($self, $n) = @_;
168 return $$self{current_row} && $$self{current_row}->column($n); }
169  
170 # Ugh... these take boxes; adding before/after columns takes tokens!
171 sub addBeforeRow {
172 my ($self, @boxes) = @_;
173 $$self{current_row}{before} = [@{ $$self{current_row}{before} || [] }, @boxes];
174 return; }
175  
176 sub addAfterRow {
177 my ($self, @boxes) = @_;
178 $$self{current_row}{after} = [@{ $$self{current_row}{after} || [] }, @boxes];
179 return; }
180  
181 sub omitColumn {
182 my ($self) = @_;
183 if (my $column = $self->currentColumn) {
184 $$column{omitted} = 1; }
185 return; }
186  
187 sub omitNextColumn {
188 my ($self) = @_;
189 if (my $column = $$self{current_row} && $$self{current_row}->column($$self{current_column} + 1)) {
190 $$column{omitted} = 1; }
191 return; }
192  
193 sub getColumnBefore {
194 my ($self) = @_;
195 my $column;
196 if (($column = $self->currentColumn) && !$$column{omitted}) {
197 return Tokens(T_CS('\@column@before'), @{ $$column{before} }); }
198 else {
199 return Tokens(); } }
200  
201 sub getColumnAfter {
202 my ($self) = @_;
203 my $column;
204 if (($column = $self->currentColumn) && !$$column{omitted}) {
205 # Possible \@@eat@space ??? (if LaTeX style???)
206 return Tokens(@{ $$column{after} }, T_CS('\@column@after')); }
207 else {
208 return Tokens(); } }
209  
210 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
211 # Support for building an alignment's Rows & Columns
212  
213 sub startRow {
214 my ($self, $pseudorow) = @_;
215 $self->newRow;
216 my $stomach = $STATE->getStomach;
217 $stomach->bgroup; # Grouping around ROW!
218 if ($pseudorow) {
219 $self->currentRow->{pseudorow} = 1; }
220 else {
221 push(@LaTeXML::LIST, $stomach->digest(T_CS('\@row@before'))); }
222 $$self{in_row} = 1;
223 $STATE->assignValue(alignmentStartColumn => 0); # ???
224 return; }
225  
226 sub endRow {
227 my ($self) = @_;
228 return unless $$self{in_row};
229 $self->endColumn() if $$self{in_column};
230 $STATE->getStomach->egroup; # Grouping around ROW!
231 # Digest(T_CS('\@row@after'));
232 $$self{in_row} = undef;
233 return; }
234  
235 sub startColumn {
236 my ($self, $pseudorow) = @_;
237 if (!$$self{in_row}) {
238 $self->startRow($pseudorow); }
239 elsif ($pseudorow) {
240 $self->currentRow->{pseudorow} = 1; }
241 $STATE->getStomach->bgroup; # Grouping around CELL!
242 # Note: a VERY round-about way of tracking the column spanning!
243 $STATE->assignValue(alignmentStartColumn => $self->currentColumnNumber);
244 my $colspec = $self->nextColumn;
245 $LaTeXML::ALIGN_STATE = 1000000;
246 $$self{in_column} = 1;
247 return; }
248  
249 sub endColumn {
250 my ($self) = @_;
251 return unless $$self{in_column};
252 $STATE->getStomach->egroup; # Grouping around CELL!
253 $$self{in_column} = undef;
254 return; }
255  
256 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
257 # Making the Alignment act like a Whatsit
258 sub toString {
259 my ($self) = @_;
260 return "Alignment[]"; }
261  
262 # Methods for overloaded operators
263 sub stringify {
264 my ($self) = @_;
265 return "Alignment[]"; }
266  
267 sub revert {
268 my ($self) = @_;
269 if ($LaTeXML::DUAL_BRANCH && ($LaTeXML::DUAL_BRANCH eq 'content') && $$self{content_reversion}) {
270 return $$self{content_reversion}->unlist; }
271 return $$self{reversion}->unlist; }
272  
273 sub setReversion {
274 my ($self, $tokens) = @_;
275 $$self{reversion} = $tokens;
276 return; }
277  
278 sub setContentReversion {
279 my ($self, $tokens) = @_;
280 $$self{content_reversion} = $tokens;
281 return; }
282  
283 sub computeSize {
284 my ($self) = @_;
285 $self->normalizeAlignment;
286 return ($$self{cwidth}, $$self{cheight}, $$self{cdepth}); }
287  
288 #======================================================================
289 # Constructing the XML for the alignment.
290  
291 sub beAbsorbed {
292 my ($self, $document) = @_;
293 my $attr = $self->getProperty('attributes');
294 my $body = $self->getBody;
295 my $ismath = $$self{isMath};
296 $self->normalizeAlignment;
297 my @rows = @{ $$self{rows} };
298 return unless @rows;
299 # We _should_ attach boxes to the alignment and rows,
300 # but (ATM) we've only got sensible boxes for the cells.
301 &{ $$self{openContainer} }($document, ($attr ? %$attr : ()),
302 cwidth => $$self{cwidth}, cheight => $$self{cheight}, cdepth => $$self{cdepth},
303 rowheights => $$self{rowheights},
304 columnwidths => $$self{columnwidths},
305 );
306 foreach my $row (@rows) {
307 my $vpad = $$row{padding};
308 &{ $$self{openRow} }($document,
309 'xml:id' => $$row{id}, tags => $$row{tags},
310 # Which properties do we expose to the constructor?
311 x => $$row{x}, y => $$row{y},
312 cwidth => $$row{cwidth}, cheight => $$row{cheight}, cdepth => $$row{cdepth},
313 );
314 if (my $before = $$row{before}) {
315 map { $document->absorb($_) } @$before; }
316 foreach my $cell (@{ $$row{columns} }) {
317 next if $$cell{skipped};
318 # Normalize the border attribute
319 my $border = join(' ', sort(map { split(/ */, $_) } $$cell{border} || ''));
320 $border =~ s/(.) \1/$1$1/g;
321 my $empty = $$cell{empty} || !$$cell{boxes} || !scalar($$cell{boxes}->unlist);
322 $$cell{cell} = &{ $$self{openColumn} }($document,
323 align => $$cell{align}, width => $$cell{width},
324 vattach => $$cell{vattach},
325 ($vpad ? (cssstyle => 'padding-bottom:' . ToString($vpad)) : ()),
326 (($$cell{colspan} || 1) != 1 ? (colspan => $$cell{colspan}) : ()),
327 (($$cell{rowspan} || 1) != 1 ? (rowspan => $$cell{rowspan}) : ()),
328 ($border ? (border => $border) : ()),
329 ($$cell{thead} ? (thead => join(' ', sort keys %{ $$cell{thead} })) : ()),
330 # Which properties do we expose to the constructor?
331 x => $$cell{x}, y => $$cell{y},
332 cwidth => $$cell{cwidth}, cheight => $$cell{cheight}, cdepth => $$cell{cdepth},
333 );
334 if (!$empty) {
335 local $LaTeXML::BOX = $$cell{boxes};
336 $document->openElement('ltx:XMArg', rule => 'Anything,') if $ismath; # Hacky!
337 $document->absorb($$cell{boxes});
338 $document->closeElement('ltx:XMArg') if $ismath;
339 }
340 &{ $$self{closeColumn} }($document); }
341 if (my $after = $$row{after}) {
342 map { $document->absorb($_) } @$after; }
343 &{ $$self{closeRow} }($document); }
344 my $node = &{ $$self{closeContainer} }($document);
345  
346 # If we're not nested inside another tabular
347 # [This should be an afterConstruct somewhere?]
348 # If requested to guess headers & we're not nested inside another tabular
349 if (!$document->findnodes("ancestor::ltx:tabular", $node)) {
350 my $hashead = $document->findnodes('descendant::ltx:td[@thead]', $node);
351 # If requested && no cells are already marked as being thead, apply heuristic
352 if ($self->getProperty('guess_headers') && !$hashead) {
353 guess_alignment_headers($document, $node, $self); }
354 # Otherwise, if not a math array, group thead & tbody rows
355 elsif ($hashead && !$body->isMath) { # in case already marked w/thead|tbody
356 alignment_regroup_rows($document, $node); } }
357  
358 return $node; }
359  
360 #======================================================================
361 # Normalize an alignment before construction
362 # * consolodating column & row spanning information
363 # * scanning for empty rows & columns and collapsing them
364 # (while accounting for spanning, and copying borders appropriately)
365 # Note that a trailing \\ in allignment (often needed to effect \hline)
366 # causes an empty row at the end. Other fancy layout fine-tuning often
367 # involves adding extra rows & columsn for spacing. HTML's table model
368 # is more forgiving that TeX's, so we don't need these extras
369 # and, in fact, they often mess up the html layout!
370 # However, math alignments, and those with expected structure (eg. eqnarray)
371 # should generally NOT have rows & columns collapsed --- except the last row!
372  
373 # Also note the inconsistency between TeX & HTML's table models regarding spans.
374 # \multicolumn creates a cell that covers a certain number of columns
375 # which are then omitted from the LaTeX AND the HTML.
376 # OTOH, \multirow creates a cell which overlaps following rows!
377 # The & is still needed to allocate the cells in those rows.
378 # And in fact they need not even be empty! TeX will just pile them up!
379 # However, in HTML the spanned rows ARE omitted!
380 sub normalizeAlignment {
381 my ($self) = @_;
382 return if $$self{normalized};
383 #======================================================================
384 $self->normalize_cell_sizes();
385 $self->normalize_mark_spans();
386 $self->normalize_prune_rows();
387 $self->normalize_prune_columns();
388 $self->normalize_sum_sizes();
389 #======================================================================
390 $$self{normalized} = 1;
391 return; }
392  
393 # Compute (approximate) sizes of all cells
394 sub normalize_cell_sizes {
395 my ($self) = @_;
396 # Examines: boxes, align, vattach
397 # Sets: cwidth, cheight, cdepth (per cell) & empty
398 foreach my $row (@{ $$self{rows} }) {
399 # Do we need to account for any space in the $$row{before} or $$row{after}?
400 foreach my $cell (@{ $$row{columns} }) {
401 if (my $boxes = $$cell{boxes}) {
402 my ($w, $h, $d, $cw, $ch, $cd)
403 = $boxes->getSize(align => $$cell{align}, width => $$cell{width},
404 vattach => $$cell{vattach});
405 Debug("CELL (" . join(',', map { $_ . "=" . ToString($$cell{$_}); } qw(align width vattach))
406 . ") size " . showSize($cw, $ch, $cd)
407 . " Boxes=" . ToString($boxes)) if $LaTeXML::DEBUG{halign} && $LaTeXML::DEBUG{size};
408 my $empty =
409 ((!$cw) || $cw->valueOf < 1)
410 || (((!$ch) || $ch->valueOf < 1)
411 && ((!$cd) || $cd->valueOf < 1))
412 || !(grep { !$_->getProperty('isSpace'); } $boxes->unlist);
413 $$cell{cwidth} = $w || Dimension(0);
414 $$cell{cheight} = $h || Dimension(0);
415 $$cell{cdepth} = $d || Dimension(0);
416 $$cell{empty} = $empty;
417 $$cell{align} = undef if $empty; }
418 else {
419 $$cell{empty} = 1; }
420 } }
421 return; }
422  
423 sub showSize {
424 my ($w, $h, $d) = @_;
425 return '[' . ToString($w) . ' x ' . ToString($h) . ' + ' . ToString($d) . ']'; }
426  
427 sub normalize_sum_sizes {
428 my ($self) = @_;
429 my @rowheights = ();
430 my @colwidths = ();
431 my @colrights = ();
432 my @collefts = ();
433 # Uses cell's cwidth,cheight,cdepth
434 # Computes net row & column sizes & positions
435 # add spacing between rows? Or only from \\[..] ?
436 my $strut = $self->getProperty('strut') || Dimension(0);
437 my $hs = $strut->multiply(0.7);
438 my $ds = $strut->multiply(0.3);
439 my @rows = @{ $$self{rows} };
440 my $nrows = scalar(@rows);
441  
442 for (my $i = 0 ; $i < $nrows ; $i++) {
443 my $row = $rows[$i];
444 my @cols = @{ $$row{columns} };
445 my $ncols = scalar(@cols);
446 if (my $short = $ncols - scalar(@colwidths)) { # Extend column arrays, if needed
447 push(@colwidths, map { 0 } 1 .. $short);
448 push(@collefts, map { 0 } 1 .. $short);
449 push(@colrights, map { 0 } 1 .. $short); }
450 my ($rowh, $rowd) = (0, 0);
451 my ($rowt, $rowb) = (($$row{tpadding} ? $$row{tpadding}->valueOf : 0),
452 ($$row{bpadding} ? $$row{bpadding}->valueOf : 0));
453 for (my $j = 0 ; $j < $ncols ; $j++) {
454 my $cell = $cols[$j];
455 next if $$cell{skipped};
456 next unless $$cell{boxes};
457 my $w = $$cell{cwidth};
458 my $h = $$cell{cheight};
459 my $d = $$cell{cdepth};
460 my $t = $$cell{tpadding};
461 my $b = $$cell{bpadding};
462 my $r = $$cell{rpadding};
463 my $l = $$cell{lpadding};
464  
465 if (($$cell{colspan} || 1) == 1) {
466 $colwidths[$j] = max($colwidths[$j], $w->valueOf) if $w;
467 $collefts[$j] = max($collefts[$j], $l->valueOf) if $l;
468 $colrights[$j] = max($colrights[$j], $r->valueOf) if $r; }
469 if (($$cell{rowspan} || 1) == 1) {
470 $rowh = max($rowh, $h->valueOf) if $h;
471 $rowd = max($rowd, $d->valueOf) if $d;
472 $rowt = max($rowt, $t->valueOf) if $t;
473 $rowb = max($rowb, $b->valueOf) if $b; }
474 else { } # Ditto spanned rows
475 }
476 $$row{cheight} = Dimension($rowh)->larger($hs);
477 $$row{cdepth} = Dimension($rowd)->larger($ds);
478 $$row{tpadding} = Dimension($rowt);
479 $$row{bpadding} = Dimension($rowb);
480 # NOTE: Should be storing column widths to; individually, as well as per-column!
481 push(@rowheights, $rowh + $rowd); } # somehow our heights are way too short????
482 ## Now compute the positions
483 my @rowpos = ();
484 my @colpos = ();
485 my $y = 0;
486 # Row & column positions: left,top
487 for (my $i = 0 ; $i < scalar(@rowheights) ; $i++) {
488 my $row = $rows[$i];
489 $y += $$row{tpadding}->valueOf if $$row{tpadding};
490 $rowpos[$i] = Dimension($y);
491 $y += $$row{cheight}->valueOf if $$row{cheight};
492 $y += $$row{cdepth}->valueOf if $$row{cdepth};
493 $y += $$row{bpadding}->valueOf if $$row{bpadding}; }
494 my $x = 0;
495 for (my $j = 0 ; $j < scalar(@colwidths) ; $j++) {
496 $x += $collefts[$j];
497 $colpos[$j] = Dimension($x);
498 $x += $colwidths[$j];
499 $x += $colrights[$j]; }
500 $$self{cwidth} = Dimension($x);
501 $$self{cheight} = Dimension($y); # or account for vertical position of array as a whole?
502 $$self{cdepth} = Dimension(0);
503 for (my $i = 0 ; $i < scalar(@rowheights) ; $i++) {
504 my $row = $rows[$i];
505 my @cols = @{ $$row{columns} };
506 my $ncols = scalar(@cols);
507 $$row{x} = $colpos[0]; $$row{y} = $rowpos[$i];
508 $$row{cwidth} = Dimension($x);
509 for (my $j = 0 ; $j < $ncols ; $j++) {
510 my $cell = $cols[$j];
511 ## NOTE Should do some further positioning (depending on align!!)
512 ## my $dx = Dimension($colwidths[$j])->subtract($$cell{cwidth})->divide(2);
513 $$cell{x} = $colpos[$j]; $$cell{y} = $rowpos[$i];
514 Debug("CELL[$j,$i] " . showSize($$cell{cwidth}, $$cell{cheight}, $$cell{cdepth})
515 . " @ " . ToString($$cell{x}) . "," . ToString($$cell{y})
516 . " w/ " . join(',', map { $_ . '=' . ToString($$cell{$_}); }
517 (qw(align vattach skipped colspan rowspan))))
518 if $LaTeXML::DEBUG{halign} && $LaTeXML::DEBUG{size};
519 } }
520 $$self{columnwidths} = [map { Dimension($_); } @colwidths];
521 $$self{rowheights} = [map { Dimension($_); } @rowheights];
522 Debug("ALIGNMENT " . showSize($$self{cwidth}, $$self{cheight}, $$self{cdepth}))
523 if $LaTeXML::DEBUG{halign} && $LaTeXML::DEBUG{size};
524 return; }
525  
526 # Mark any cells that are covered by rowspan or colspan
527 sub normalize_mark_spans {
528 my ($self) = @_;
529 # Examines: rowspan, colspan, pseudorow, empty
530 # Sets: skipped, colspanned, rowspanned
531 my @rows = @{ $$self{rows} };
532 for (my $i = 0 ; $i < scalar(@rows) ; $i++) {
533 my $row = $rows[$i];
534 my @row = @{ $$row{columns} };
535 for (my $j = 0 ; $j < scalar(@row) ; $j++) {
536 my $col = $row[$j];
537 my ($nc, $nr);
538 # scan the row for spanned columns that also span rows! Move rowspan to leading column
539 if (($nc = $$col{colspan} || 1) > 1) {
540 foreach (my $jj = $j + 1 ; $jj < $j + $nc ; $jj++) {
541 my $ccol = $row[$jj];
542 $$ccol{skipped} = 1;
543 $$ccol{colspanned} = $j; # note that this column is spanned by column $j
544 if (my $cnr = $$ccol{rowspan}) { # If this spanned column has rowspan
545 $$col{rowspan} = $cnr; } } } # copy rowspan to initial column
546 if (($nr = $$col{rowspan} || 1) > 1) { # If this column spans rows
547 my $nr_orig = $nr;
548 my $ncspan = $$col{colspan} || 1;
549 # Mark all spanned columns in following rows as skipped.
550 my $nrc = $nr;
551 my $ii;
552 for ($ii = $i + 1 ; $nrc ; $ii++) {
553 # Prescan the columns to make sure they're empty!
554 my $rowempty = 1;
555 my $rrow = $rows[$ii];
556 my $rowpseudo = $$rrow{pseudorow};
557 $nrc-- unless $rowpseudo;
558 if ($rrow) {
559 for (my $jj = $j ; $jj < $j + $ncspan ; $jj++) {
560 if (my $ccol = $$rrow{columns}[$jj]) {
561 if (!$$ccol{empty}) {
562 $rowempty = 0; } } } }
563 if (!$nrc) { }
564 elsif (!$rrow || !$rowempty) {
565 # Prescan the columns to make sure they're empty!
566 my $oldnr = $nr;
567 $nr = $$col{rowspan} = $nr - $nrc;
568 $nrc = 0;
569 Info('unexpected', 'rowspan', undef,
570 "Rowspan $oldnr in cell($i,$j) covers non-empty cells; truncating.to $nr"); }
571 elsif ($rrow) {
572 for (my $jj = $j ; $jj < $j + $ncspan ; $jj++) {
573 if (my $ccol = $$rrow{columns}[$jj]) {
574 $$ccol{skipped} = 1;
575 $$ccol{rowspanned} = $i; } } } } # note that this column is spanned by row $i
576 # And, if the last (skipped) columns have a bottom border, copy that to the rowspanned col
577 if (my $rrow = $rows[$ii - 1]) {
578 my $sborder = '';
579 for (my $jj = $j ; $jj < $j + $nc ; $jj++) {
580 if (my $ccol = $$rrow{columns}[$jj]) {
581 my $border = $$ccol{border} || '';
582 $border =~ s/[^bB]//g; # mask all but bottom border
583 $sborder = $border unless $sborder; } }
584 $$col{border} .= $sborder if $sborder; }
585 } } }
586 return; }
587  
588 # Now scan for and remove empty rows & columns
589 # but copying borders and adjusting rowspan's & colspan's appropriately.
590 sub normalize_prune_rows {
591 my ($self) = @_;
592 # Examines: rowspan,rowspanned, border, pseudorow, empty
593 # Sets: border, rowspan
594 my $preserve = $$self{isMath} || $self->getProperty('preserve_structure');
595 # First, do rows.
596 my @rows = @{ $$self{rows} };
597 my @filtered = ();
598 for (my $i = 0 ; $i < scalar(@rows) ; $i++) {
599 my $row = $rows[$i];
600 if (grep { !$$_{empty} } @{ $$row{columns} }) { # Not empty! so keep it
601 push(@filtered, $row); }
602 elsif (my $next = $rows[$i + 1]) { # Remove empty row, but copy top border to NEXT row
603 if ($preserve) {
604 push(@filtered, $row); next; } # don't remove inner rows from math EXCEPT last row!!
605 my $nc = scalar(@{ $$row{columns} });
606 my ($pruneh, $pruned) = (0, 0);
607 for (my $j = 0 ; $j < $nc ; $j++) {
608 my $col = $$row{columns}[$j];
609 $pruneh = max($pruneh, $$col{cheight}->valueOf) if $$col{cheight};
610 $pruned = max($pruned, $$col{cdepth}->valueOf) if $$col{cdepth};
611 if (!$$row{pseudorow} && defined $$col{rowspanned}) {
612 $rows[$$col{rowspanned}]{columns}[$j]{rowspan}--; } # Decrement rowspan of spanning column
613 my $border = $$col{border} || '';
614 $border =~ s/[^tTbB]//g; # mask all but top & bottom border
615 $border =~ s/b/t/g; # but convert to top
616 $border =~ s/B/T/g; # but convert to top
617 $$next{columns}[$j]{border} .= $border; } # add to NEXT row
618 # This tpadding should be combined w/any extra rowspacing from \\[dim] !
619 $$next{tpadding} = Dimension($pruneh + $pruned) if $pruneh + $pruned; } # And save padding.
620 else { # Remove empty last row, but copy top border to bottom of prev.
621 my $prev = $filtered[-1];
622 my $nc = scalar(@{ $$row{columns} });
623 my ($pruneh, $pruned) = (0, 0);
624 for (my $j = 0 ; $j < $nc ; $j++) {
625 my $col = $$row{columns}[$j];
626 $pruneh = max($pruneh, $$col{cheight}->valueOf) if $$col{cheight};
627 $pruned = max($pruned, $$col{cdepth}->valueOf) if $$col{cdepth};
628 if (!$$row{pseudorow} && defined $$col{rowspanned}) {
629 $rows[$$col{rowspanned}]{columns}[$j]{rowspan}--; } # Decrement rowspan of spanning column
630 my $border = $$col{border} || '';
631 $border =~ s/[^tT]//g; # mask all but top border
632 $border =~ s/t/b/g; # convert to bottom
633 $border =~ s/T/B/g; # convert to bottom
634 my $ccol = $$prev{columns}[$j];
635 if (defined $$ccol{rowspanned}) { # skip to spanning column if rowspanned!
636 $ccol = $rows[$$ccol{rowspanned}]{columns}[$j]; }
637 $$ccol{border} .= $border; } # add to PREVIOUS row.
638 $$prev{bpadding} = Dimension($pruneh + $pruned) if $pruneh + $pruned; } # And save padding.
639 }
640 @rows = @filtered;
641 $$self{rows} = [@filtered];
642 return; }
643  
644 sub normalize_prune_columns {
645 my ($self) = @_;
646 my $preserve = $$self{isMath} || $self->getProperty('preserve_structure');
647 # Now prune empty columns.
648 if (!$preserve) { # Don't remove empty columns from math.
649 my @rows = @{ $$self{rows} };
650 my $nc = 0;
651 foreach my $row (@rows) {
652 my $n = scalar(@{ $$row{columns} });
653 $nc = $n if $n > $nc; }
654 for (my $j = $nc - 1 ; $j >= 0 ; $j--) { # Prune from RIGHT!
655 if (!grep { (defined $$_{columns}[$j]) && !$$_{columns}[$j]{empty} } @rows) { # Empty!
656 my $prunew = 0;
657 foreach my $row (@rows) {
658 if (my $col = $$row{columns}[$j]) {
659 if (defined $$col{colspanned}) {
660 $$row{columns}[$$col{colspanned}]{colspan}--; } # Decrement colspan of spanning column
661 $prunew = max($prunew, $$col{cwidth}) if $$col{cwidth};
662 my $border = $$col{border} || '';
663 if ($j > 0) {
664 my $prev = $$row{columns}[$j - 1];
665 if (my $jj = $$prev{colspanned}) {
666 $prev = $$row{columns}[$jj]; }
667 $border =~ s/[^rRlL]//g; # mask all but left border
668 $border =~ s/l/r/g; # convert to right
669 $border =~ s/L/R/g; # convert to right
670 $$prev{border} .= $border;
671 if (my @preserve = preservedBoxes($$col{boxes})) { # Copy boxes over, in case side effects?
672 $$prev{boxes} = LaTeXML::Core::List($$prev{boxes}
673 ? ($$prev{boxes}->unlist, @preserve) : @preserve); }
674 }
675 elsif (my $next = $$row{columns}[1]) {
676 $border =~ s/[^rRlL]//g; # mask all but left & right border
677 $border =~ s/r/l/g; # but convert to left
678 $border =~ s/R/L/g; # but convert to left
679 $$next{border} .= $border; # add to next row
680 if (my @preserve = preservedBoxes($$col{boxes})) { # Copy boxes over, in case side effects?
681 $$next{boxes} = LaTeXML::Core::List($$col{boxes}
682 ? (@preserve, $$next{boxes}->unlist) : @preserve); }
683 } # Now, remove the column
684 $$row{columns} = [grep { $_ ne $col } @{ $$row{columns} }];
685 } }
686 if ($j) { # If not 1st row, add right padding to previous column
687 foreach my $row (@rows) {
688 if (my $col = $$row{columns}[$j - 1]) {
689 $$col{rpadding} = Dimension($prunew); } } }
690 else { # Else add left padding to (newly) first column
691 foreach my $row (@rows) { # And add the padding to previous column
692 if (my $col = $$row{columns}[0]) {
693 $$col{lpadding} = Dimension($prunew); } } }
694 } } }
695 return; }
696  
697 sub show_row {
698 my ($i, $row) = @_;
699 Debug("\nRow[$i]:" . join(', ', map { $_ . '=' . ToString($$row{$_}); }
700 grep { $_ ne 'columns'; } sort keys %$row));
701 my @c = @{ $$row{columns} };
702 for (my $j = 1 ; @c ; $j++) {
703 show_col($i, $j, shift(@c)); }
704 return; }
705  
706 sub show_col {
707 my ($i, $j, $col) = @_;
708 Debug("Column[$i,$j]:" . join(', ', map { $_ . '=' . ToString($$col{$_}); } sort keys %$col));
709 return; }
710  
711 sub preservedBoxes {
712 my ($boxes) = @_;
713 return ($boxes ? grep { $_->getProperty('alignmentPreserve') } $boxes->unlist : ()); }
714 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
715 # Dealing with templates
716  
717 # newcolumntype
718 # defines \NC@rewrite@<char>
719 # As macro
720 # or "constructor" (or just sub that creates a column)
721  
722 sub ReadAlignmentTemplate {
723 my ($gullet) = @_;
724 $gullet->skipSpaces;
725 local $LaTeXML::BUILD_TEMPLATE =
726 LaTeXML::Core::Alignment::Template->new(columns => [], tokens => []);
727 my @tokens = (T_BEGIN);
728 my $nopens = 0;
729 while (my $open = $gullet->readToken) {
730 if ($open->equals(T_BEGIN)) { $nopens++; }
731 else { $gullet->unread($open); last; } }
732 my $defn;
733 while (my $op = $gullet->readToken) {
734 if ($op->equals(T_SPACE)) { }
735 elsif ($op->equals(T_END)) {
736 while (--$nopens && ($op = $gullet->readToken)->equals(T_END)) { }
737 last unless $nopens;
738 $gullet->unread($op); }
739 elsif (defined($defn = $STATE->lookupDefinition(T_CS('\NC@rewrite@' . ToString($op))))
740 && $defn->isExpandable) {
741 $gullet->unread($defn->invoke($gullet, 1)); }
742 elsif ($op->equals(T_BEGIN)) { # Wrong, but a safety valve
743 $gullet->unread($gullet->readBalanced); }
744 else {
745 Warn('unexpected', $op, $gullet, "Unrecognized tabular template '" . Stringify($op) . "'"); }
746 last unless $nopens; }
747 push(@tokens, T_END);
748 $LaTeXML::BUILD_TEMPLATE->setReversion(@tokens);
749 return $LaTeXML::BUILD_TEMPLATE; }
750  
751 sub parseAlignmentTemplate {
752 my ($spec) = @_;
753 return $STATE->getStomach->getGullet->readingFromMouth(LaTeXML::Core::Mouth->new("{" . $spec . "}"), sub {
754 ReadAlignmentTemplate($_[0]); }); }
755  
756 sub MatrixTemplate {
757 return LaTeXML::Core::Alignment::Template->new(repeated => [{ before => Tokens(T_CS('\hfil')),
758 after => Tokens(T_CS('\hfil')) }]); }
759  
760 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
761 # Experimental alignment heading heuristications.
762 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
763 # We attempt to recognize patterns of rows/columns that indicate which might be headers.
764 # We'll characterize the cells by alignment, content and borders.
765 # Then, assuming that headers will be first and be noticably `different' from data lines,
766 # and also that the data lines will have similar structure, we'll attempt to
767 # recognize groups of header lines and groups data lines, possibly alternating.
768  
769 sub guess_alignment_headers {
770 my ($document, $table, $alignment) = @_;
771 # Assume that headers don't make sense for nested tables.
772 # OR Maybe we should only do this within table environments???
773 return if !$table || $document->findnodes("ancestor::ltx:tabular", $table);
774  
775 my $tag = $document->getModel->getNodeQName($table);
776 my $x;
777 Debug(('=' x 50) . "\nGuessing alignment headers for "
778 . (($x = $document->findnode('ancestor-or-self::*[@xml:id]', $table)) ? $x->getAttribute('xml:id') : $tag))
779 if $LaTeXML::DEBUG{alignment};
780  
781 my $ismath = $tag eq 'ltx:XMArray';
782 local $LaTeXML::TR = ($ismath ? 'ltx:XMRow' : 'ltx:tr');
783 local $LaTeXML::TD = ($ismath ? 'ltx:XMCell' : 'ltx:td');
784 my $reversed = 0;
785 # Build a view of the table by extracting the rows, collecting & characterizing each cell.
786 my @rows = collect_alignment_rows($document, $table, $alignment);
787 # Flip the rows around to produce a column view.
788 my @cols = ();
789 return unless @rows;
790 for (my $c = 0 ; $c < scalar(@{ $rows[0] }) ; $c++) {
791 push(@cols, [map { $$_[$c] } @rows]); }
792  
793 # Attempt to recognize header lines.
794 if (alignment_characterize_lines($document, 0, 0, @rows)) { }
795 # This usually does something unpleasant
796 ## else {
797 ## Debug("Retry characterizing lines in reverse") if $LaTeXML::DEBUG{alignment};
798 ## $reversed=alignment_characterize_lines(0,1,reverse(@rows)); }
799 alignment_characterize_lines($document, 1, 0, @cols);
800 # Did we go overboard?
801 my %n = (h => 0, d => 0);
802 foreach my $r (@rows) {
803 foreach my $c (@$r) {
804 $n{ $$c{cell_type} }++; } }
805 Debug("$n{h} header, $n{d} data cells") if $LaTeXML::DEBUG{alignment};
806 if ($n{d} == 1) { # Or any other heuristic?
807 $n{h} = 0;
808 foreach my $r (@rows) {
809 foreach my $c (@$r) {
810 $$c{cell_type} = 'd';
811 $$c{cell}->removeAttribute('thead') if $$c{cell}; } } }
812 # Regroup the rows into thead & tbody elements.
813 # But not if it's a math array, or if reversed (since browsers get confused?)
814 if (!$ismath && !$reversed) {
815 alignment_regroup_rows($document, $table); }
816 if ($n{h}) { # Found some headers?
817 $document->addClass($table, 'ltx_guessed_headers'); }
818  
819 # Debugging report!
820 summarize_alignment([@rows], [@cols]) if $LaTeXML::DEBUG{alignment};
821 return; }
822  
823 #======================================================================
824 # Regroup the rows into thead, tbody & tfoot
825 # Any leading rows, all of whose cells have attribute thead should be in thead.
826 # UNLESS any of them have a rowspan that extends PAST the end of the thead!!!!
827 # trailing rows marked as thead go into tfoot.
828 sub alignment_regroup_rows {
829 my ($document, $table) = @_;
830 my @rows = $document->findnodes("ltx:tr", $table);
831 my @heads = ();
832 my $maxreach = 0;
833 # Scan initial rows as potential thead
834 while (@rows) {
835 my @cells = $document->findnodes('ltx:td', $rows[0]);
836 # Non header cells, done.
837 last if scalar(grep { (!$_->getAttribute('thead')) } @cells);
838 my $line = scalar(@heads);
839 push(@heads, shift(@rows));
840 $maxreach = max($maxreach, map { ($_->getAttribute('rowspan') || 0) + $line } @cells); }
841 if ($maxreach > scalar(@heads)) { # rowspan crossed over thead boundary!
842 unshift(@rows, @heads); @heads = (); }
843 # scan trailing rows as potential tfoot
844 my @foots = ();
845 while (@rows) {
846 my @cells = $document->findnodes('ltx:td', $rows[-1]);
847 # Non header cells, done.
848 last if scalar(grep { (!$_->getAttribute('thead')) } @cells);
849 unshift(@foots, pop(@rows)); }
850 $document->wrapNodes('ltx:thead', @heads) if @heads;
851 $document->wrapNodes('ltx:tbody', @rows) if @rows;
852 $document->wrapNodes('ltx:tfoot', @foots) if @foots;
853 return; }
854  
855 #======================================================================
856 # Build a View of the alignment, with characterized cells, for analysis.
857 my %ALIGNMENT_CODE = ( # CONSTANT
858 right => 'r', left => 'l', center => 'c', justify => 'p');
859  
860 sub collect_alignment_rows {
861 my ($document, $table, $alignment) = @_;
862 my @arows = @{ $$alignment{rows} };
863 my $nrows = scalar(@arows);
864 my $ncols = 0;
865 foreach my $arow (@arows) {
866 my $n = scalar(@{ $$arow{columns} });
867 $ncols = $n if $n > $ncols; }
868 my @rows = ();
869 my ($h, $v) = (0, 0);
870 foreach my $arow (@arows) {
871 push(@rows, []);
872 my @cols = @{ $$arow{columns} };
873 foreach my $col (@cols) {
874 push(@{ $rows[-1] }, $col);
875 $$col{cell_type} = 'd';
876 $$col{content_class} = (($$col{align} || '') eq 'justify' ? 'mx' # Assume mixed content for any justified cell???
877 : ($$col{cell} ? classify_alignment_cell($document, $$col{cell}) : '?'));
878 $$col{content_length} = ($$col{content_class} eq 'g' ? 1000
879 : ($$col{cell} ? length($$col{cell}->textContent) : 0));
880 my %border = (t => 0, r => 0, b => 0, l => 0); # Decode border
881 map { $border{$_}++ } split(/ */, $$col{border} || '');
882 $h = 1 if $border{t} || $border{b};
883 $v = 1 if $border{r} || $border{l};
884 map { $$col{$_} = $border{$_} } keys %border; }
885 # pad the columns out.
886 for (my $c = scalar(@cols) ; $c < $ncols ; $c++) {
887 my $col = {};
888 push(@{ $rows[-1] }, $col);
889 $$col{align} = 'c';
890 $$col{cell_type} = 'd';
891 $$col{content_class} = '_';
892 $$col{content_length} = 0;
893 map { $$col{$_} = 0 } qw(t r b l); }
894 }
895 # copy the characterizations to spanned cells
896 for (my $r = 0 ; $r < $nrows ; $r++) {
897 for (my $c = 0 ; $c < $ncols ; $c++) {
898 my $rs = $rows[$r][$c]{rowspan} || 1;
899 my $cs = $rows[$r][$c]{colspan} || 1;
900 my $ca = $rows[$r][$c]{align};
901 my $cc = $rows[$r][$c]{content_class};
902 my $cl = $rows[$r][$c]{content_length};
903 my $rb = $rows[$r][$c]{r}; $rows[$r][$c]{r} = 0;
904 my $bb = $rows[$r][$c]{b}; $rows[$r][$c]{b} = 0;
905 for (my $sc = 1 ; $sc < $cs ; $sc++) {
906 $rows[$r][$c + $sc]{align} = $ca;
907 $rows[$r][$c + $sc]{content_class} = $cc;
908 $rows[$r][$c + $sc]{content_length} = $cl; }
909 for (my $sr = 1 ; $sr < $rs ; $sr++) {
910 for (my $sc = 0 ; $sc < $cs ; $sc++) {
911 $rows[$r + $sr][$c + $sc]{align} = $ca;
912 $rows[$r + $sr][$c + $sc]{content_class} = $cc;
913 $rows[$r + $sr][$c + $sc]{content_length} = $cl; } }
914 # move the outer borders
915 for (my $sr = 0 ; $sr < $rs ; $sr++) {
916 $rows[$r + $sr][$c + $cs - 1]{r} = $rb; }
917 for (my $sc = 0 ; $sc < $cs ; $sc++) {
918 $rows[$r + $rs - 1][$c + $sc]{b} = $bb; }
919 } }
920  
921 # Now, do some border massaging...
922 for (my $r = 0 ; $r < $nrows ; $r++) {
923 $rows[$r][0]{l} = $v;
924 $rows[$r][0]{r} = $rows[$r][1]{l} if ($ncols > 1) && $rows[$r][1]{l};
925 $rows[$r][$ncols - 1]{l} = $rows[$r][$ncols - 2]{r} if ($ncols > 1) && $rows[$r][$ncols - 2]{r};
926 $rows[$r][$ncols - 1]{r} = $v; }
927 for (my $c = 0 ; $c < $ncols ; $c++) {
928 $rows[0][$c]{t} = $h;
929 $rows[0][$c]{b} = $rows[1][$c]{t} if ($nrows > 1) && $rows[1][$c]{t};
930 $rows[$nrows - 1][$c]{t} = $rows[$nrows - 2][$c]{b} if ($nrows > 1) && $rows[$nrows - 2][$c]{b};
931 $rows[$nrows - 1][$c]{b} = $h; }
932 for (my $r = 1 ; $r < $nrows - 1 ; $r++) {
933 for (my $c = 1 ; $c < $ncols - 1 ; $c++) {
934 $rows[$r][$c]{t} = $rows[$r - 1][$c]{b} if $rows[$r - 1][$c]{b};
935 $rows[$r][$c]{b} = $rows[$r + 1][$c]{t} if $rows[$r + 1][$c]{t};
936 $rows[$r][$c]{l} = $rows[$r][$c - 1]{r} if $rows[$r][$c - 1]{r};
937 $rows[$r][$c]{r} = $rows[$r][$c + 1]{l} if $rows[$r][$c + 1]{l}; } }
938 if ($LaTeXML::DEBUG{alignment}) {
939 Debug("Cell characterizations:");
940 for (my $r = 0 ; $r < $nrows ; $r++) {
941 for (my $c = 0 ; $c < $ncols ; $c++) {
942 my $col = $rows[$r][$c];
943 Debug("[$r,$c]=>" . ($$col{cell_type} || '?')
944 . ($$col{align} ? $ALIGNMENT_CODE{ $$col{align} } : ' ')
945 . ($$col{content_class} || '?')
946 . ' ' . $$col{content_length}
947 . ' ' . $$col{border} . "=>" . join('', grep { $$col{$_} } qw(t r b l))
948 . (($$col{rowspan} || 1) > 1 ? " rowspan=" . $$col{rowspan} : '')
949 . (($$col{colspan} || 1) > 1 ? " colspan=" . $$col{colspan} : '')); } } }
950 return @rows; }
951  
952 # Return one of: i(nteger), t(ext), m(ath), ? (unknown) or '_' (empty) (or some combination)
953 # or 'mx' for alternating text & math.
954 sub classify_alignment_cell {
955 my ($document, $xcell) = @_;
956 my $content = $xcell->textContent;
957 my $class = '';
958 # if($content =~ /^\s*\d+\s*$/){
959 if ($content =~ /^[\s\d]+$/) {
960 $class = 'i'; }
961 else {
962 my @nodes = $xcell->childNodes;
963 while (@nodes) {
964 my $ch = shift(@nodes);
965 my $chtype = $ch->nodeType;
966 if ($chtype == XML_TEXT_NODE) {
967 my $text = $ch->textContent;
968 $class .= 't'
969 unless $text =~ /^\s*$/ || (($class eq 'm') && ($text =~ /^\s*[\.,;]\s*$/)); }
970 elsif ($chtype == XML_ELEMENT_NODE) {
971 my $chtag = $document->getModel->getNodeQName($ch);
972 if ($chtag eq 'ltx:text') { # Font would be useful, but haven't "resolved" it, yet!
973 $class .= 't' unless $class eq 't'; }
974 elsif ($chtag eq 'ltx:graphics') {
975 $class .= 'g' unless $class eq 'g'; }
976 elsif ($chtag eq 'ltx:Math') {
977 $class .= 'm' unless $class eq 'm'; }
978 elsif ($chtag eq 'ltx:XMText') {
979 $class .= 't' unless $class eq 't'; }
980 elsif ($chtag eq 'ltx:XMArg') {
981 unshift(@nodes, $ch->childNodes); }
982 elsif ($chtag =~ /^ltx:XM/) {
983 $class .= 'm' unless $class eq 'm'; }
984 else {
985 $class .= '?' unless $class; }
986 } } }
987 $class = 'mx' if $class && (($class =~ /^((m|i)t)+(m|i)?$/) || ($class =~ /^(t(m|i))+t?$/));
988 return $class || '_'; }
989  
990 #======================================================================
991 # Scan pairs of rows/columns attempting to recognize differences that
992 # might indicate which are headers and which are data.
993 # Warning: This section is full of "magic numbers"
994 # guessed by sampling various test cases.
995  
996 my $MIN_ALIGNMENT_DATA_LINES = 1; # (or 2?) [CONSTANT]
997 my $MAX_ALIGNMENT_HEADER_LINES = 4; # [CONSTANT]
998  
999 # We expect to find header lines at the beginning, noticably different from the eventual data lines.
1000 # Both header lines and data lines can consist of several neighboring lines.
1001 # Check that header lines are `similar' to each other. So, the strategy is to look
1002 # for a `hump' in the line differences and consider blocks containing these lines to be potential headers.
1003 my @axisname = ('column', 'row');
1004  
1005 sub alignment_characterize_lines {
1006 my ($document, $axis, $reversed, @lines) = @_;
1007 my $n = scalar(@lines);
1008 return if $n < 2;
1009 local @::TABLINES = @lines;
1010 Debug("Characterizing $n " . ($axis ? "columns" : "rows"))
1011 if $LaTeXML::DEBUG{alignment};
1012  
1013 # Establish a scale of differences for the table.
1014 my ($diffhi, $difflo, $diffavg) = (0, 99999999, 0);
1015 for (my $l = 0 ; $l < $n - 1 ; $l++) {
1016 my $d = alignment_compare($axis, 1, $reversed, $l, $l + 1);
1017 $diffavg += $d;
1018 $diffhi = $d if $d > $diffhi;
1019 $difflo = $d if $d < $difflo; }
1020 $diffavg = $diffavg / ($n - 1);
1021 if ($diffhi < 0.05) { # virtually no differences.
1022 Debug("Lines are almost identical => Fail") if $LaTeXML::DEBUG{alignment};
1023 return; }
1024 if (($n > 2) && (($diffhi - $difflo) < $diffhi * 0.5)) { # differences too similar to establish pattern
1025 Debug("Differences between lines are almost identical => Fail")
1026 if $LaTeXML::DEBUG{alignment};
1027 return; }
1028 # local $::TAB_THRESHOLD = $difflo + 0.4*($diffhi-$difflo);
1029 local $::TAB_THRESHOLD = $difflo + 0.3 * ($diffhi - $difflo);
1030 # local $::TAB_THRESHOLD = $difflo + 0.2*($diffhi-$difflo);
1031 # local $::TAB_THRESHOLD = $diffavg;
1032 local $::TAB_AXIS = $axis;
1033 Debug("Differences $difflo -- $diffhi => threshold = $::TAB_THRESHOLD")
1034 if $LaTeXML::DEBUG{alignment};
1035 # Find the first hump in differences. These are candidates for header lines.
1036 Debug("Scanning for headers") if $LaTeXML::DEBUG{alignment};
1037 my $diff;
1038 my ($minh, $maxh) = (1, 1);
1039 while (($diff = alignment_compare($axis, 1, $reversed, $maxh - 1, $maxh)) < $::TAB_THRESHOLD) {
1040 $maxh++; }
1041 return if $maxh > $MAX_ALIGNMENT_HEADER_LINES; # too many before even finding diffs? give up!
1042 # while( alignment_compare($axis,1,$reversed,$maxh,$maxh+1) > $difflo + ($diff-$difflo)/6){
1043 while (alignment_compare($axis, 1, $reversed, $maxh, $maxh + 1) > $::TAB_THRESHOLD) {
1044 $maxh++; }
1045 $maxh = $MAX_ALIGNMENT_HEADER_LINES if $maxh > $MAX_ALIGNMENT_HEADER_LINES;
1046 Debug("Found from $minh--$maxh potential headers") if $LaTeXML::DEBUG{alignment};
1047  
1048 my $nn = scalar(@{ $lines[0] }) - 1;
1049 # The sets of lines 1--$minh, .. 1--$maxh are potential headers.
1050 for (my $nh = $maxh ; $nh >= $minh ; $nh--) {
1051 # for(my $nh = $minh; $nh <= $maxh; $nh++){
1052 # Check whether the set 1..$nh is plausable.
1053 if (my @heads = alignment_test_headers($nh)) {
1054 # Now, change all cells marked as header from td => th.
1055 foreach my $h (@heads) {
1056 my $i = 0;
1057 foreach my $cell (@{ $lines[$h] }) {
1058 $$cell{cell_type} = 'h';
1059 if (my $xcell = $$cell{cell}) {
1060 if (($$cell{content_class} eq '_') # But NOT empty cells on outer edges.
1061 && ((($i == 0) && !$$cell{ ($axis == 0 ? 'l' : 't') })
1062 || (($i == $nn) && !$$cell{ ($axis == 0 ? 'r' : 'b') }))) { }
1063 else {
1064 $document->addSSValues($$cell{cell}, thead => $axisname[$axis]); } }
1065 $i++; } }
1066 return 1; } }
1067 return; }
1068  
1069 # Test whether $nhead lines makes a good fit for the headers
1070 sub alignment_test_headers {
1071 my ($nhead) = @_;
1072 Debug("Testing $nhead headers") if $LaTeXML::DEBUG{alignment};
1073 my ($headlength, $datalength) = (0, 0);
1074 my @heads = (0 .. $nhead - 1); # The indices of heading lines.
1075 $headlength = alignment_max_content_length($headlength, 0, $nhead - 1);
1076 my $nextline = $nhead; # Start from the end of the proposed headings.
1077  
1078 # Watch out for the assumed header being really data that is a repeated pattern.
1079 my $nrep = scalar(@::TABLINES) / $nhead;
1080 if (($nhead > 1) && ($nrep == int($nrep))) {
1081 Debug("Check for apparent header repeated $nrep times") if $LaTeXML::DEBUG{alignment};
1082 my $matched = 1;
1083 for (my $r = 1 ; $r < $nrep ; $r++) {
1084 $matched &&= alignment_match_head(0, $r * $nhead, $nhead); }
1085 Debug("Repeated headers: " . ($matched ? "Matched=> Fail" : "Nomatch => Succeed"))
1086 if $LaTeXML::DEBUG{alignment};
1087 return if $matched; }
1088  
1089 # And find a following grouping of data lines.
1090 my $ndata = alignment_skip_data($nextline);
1091 return if $ndata < $nhead; # ???? Well, maybe if _really_ convincing???
1092 return if ($ndata < $nhead) && ($ndata < 2);
1093 # Check that the content of the headers isn't dramatically larger than the content in the data
1094 $datalength = alignment_max_content_length($datalength, $nextline, $nextline + $ndata - 1);
1095 $nextline += $ndata;
1096  
1097 my $nd;
1098 # If there are more lines, they should match either the previous data block, or the head/data pattern.
1099 while ($nextline < scalar(@::TABLINES)) {
1100 # First try to match a repeat of the 1st data block;
1101 # This would be the case when groups of data have borders around them.
1102 # Could want to match a variable number of datalines, but they should be similar!!!??!?!?
1103 if (($ndata > 1) && ($nd = alignment_match_data($nhead, $nextline, $ndata))) {
1104 $datalength = alignment_max_content_length($datalength, $nextline, $nextline + $nd - 1);
1105 $nextline += $nd; }
1106 # Else, try to match the first header block; less common.
1107 elsif (alignment_match_head(0, $nextline, $nhead)) {
1108 push(@heads, $nextline .. $nextline + $nhead - 1);
1109 $headlength = alignment_max_content_length($headlength, $nextline, $nextline + $nhead - 1);
1110 $nextline += $nhead;
1111 # Then attempt to match a new data block.
1112 # my $d = alignment_skip_data($nextline);
1113 # return unless ($d >= $nhead) || ($d >= 2);
1114 # $nextline += $d; }
1115 # No, better be the same data block?
1116 return unless ($nd = alignment_match_data($nhead, $nextline, $ndata));
1117 $datalength = alignment_max_content_length($datalength, $nextline, $nextline + $nd - 1);
1118 $nextline += $nd; }
1119 else { return; } }
1120 # Header content seems too large relative to data?
1121 Debug("header content = $headlength; data content = $datalength")
1122 if $LaTeXML::DEBUG{alignment};
1123 ## if(($headlength > 10) && (0.3*$headlength > $datalength)){
1124 if (($headlength > 10) && (0.25 * $headlength > $datalength)) {
1125 Debug("header content too much longer than data content")
1126 if $LaTeXML::DEBUG{alignment};
1127 return; }
1128 # Or if a header cell has "large" content?
1129 if ($headlength >= 1000) { # Or if a header cell has "large" content?
1130 Debug("header content too large")
1131 if $LaTeXML::DEBUG{alignment};
1132 return; }
1133  
1134 Debug("Succeeded with $nhead headers") if $LaTeXML::DEBUG{alignment};
1135 return @heads; }
1136  
1137 sub alignment_match_head {
1138 my ($p1, $p2, $nhead) = @_;
1139 Debug("Try match $nhead header lines from $p1 to $p2") if $LaTeXML::DEBUG{alignment};
1140 my $nh = alignment_match_lines($p1, $p2, $nhead);
1141 my $ok = $nhead == $nh;
1142 Debug("Matched $nh header lines => " . ($ok ? "Succeed" : "Failed")) if $LaTeXML::DEBUG{alignment};
1143 return ($ok ? $nhead : 0); }
1144  
1145 sub alignment_match_data {
1146 my ($p1, $p2, $ndata) = @_;
1147 Debug("Try match $ndata data lines from $p1 to $p2")
1148 if $LaTeXML::DEBUG{alignment};
1149 my $nd = alignment_match_lines($p1, $p2, $ndata);
1150 my $ok = ($nd * 1.0) / $ndata > 0.66;
1151 Debug("Matched $nd data lines => " . ($ok ? "Succeed" : "Failed"))
1152 if $LaTeXML::DEBUG{alignment};
1153 return ($ok ? $nd : 0); }
1154  
1155 # Match the $n lines starting at $i2 to those starting at $i1.
1156 sub alignment_match_lines {
1157 my ($p1, $p2, $n) = @_;
1158 for (my $i = 0 ; $i < $n ; $i++) {
1159 return $i if ($p1 + $i >= scalar(@::TABLINES)) || ($p2 + $i >= scalar(@::TABLINES))
1160 || alignment_compare($::TAB_AXIS, 0, 0, $p1 + $i, $p2 + $i) >= $::TAB_THRESHOLD; }
1161 return $n; }
1162  
1163 # Skip through a block of lines starting at $i that appear to be data, returning the number of lines.
1164 # We'll assume the 1st line is data, compare it to following lines,
1165 # but also accept `continuation' data lines.
1166 sub alignment_skip_data {
1167 my ($i) = @_;
1168 return 0 if $i >= scalar(@::TABLINES);
1169 Debug("Scanning for data") if $LaTeXML::DEBUG{alignment};
1170 my $n = 1;
1171 while ($i + $n < scalar(@::TABLINES)) {
1172 last if (alignment_compare($::TAB_AXIS, 1, 0, $i + $n - 1, $i + $n) >= $::TAB_THRESHOLD)
1173 # Accept an outlying `continuation line' as data, if mostly empty
1174 && (($n < 2)
1175 || (scalar(grep { $$_{content_class} eq '_' } @{ $::TABLINES[$i + $n] }) <= 0.4 * scalar($::TABLINES[0])));
1176 $n++; }
1177 Debug("Found $n data lines at $i") if $LaTeXML::DEBUG{alignment};
1178 return ($n >= $MIN_ALIGNMENT_DATA_LINES ? $n : 0); }
1179  
1180 sub XXXalignment_max_content_length {
1181 my ($length, $from, $to) = @_;
1182 foreach my $j (($from .. $to)) {
1183 foreach my $cell (@{ $::TABLINES[$j] }) {
1184 $length = $$cell{content_length}
1185 if $$cell{content_length} && ($$cell{content_length} > $length); } }
1186 return $length; }
1187  
1188 # Return the maximum "content length" for lines from $from to $to.
1189 sub alignment_max_content_length {
1190 my ($length, $from, $to) = @_;
1191 foreach my $j (($from .. $to)) {
1192 my $l = 0;
1193 foreach my $cell (@{ $::TABLINES[$j] }) {
1194 $l += $$cell{content_length} || 0; }
1195 $length = $l if $l > $length; }
1196 return $length; }
1197  
1198 #======================================================================
1199 # The comparator.
1200 # our %cell_class_diff =
1201 # ('_'=>{'_'=>0.0, m=>0.1, i=>0.1, t=>0.1, '?'=>0.1, mx=>0.1},
1202 # m =>{'_'=>0.1, m=>0.0, i=>0.1, mx=>0.2},
1203 # i =>{'_'=>0.1, m=>0.1, i=>0.0, mx=>0.2},
1204 # t =>{'_'=>0.1, t=>0.0, mx=>0.2},
1205 # '?'=>{'_'=>0.1, '?'=>0.0, mx=>0.2},
1206 # mx=>{'_'=>0.1, m=>0.2, i=>0.2, t=>0.2, '?'=>0.2, mx=>0.0});
1207  
1208 my %cell_class_diff = ( # [CONSTANT]
1209 '_' => { '_' => 0.0, m => 0.05, i => 0.05, t => 0.05, '?' => 0.05, mx => 0.05 },
1210 m => { '_' => 0.05, m => 0.0, i => 0.1, mx => 0.2 },
1211 i => { '_' => 0.05, m => 0.1, i => 0.0, mx => 0.2 },
1212 t => { '_' => 0.05, t => 0.0, mx => 0.2 },
1213 '?' => { '_' => 0.05, '?' => 0.0, mx => 0.2 },
1214 mx => { '_' => 0.05, m => 0.2, i => 0.2, t => 0.2, '?' => 0.2, mx => 0.0 });
1215  
1216 # Compare two lines along $axis (0=row,1=column), returning a measure of the difference.
1217 # The borders are compared differently if
1218 # $foradjacency: we adjacent lines that might belong to the same block,
1219 # otherwise : comparing two lines that ought to have identical patterns (eg. in a repeated block)
1220 sub alignment_compare {
1221 my ($axis, $foradjacency, $reversed, $p1, $p2) = @_;
1222 my $line1 = $::TABLINES[$p1];
1223 my $line2 = $::TABLINES[$p2];
1224 return 0 if !($line1 && $line2);
1225 return 999999 if $line1 xor $line2;
1226 my @cells1 = @$line1;
1227 my @cells2 = @$line2;
1228 my $ncells = scalar(@cells1);
1229 my $diff = 0.0;
1230  
1231 while (@cells1 && @cells2) {
1232 my $cell1 = shift(@cells1);
1233 my $cell2 = shift(@cells2);
1234 # Annoying test avoids warnings if cells inconsistent; likely due to incorrect row/col spans
1235 next if grep { !defined $$cell1{$_} } qw(content_class r l t b);
1236 next if grep { !defined $$cell2{$_} } qw(content_class r l t b);
1237 # $diff += 0.5 if (($$cell1{align}||'') ne ($$cell2{align}||''))
1238 $diff += 0.75 if (($$cell1{align} || '') ne ($$cell2{align} || ''))
1239 && ($$cell1{content_class} ne '_') && ($$cell2{content_class} ne '_');
1240 if (my $d = $cell_class_diff{ $$cell1{content_class} }{ $$cell2{content_class} }) {
1241 $diff += $d; }
1242 elsif ($$cell1{content_class} ne $$cell2{content_class}) {
1243 $diff += 0.75; }
1244 # compare certain edges
1245 if ($foradjacency) { # Compare edges for adjacent rows of potentially different purpose
1246 $diff += 0.3 * scalar(grep { $$cell1{$_} != $$cell2{$_} } ($axis == 0 ? qw(r l) : qw(t b)));
1247 # Penalty for apparent divider between.
1248 my $pedge = ($axis == 0 ? ($reversed ? 't' : 'b') : ($reversed ? 'l' : 'r'));
1249 if ($$cell1{$pedge} && ($$cell1{$pedge} != $$cell2{$pedge})) {
1250 $diff += abs($$cell1{$pedge} - $$cell2{$pedge}) * 1.0; }
1251 }
1252 else { # Compare edges for rows from diff places for potential similarity
1253 $diff += 0.3 * scalar(grep { $$cell1{$_} != $$cell2{$_} } qw(r l t b)); }
1254 }
1255 $diff /= $ncells;
1256 Debug("$p1-$p2 => $diff; ") if $LaTeXML::DEBUG{alignment};
1257 return $diff; }
1258  
1259 #======================================================================
1260 # Debugging.
1261 sub summarize_alignment {
1262 my ($rows, $cols) = @_;
1263 my $r = 0;
1264 my ($nrows, $ncols) = (scalar(@$rows), scalar(@{ $$rows[0] }));
1265 foreach my $cell (@{ $$rows[0] }) {
1266 Debug(' ' . ($$cell{t} ? ('-' x 6) : (' ' x 6))); }
1267 foreach my $row (@$rows) {
1268 my $maxb = 0;
1269 Debug(($$row[0]{l} ? ('|' x $$row[0]{l}) : ' '));
1270 foreach my $cell (@$row) {
1271 Debug(sprintf(" %4s ",
1272 ($$cell{cell_type} || '?')
1273 . ($$cell{align} ? $ALIGNMENT_CODE{ $$cell{align} } : ' ')
1274 . ($$cell{content_class} || '?')
1275 . ($$cell{r} ? ('|' x $$cell{r}) : ' ')));
1276 $maxb = $$cell{b} if $$cell{b} > $maxb; }
1277 # Debug(sprintf("%.3f",alignment_compare(0,1,$$rows[$r],$$rows[$r+1])) if ($r < $nrows-1));
1278 for (my $b = 0 ; $b < $maxb ; $b++) {
1279 foreach my $cell (@$row) {
1280 Debug(' ' . ($b < $$cell{b} ? ('-' x 6) : (' ' x 6))); } }
1281 $r++; }
1282 # for(my $c = 0; $c < $ncols-1; $c++){
1283 # Debug(sprintf(" %.3f ",alignment_compare(1,1,$$cols[$c],$$cols[$c+1]))); }
1284 return; }
1285  
1286 #======================================================================
1287 1;
1288  
1289 __END__
« lib/LaTeXML/Core.pm ↑ Summary lib/LaTeXML/Core/Definition/Expandable.pm »