| 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 | use strict; | ||
| 14 | use warnings; | ||
| 15 | use LaTeXML::Global; | ||
| 16 | use LaTeXML::Common::Error; | ||
| 17 | use LaTeXML::Core::Token; | ||
| 18 | use LaTeXML::Core::Tokens; | ||
| 19 | use LaTeXML::Common::Object; | ||
| 20 | use LaTeXML::Common::XML; | ||
| 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 \@open@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 | |||
| 52 | # Create a new Alignment. | ||
| 53 | # %data can contain: | ||
| 54 | # template : an Alignment::Template object | ||
| 55 | # openContainer = sub($doc,%attrib); creates the container element with given attributes | ||
| 56 | # closeContainer = sub($doc); closes the container | ||
| 57 | # openRow = sub($doc,%attrib); creates the row element with given attributes | ||
| 58 | # closeRow = closes the row | ||
| 59 | # openColumn = sub($doc,%attrib); creates the column element with given attributes | ||
| 60 | # closeColumn = closes the column | ||
| 61 | # attributes = hashref containing extra attributes for the container element. | ||
| 62 | sub new { | ||
| 63 | my ($class, %data) = @_; | ||
| 64 | my $self = bless {%data}, $class; | ||
| 65 | $$self{template} = LaTeXML::Core::Alignment::Template->new() unless $$self{template}; | ||
| 66 | $$self{template} = parseAlignmentTemplate($$self{template}) unless ref $$self{template}; | ||
| 67 | $$self{rows} = []; | ||
| 68 | $$self{current_column} = 0; | ||
| 69 | $$self{current_row} = undef; | ||
| 70 | $$self{properties} = {} unless $$self{properties}; | ||
| 71 | # Copy any attribute width, height, depth to main properties. | ||
| 72 | if (my $attributes = $$self{properties}{attributes}) { | ||
| 73 | $$self{properties}{width} = $$attributes{width} if $$attributes{width}; | ||
| 74 | $$self{properties}{height} = $$attributes{height} if $$attributes{height}; | ||
| 75 | $$self{properties}{depth} = $$attributes{depth} if $$attributes{depth}; } | ||
| 76 | return $self; } | ||
| 77 | |||
| 78 | #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | ||
| 79 | # Alignment specific accessors | ||
| 80 | sub getTemplate { | ||
| 81 | my ($self, $template) = @_; | ||
| 82 | return $$self{template}; } | ||
| 83 | |||
| 84 | sub currentRow { | ||
| 85 | my ($self) = @_; | ||
| 86 | return $$self{current_row}; } | ||
| 87 | |||
| 88 | sub newRow { | ||
| 89 | my ($self) = @_; | ||
| 90 | my $row = $$self{template}->clone; | ||
| 91 | $$self{current_row} = $row; | ||
| 92 | $$self{current_column} = 0; | ||
| 93 | push(@{ $$self{rows} }, $row); | ||
| 94 | return $row; } | ||
| 95 | |||
| 96 | sub removeRow { | ||
| 97 | my ($self) = @_; | ||
| 98 | my @rows = @{ $$self{rows} }; | ||
| 99 | if (@rows) { | ||
| 100 | my $row = pop(@rows); | ||
| 101 | $$self{rows} = [@rows]; | ||
| 102 | return $row; } | ||
| 103 | else { | ||
| 104 | return; } } | ||
| 105 | |||
| 106 | sub prependRows { | ||
| 107 | my ($self, @rows) = @_; | ||
| 108 | unshift(@{ $$self{rows} }, @rows); | ||
| 109 | return; } | ||
| 110 | |||
| 111 | sub appendRows { | ||
| 112 | my ($self, @rows) = @_; | ||
| 113 | push(@{ $$self{rows} }, @rows); | ||
| 114 | return; } | ||
| 115 | |||
| 116 | sub rows { | ||
| 117 | my ($self) = @_; | ||
| 118 | return @{ $$self{rows} }; } | ||
| 119 | |||
| 120 | sub addLine { | ||
| 121 | my ($self, $border, @cols) = @_; | ||
| 122 | my $row = $$self{current_row}; | ||
| 123 | if (@cols) { | ||
| 124 | foreach my $c (@cols) { | ||
| 125 | my $colspec = $row->column($c); | ||
| 126 | $$colspec{border} .= $border; } } | ||
| 127 | else { | ||
| 128 | foreach my $colspec (@{ $$row{columns} }) { | ||
| 129 | $$colspec{border} .= $border; } } | ||
| 130 | return; } | ||
| 131 | |||
| 132 | sub nextColumn { | ||
| 133 | my ($self) = @_; | ||
| 134 | return unless $$self{current_row}; | ||
| 135 | my $colspec = $$self{current_row}->column(++$$self{current_column}); | ||
| 136 | if (!$colspec) { | ||
| 137 | Error('unexpected', '&', $STATE->getStomach->getGullet, "Extra alignment tab '&'"); | ||
| 138 | $$self{current_row}->addColumn(align => 'center'); | ||
| 139 | $colspec = $$self{current_row}->column($$self{current_column}); } | ||
| 140 | return $colspec; } | ||
| 141 | |||
| 142 | sub currentColumnNumber { | ||
| 143 | my ($self) = @_; | ||
| 144 | return $$self{current_column}; } | ||
| 145 | |||
| 146 | sub currentRowNumber { | ||
| 147 | my ($self) = @_; | ||
| 148 | return scalar(@{ $$self{rows} }); } | ||
| 149 | |||
| 150 | sub currentColumn { | ||
| 151 | my ($self) = @_; | ||
| 152 | return $$self{current_row} && $$self{current_row}->column($$self{current_column}); } | ||
| 153 | |||
| 154 | sub getColumn { | ||
| 155 | my ($self, $n) = @_; | ||
| 156 | return $$self{current_row} && $$self{current_row}->column($n); } | ||
| 157 | |||
| 158 | # Ugh... these take boxes; adding before/after columns takes tokens! | ||
| 159 | sub addBeforeRow { | ||
| 160 | my ($self, @boxes) = @_; | ||
| 161 | $$self{current_row}{before} = [@{ $$self{current_row}{before} || [] }, @boxes]; | ||
| 162 | return; } | ||
| 163 | |||
| 164 | sub addAfterRow { | ||
| 165 | my ($self, @boxes) = @_; | ||
| 166 | $$self{current_row}{after} = [@{ $$self{current_row}{after} || [] }, @boxes]; | ||
| 167 | return; } | ||
| 168 | |||
| 169 | #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | ||
| 170 | # Making the Alignment act like a Whatsit | ||
| 171 | sub toString { | ||
| 172 | my ($self) = @_; | ||
| 173 | return "Alignment[]"; } | ||
| 174 | |||
| 175 | # Methods for overloaded operators | ||
| 176 | sub stringify { | ||
| 177 | my ($self) = @_; | ||
| 178 | return "Alignment[]"; } | ||
| 179 | |||
| 180 | sub revert { | ||
| 181 | my ($self) = @_; | ||
| 182 | return $self->getBody->revert; } | ||
| 183 | |||
| 184 | sub computeSize_internal { | ||
| 185 | my ($self) = @_; | ||
| 186 | $self->normalizeAlignment; | ||
| 187 | my @rowheights = (); | ||
| 188 | my @colwidths = (); | ||
| 189 | # add \baselineskip between rows? Or max the row heights with it ... | ||
| 190 | my $base = $STATE->lookupDefinition(T_CS('\baselineskip'))->valueOf->valueOf; | ||
| 191 | foreach my $row (@{ $$self{rows} }) { | ||
| 192 | # Do we need to account for any space in the $$row{before} or $$row{after}? | ||
| 193 | my @cols = @{ $$row{columns} }; | ||
| 194 | my $ncols = scalar(@cols); | ||
| 195 | if (my $short = $ncols - scalar(@colwidths)) { | ||
| 196 | push(@colwidths, map { 0 } 1 .. $short); } | ||
| 197 | my ($rowh, $rowd) = ($base * 0.7, $base * 0.3); | ||
| 198 | for (my $i = 0 ; $i < $ncols ; $i++) { | ||
| 199 | my $cell = $cols[$i]; | ||
| 200 | next if $$cell{skipped}; | ||
| 201 | next unless $$cell{boxes}; | ||
| 202 | my ($w, $h, $d) = $$cell{boxes}->getSize(align => $$cell{align}, width => $$cell{width}, | ||
| 203 | vattach => $$cell{vattach}); | ||
| 204 | if (($$cell{colspan} || 1) == 1) { | ||
| 205 | $colwidths[$i] = max($colwidths[$i], $w->valueOf); } | ||
| 206 | else { } # Could check afterwards that spanned columns are wide enough? | ||
| 207 | if (($$cell{rowspan} || 1) == 1) { | ||
| 208 | $rowh = max($rowh, $h->valueOf); | ||
| 209 | $rowd = max($rowd, $d->valueOf); } | ||
| 210 | else { } # Ditto spanned rows | ||
| 211 | } | ||
| 212 | push(@rowheights, $rowh + $rowd + 0.5 * $base); } # somehow our heights are way too short???? | ||
| 213 | return ([@rowheights],[@colwidths]); } | ||
| 214 | |||
| 215 | sub computeSize { | ||
| 216 | my ($self, %options) = @_; | ||
| 217 | my ($rowheights, $colwidths) = $self->computeSize_internal(); | ||
| 218 | my $props = $self->getPropertiesRef; | ||
| 219 | my $ww = Dimension(sum(@$colwidths)); | ||
| 220 | my $hh = Dimension(sum(@$rowheights)); | ||
| 221 | my $dd = Dimension(0); | ||
| 222 | $$props{width} = $ww unless defined $$props{width}; | ||
| 223 | $$props{height} = $hh unless defined $$props{height}; | ||
| 224 | $$props{depth} = $dd unless defined $$props{depth}; | ||
| 225 | return; } | ||
| 226 | |||
| 227 | #====================================================================== | ||
| 228 | # Constructing the XML for the alignment. | ||
| 229 | |||
| 230 | sub beAbsorbed { | ||
| 231 | my ($self, $document) = @_; | ||
| 232 | my $attr = $self->getProperty('attributes'); | ||
| 233 | my $body = $self->getBody; | ||
| 234 | my $ismath = $$self{isMath}; | ||
| 235 | $self->normalizeAlignment; | ||
| 236 | # We _should_ attach boxes to the alignment and rows, | ||
| 237 | # but (ATM) we've only got sensible boxes for the cells. | ||
| 238 | &{ $$self{openContainer} }($document, ($attr ? %$attr : ())); | ||
| 239 | foreach my $row (@{ $$self{rows} }) { | ||
| 240 | &{ $$self{openRow} }($document, 'xml:id' => $$row{id}, tags => $$row{tags}); | ||
| 241 | if (my $before = $$row{before}) { | ||
| 242 | map { $document->absorb($_) } @$before; } | ||
| 243 | foreach my $cell (@{ $$row{columns} }) { | ||
| 244 | next if $$cell{skipped}; | ||
| 245 | # Normalize the border attribute | ||
| 246 | my $border = join(' ', sort(map { split(/ */, $_) } $$cell{border} || '')); | ||
| 247 | $border =~ s/(.) \1/$1$1/g; | ||
| 248 | my $empty = !$$cell{boxes} || !scalar($$cell{boxes}->unlist); | ||
| 249 | $$cell{cell} = &{ $$self{openColumn} }($document, | ||
| 250 | align => $$cell{align}, width => $$cell{width}, | ||
| 251 | vattach => $$cell{vattach}, | ||
| 252 | (($$cell{colspan} || 1) != 1 ? (colspan => $$cell{colspan}) : ()), | ||
| 253 | (($$cell{rowspan} || 1) != 1 ? (rowspan => $$cell{rowspan}) : ()), | ||
| 254 | ($border ? (border => $border) : ()), | ||
| 255 | ($$cell{thead} ? (thead => join(' ', sort keys %{ $$cell{thead} })) : ())); | ||
| 256 | if (!$empty) { | ||
| 257 | local $LaTeXML::BOX = $$cell{boxes}; | ||
| 258 | $document->openElement('ltx:XMArg', rule => 'Anything,') if $ismath; # Hacky! | ||
| 259 | $document->absorb($$cell{boxes}); | ||
| 260 | $document->closeElement('ltx:XMArg') if $ismath; | ||
| 261 | } | ||
| 262 | &{ $$self{closeColumn} }($document); } | ||
| 263 | if (my $after = $$row{after}) { | ||
| 264 | map { $document->absorb($_) } @$after; } | ||
| 265 | &{ $$self{closeRow} }($document); } | ||
| 266 | my $node = &{ $$self{closeContainer} }($document); | ||
| 267 | |||
| 268 | # If we're not nested inside another tabular | ||
| 269 | # [This should be an afterConstruct somewhere?] | ||
| 270 | # If requested to guess headers & we're not nested inside another tabular | ||
| 271 | if (!$document->findnodes("ancestor::ltx:tabular", $node)) { | ||
| 272 | ## my $hashead = $document->findnodes('descendant::ltx:td[contains(@class,"thead")]', $node); | ||
| 273 | my $hashead = $document->findnodes('descendant::ltx:td[@thead]', $node); | ||
| 274 | # If requested && no cells are already marked as being thead, apply heuristic | ||
| 275 | if ($self->getProperty('guess_headers') && !$hashead) { | ||
| 276 | guess_alignment_headers($document, $node, $self); } | ||
| 277 | # Otherwise, if not a math array, group thead & tbody rows | ||
| 278 | elsif ($hashead && !$body->isMath) { # in case already marked w/thead|tbody | ||
| 279 | alignment_regroup_rows($document, $node); } } | ||
| 280 | |||
| 281 | return $node; } | ||
| 282 | |||
| 283 | #====================================================================== | ||
| 284 | # Normalize an alignment before construction | ||
| 285 | # * consolodating column & row spanning information | ||
| 286 | # * scanning for empty rows & columns and collapsing them | ||
| 287 | # (while accounting for spanning, and copying borders appropriately) | ||
| 288 | # Note that a trailing \\ in allignment (often needed to effect \hline) | ||
| 289 | # causes an empty row at the end. Other fancy layout fine-tuning often | ||
| 290 | # involves adding extra rows & columsn for spacing. HTML's table model | ||
| 291 | # is more forgiving that TeX's, so we don't need these extras | ||
| 292 | # and, in fact, they often mess up the html layout! | ||
| 293 | # However, math alignments, and those with expected structure (eg. eqnarray) | ||
| 294 | # should generally NOT have rows & columns collapsed --- except the last row! | ||
| 295 | |||
| 296 | # Also note the inconsistency between TeX & HTML's table models regarding spans. | ||
| 297 | # \multicolumn creates a cell that covers a certain number of columns | ||
| 298 | # which are then omitted from the LaTeX AND the HTML. | ||
| 299 | # OTOH, \multirow creates a cell which overlaps following rows! | ||
| 300 | # The & is still needed to allocate the cells in those rows. | ||
| 301 | # And in fact they need not even be empty! TeX will just pile them up! | ||
| 302 | # However, in HTML the spanned rows ARE omitted! | ||
| 303 | sub normalizeAlignment { | ||
| 304 | my ($self) = @_; | ||
| 305 | return if $$self{normalized}; | ||
| 306 | my $ismath = $$self{isMath}; | ||
| 307 | my $preserve = $$self{isMath} || $self->getProperty('preserve_structure'); | ||
| 308 | |||
| 309 | my @rows = @{ $$self{rows} }; | ||
| 310 | # Mark any cells that are covered by rowspans | ||
| 311 | for (my $i = 0 ; $i < scalar(@rows) ; $i++) { | ||
| 312 | my @row = @{ $rows[$i]->{columns} }; | ||
| 313 | |||
| 314 | for (my $j = 0 ; $j < scalar(@row) ; $j++) { | ||
| 315 | my $col = $row[$j]; | ||
| 316 | my ($nc, $nr); | ||
| 317 | # scan the row for spanned columns that also span rows! Move rowspan to leading column | ||
| 318 | if (($nc = $$col{colspan} || 1) > 1) { | ||
| 319 | foreach (my $jj = $j + 1 ; $jj < $j + $nc ; $jj++) { | ||
| 320 | my $ccol = $row[$jj]; | ||
| 321 | $$ccol{skipped} = 1; | ||
| 322 | $$ccol{colspanned} = $j; # note that this column is spanned by column $j | ||
| 323 | if (my $nr = $$ccol{rowspan}) { # If this spanned column has rowspan | ||
| 324 | $$col{rowspan} = $nr; } } } # copy rowspan to initial column | ||
| 325 | if (($nr = $$col{rowspan} || 1) > 1) { # If this column spans rows | ||
| 326 | my $nr_orig = $nr; | ||
| 327 | my $nc = $$col{colspan} || 1; | ||
| 328 | # Mark all spanned columns in following rows as skipped. | ||
| 329 | for (my $ii = $i + 1 ; $ii < $i + $nr ; $ii++) { | ||
| 330 | # Prescan the columns to make sure they're empty! | ||
| 331 | my $rowempty = 1; | ||
| 332 | my $rrow = $rows[$ii]; | ||
| 333 | if ($rrow) { | ||
| 334 | for (my $jj = $j ; $jj < $j + $nc ; $jj++) { | ||
| 335 | if (my $ccol = $$rrow{columns}[$jj]) { | ||
| 336 | if (!$$ccol{empty}) { | ||
| 337 | $rowempty = 0; } } } } | ||
| 338 | if (!$rrow || !$rowempty) { | ||
| 339 | # Prescan the columns to make sure they're empty! | ||
| 340 | $nr = $$col{rowspan} = $ii - $i; | ||
| 341 | Info('unexpected', 'rowspan', undef, | ||
| 342 | "Rowspan in cell($i,$j) covers non-empty cells; truncating."); } | ||
| 343 | elsif ($rrow) { | ||
| 344 | for (my $jj = $j ; $jj < $j + $nc ; $jj++) { | ||
| 345 | if (my $ccol = $$rrow{columns}[$jj]) { | ||
| 346 | $$ccol{skipped} = 1; | ||
| 347 | $$ccol{rowspanned} = $i; } } } # note that this column is spanned by row $i | ||
| 348 | } | ||
| 349 | # And, if the last (skipped) columns have a bottom border, copy that to the rowspanned col | ||
| 350 | if (my $rrow = $rows[$i + $nr - 1]) { | ||
| 351 | my $sborder = ''; | ||
| 352 | for (my $jj = $j ; $jj < $j + $nc ; $jj++) { | ||
| 353 | if (my $ccol = $$rrow{columns}[$jj]) { | ||
| 354 | my $border = $$ccol{border} || ''; | ||
| 355 | $border =~ s/[^bB]//g; # mask all but bottom border | ||
| 356 | $sborder = $border unless $sborder; } } | ||
| 357 | $$col{border} .= $sborder if $sborder; } | ||
| 358 | } } } | ||
| 359 | |||
| 360 | # if (!$ismath) { # Best not to do this in math? At least not in equationgroups! | ||
| 361 | # Now scan for and remove empty rows & columns | ||
| 362 | # but copying borders and adjusting rowspan's & colspan's appropriately. | ||
| 363 | # First, do rows. | ||
| 364 | my @filtered = (); | ||
| 365 | for (my $i = 0 ; $i < scalar(@rows) ; $i++) { | ||
| 366 | my $row = $rows[$i]; | ||
| 367 | foreach my $col (@{ $$row{columns} }) { # Mark all empty columns | ||
| 368 | $$col{empty} = 1 unless $$col{boxes} && $$col{boxes}->unlist; } | ||
| 369 | if (grep { !$$_{empty} } @{ $$row{columns} }) { # Not empty! so keep it | ||
| 370 | push(@filtered, $row); } | ||
| 371 | elsif (my $next = $rows[$i + 1]) { # Remove empty row, but copy top border to NEXT row | ||
| 372 | if ($preserve) { | ||
| 373 | push(@filtered, $row); next; } # don't remove inner rows from math | ||
| 374 | my $nc = scalar(@{ $$row{columns} }); | ||
| 375 | for (my $j = 0 ; $j < $nc ; $j++) { | ||
| 376 | my $col = $$row{columns}[$j]; | ||
| 377 | if (defined $$col{rowspanned}) { | ||
| 378 | $rows[$$col{rowspanned}]{columns}[$j]{rowspan}--; } # Decrement rowspan of spanning column | ||
| 379 | my $border = $$col{border} || ''; | ||
| 380 | $border =~ s/[^tTbB]//g; # mask all but top & bottom border | ||
| 381 | $border =~ s/b/t/g; # but convert to top | ||
| 382 | $border =~ s/B/T/g; # but convert to top | ||
| 383 | $$next{columns}[$j]{border} .= $border; } } # add to next row | ||
| 384 | else { # Remove empty last row, but copy top border to bottom of prev. | ||
| 385 | my $prev = $filtered[-1]; | ||
| 386 | my $nc = scalar(@{ $$row{columns} }); | ||
| 387 | for (my $j = 0 ; $j < $nc ; $j++) { | ||
| 388 | my $col = $$row{columns}[$j]; | ||
| 389 | if (defined $$col{rowspanned}) { | ||
| 390 | $rows[$$col{rowspanned}]{columns}[$j]{rowspan}--; } # Decrement rowspan of spanning column | ||
| 391 | my $border = $$col{border} || ''; | ||
| 392 | $border =~ s/[^tT]//g; # mask all but top border | ||
| 393 | $border =~ s/t/b/g; # convert to bottom | ||
| 394 | $border =~ s/T/B/g; # convert to bottom | ||
| 395 | my $ccol = $$prev{columns}[$j]; | ||
| 396 | if (defined $$ccol{rowspanned}) { # skip to spanning column if rowspanned! | ||
| 397 | $ccol = $rows[$$ccol{rowspanned}]{columns}[$j]; } | ||
| 398 | $$ccol{border} .= $border; } } # add to previous row. | ||
| 399 | } | ||
| 400 | @rows = @filtered; | ||
| 401 | $$self{rows} = [@filtered]; | ||
| 402 | #return; | ||
| 403 | # Now columns. | ||
| 404 | if (!$preserve) { # Don't remove empty columns from math. | ||
| 405 | my $nc = 0; | ||
| 406 | foreach my $row (@rows) { | ||
| 407 | my $n = scalar(@{ $$row{columns} }); | ||
| 408 | $nc = $n if $n > $nc; } | ||
| 409 | for (my $j = $nc - 1 ; $j >= 0 ; $j--) { | ||
| 410 | if (!grep { (defined $$_{columns}[$j]) && !$$_{columns}[$j]{empty} } @rows) { # Empty! | ||
| 411 | foreach my $row (@rows) { | ||
| 412 | if (my $col = $$row{columns}[$j]) { | ||
| 413 | if (defined $$col{colspanned}) { | ||
| 414 | $$row{columns}[$$col{colspanned}]{colspan}--; } # Decrement colspan of spanning column | ||
| 415 | my $border = $$col{border} || ''; | ||
| 416 | if ($j > 0) { | ||
| 417 | my $prev = $$row{columns}[$j - 1]; | ||
| 418 | if (my $jj = $$prev{colspanned}) { | ||
| 419 | $prev = $$row{columns}[$jj]; } | ||
| 420 | $border =~ s/[^rRlL]//g; # mask all but left border | ||
| 421 | $border =~ s/l/r/g; # convert to right | ||
| 422 | $border =~ s/L/R/g; # convert to right | ||
| 423 | $$prev{border} .= $border; | ||
| 424 | if (my @preserve = preservedBoxes($$col{boxes})) { # Copy boxes over, in case side effects? | ||
| 425 | $$prev{boxes} = LaTeXML::Core::List($$prev{boxes} | ||
| 426 | ? ($$prev{boxes}->unlist, @preserve) : @preserve); } | ||
| 427 | } | ||
| 428 | elsif (my $next = $$row{columns}[1]) { | ||
| 429 | my $border = $$col{border} || ''; | ||
| 430 | $border =~ s/[^rRlL]//g; # mask all but left & right border | ||
| 431 | $border =~ s/r/l/g; # but convert to left | ||
| 432 | $border =~ s/R/L/g; # but convert to left | ||
| 433 | $$next{border} .= $border; # add to next row | ||
| 434 | if (my @preserve = preservedBoxes($$col{boxes})) { # Copy boxes over, in case side effects? | ||
| 435 | $$next{boxes} = LaTeXML::Core::List($$col{boxes} | ||
| 436 | ? (@preserve, $$next{boxes}->unlist) : @preserve); } | ||
| 437 | } # Now, remove the column | ||
| 438 | $$row{columns} = [grep { $_ ne $col } @{ $$row{columns} }]; | ||
| 439 | } } } } | ||
| 440 | } | ||
| 441 | $$self{normalized} = 1; | ||
| 442 | return; } | ||
| 443 | |||
| 444 | sub preservedBoxes { | ||
| 445 | my ($boxes) = @_; | ||
| 446 | return ($boxes ? grep { $_->getProperty('alignmentPreserve') } $boxes->unlist : ()); } | ||
| 447 | #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | ||
| 448 | # Dealing with templates | ||
| 449 | |||
| 450 | # newcolumntype | ||
| 451 | # defines \NC@rewrite@<char> | ||
| 452 | # As macro | ||
| 453 | # or "constructor" (or just sub that creates a column) | ||
| 454 | |||
| 455 | sub ReadAlignmentTemplate { | ||
| 456 | my ($gullet) = @_; | ||
| 457 | $gullet->skipSpaces; | ||
| 458 | local $LaTeXML::BUILD_TEMPLATE = | ||
| 459 | LaTeXML::Core::Alignment::Template->new(columns => [], tokens => []); | ||
| 460 | my @tokens = (T_BEGIN); | ||
| 461 | my $nopens = 0; | ||
| 462 | while (my $open = $gullet->readToken) { | ||
| 463 | if ($open->equals(T_BEGIN)) { $nopens++; } | ||
| 464 | else { $gullet->unread($open); last; } } | ||
| 465 | my $defn; | ||
| 466 | while (my $op = $gullet->readToken) { | ||
| 467 | if ($op->equals(T_SPACE)) { } | ||
| 468 | elsif ($op->equals(T_END)) { | ||
| 469 | while (--$nopens && ($op = $gullet->readToken)->equals(T_END)) { } | ||
| 470 | last unless $nopens; | ||
| 471 | $gullet->unread($op); } | ||
| 472 | elsif (defined($defn = $STATE->lookupDefinition(T_CS('\NC@rewrite@' . ToString($op)))) | ||
| 473 | && $defn->isExpandable) { | ||
| 474 | # A variation on $defn->invoke, so we can reconstruct the reversion | ||
| 475 | my @args = $defn->readArguments($gullet); | ||
| 476 | if (my $exp = $defn->doInvocation($gullet, @args)) { # This just expanded into other stuff | ||
| 477 | $gullet->unread(@{$exp}); } | ||
| 478 | else { | ||
| 479 | push(@tokens, $op); | ||
| 480 | if (my $param = $defn->getParameters) { | ||
| 481 | push(@tokens, $param->revertArguments(@args)); } } } | ||
| 482 | elsif ($op->equals(T_BEGIN)) { # Wrong, but a safety valve | ||
| 483 | $gullet->unread($gullet->readBalanced->unlist); } | ||
| 484 | else { | ||
| 485 | Warn('unexpected', $op, $gullet, "Unrecognized tabular template '" . Stringify($op) . "'"); } | ||
| 486 | last unless $nopens; } | ||
| 487 | push(@tokens, T_END); | ||
| 488 | $LaTeXML::BUILD_TEMPLATE->setReversion(@tokens); | ||
| 489 | return $LaTeXML::BUILD_TEMPLATE; } | ||
| 490 | |||
| 491 | sub parseAlignmentTemplate { | ||
| 492 | my ($spec) = @_; | ||
| 493 | return $STATE->getStomach->getGullet->readingFromMouth(LaTeXML::Core::Mouth->new("{" . $spec . "}"), sub { | ||
| 494 | ReadAlignmentTemplate($_[0]); }); } | ||
| 495 | |||
| 496 | sub MatrixTemplate { | ||
| 497 | return LaTeXML::Core::Alignment::Template->new(repeated => [{ before => Tokens(T_CS('\hfil')), | ||
| 498 | after => Tokens(T_CS('\hfil')) }]); } | ||
| 499 | |||
| 500 | #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | ||
| 501 | # Experimental alignment heading heuristications. | ||
| 502 | #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | ||
| 503 | # We attempt to recognize patterns of rows/columns that indicate which might be headers. | ||
| 504 | # We'll characterize the cells by alignment, content and borders. | ||
| 505 | # Then, assuming that headers will be first and be noticably `different' from data lines, | ||
| 506 | # and also that the data lines will have similar structure, we'll attempt to | ||
| 507 | # recognize groups of header lines and groups data lines, possibly alternating. | ||
| 508 | |||
| 509 | sub guess_alignment_headers { | ||
| 510 | my ($document, $table, $alignment) = @_; | ||
| 511 | # Assume that headers don't make sense for nested tables. | ||
| 512 | # OR Maybe we should only do this within table environments??? | ||
| 513 | return if $document->findnodes("ancestor::ltx:tabular", $table); | ||
| 514 | |||
| 515 | my $tag = $document->getModel->getNodeQName($table); | ||
| 516 | my $x; | ||
| 517 | print STDERR "\n" . ('=' x 50) . "\nGuessing alignment headers for " | ||
| 518 | . (($x = $document->findnode('ancestor-or-self::*[@xml:id]', $table)) ? $x->getAttribute('xml:id') : $tag) . "\n" | ||
| 519 | if $LaTeXML::Core::Alignment::DEBUG; | ||
| 520 | |||
| 521 | my $ismath = $tag eq 'ltx:XMArray'; | ||
| 522 | local $LaTeXML::TR = ($ismath ? 'ltx:XMRow' : 'ltx:tr'); | ||
| 523 | local $LaTeXML::TD = ($ismath ? 'ltx:XMCell' : 'ltx:td'); | ||
| 524 | my $reversed = 0; | ||
| 525 | # Build a view of the table by extracting the rows, collecting & characterizing each cell. | ||
| 526 | my @rows = collect_alignment_rows($document, $table, $alignment); | ||
| 527 | # Flip the rows around to produce a column view. | ||
| 528 | my @cols = (); | ||
| 529 | return unless @rows; | ||
| 530 | for (my $c = 0 ; $c < scalar(@{ $rows[0] }) ; $c++) { | ||
| 531 | push(@cols, [map { $$_[$c] } @rows]); } | ||
| 532 | |||
| 533 | # Attempt to recognize header lines. | ||
| 534 | if (alignment_characterize_lines($document, 0, 0, @rows)) { } | ||
| 535 | # This usually does something unpleasant | ||
| 536 | ## else { | ||
| 537 | ## print STDERR "Retry characterizing lines in reverse\n" if $LaTeXML::Core::Alignment::DEBUG; | ||
| 538 | ## $reversed=alignment_characterize_lines(0,1,reverse(@rows)); } | ||
| 539 | alignment_characterize_lines($document, 1, 0, @cols); | ||
| 540 | # Did we go overboard? | ||
| 541 | my %n = (h => 0, d => 0); | ||
| 542 | foreach my $r (@rows) { | ||
| 543 | foreach my $c (@$r) { | ||
| 544 | $n{ $$c{cell_type} }++; } } | ||
| 545 | print STDERR "$n{h} header, $n{d} data cells\n" if $LaTeXML::Core::Alignment::DEBUG; | ||
| 546 | if ($n{d} == 1) { # Or any other heuristic? | ||
| 547 | $n{h} = 0; | ||
| 548 | foreach my $r (@rows) { | ||
| 549 | foreach my $c (@$r) { | ||
| 550 | $$c{cell_type} = 'd'; | ||
| 551 | $$c{cell}->removeAttribute('thead') if $$c{cell}; } } } | ||
| 552 | # Regroup the rows into thead & tbody elements. | ||
| 553 | # But not if it's a math array, or if reversed (since browsers get confused?) | ||
| 554 | if (!$ismath && !$reversed) { | ||
| 555 | alignment_regroup_rows($document, $table); } | ||
| 556 | if ($n{h}) { # Found some headers? | ||
| 557 | $document->addClass($table, 'ltx_guessed_headers'); } | ||
| 558 | |||
| 559 | # Debugging report! | ||
| 560 | summarize_alignment([@rows], [@cols]) if $LaTeXML::Core::Alignment::DEBUG; | ||
| 561 | return; } | ||
| 562 | |||
| 563 | #====================================================================== | ||
| 564 | # Regroup the rows into thead, tbody & tfoot | ||
| 565 | # Any leading rows, all of whose cells have attribute thead should be in thead. | ||
| 566 | # UNLESS any of them have a rowspan that extends PAST the end of the thead!!!! | ||
| 567 | # trailing rows marked as thead go into tfoot. | ||
| 568 | sub alignment_regroup_rows { | ||
| 569 | my ($document, $table) = @_; | ||
| 570 | my @rows = $document->findnodes("ltx:tr", $table); | ||
| 571 | my @heads = (); | ||
| 572 | my $maxreach = 0; | ||
| 573 | # Scan initial rows as potential thead | ||
| 574 | while (@rows) { | ||
| 575 | my @cells = $document->findnodes('ltx:td', $rows[0]); | ||
| 576 | # Non header cells, done. | ||
| 577 | last if scalar(grep { (!$_->getAttribute('thead')) } @cells); | ||
| 578 | my $line = scalar(@heads); | ||
| 579 | push(@heads, shift(@rows)); | ||
| 580 | $maxreach = max($maxreach, map { ($_->getAttribute('rowspan') || 0) + $line } @cells); } | ||
| 581 | if ($maxreach > scalar(@heads)) { # rowspan crossed over thead boundary! | ||
| 582 | unshift(@rows, @heads); @heads = (); } | ||
| 583 | # scan trailing rows as potential tfoot | ||
| 584 | my @foots = (); | ||
| 585 | while (@rows) { | ||
| 586 | my @cells = $document->findnodes('ltx:td', $rows[-1]); | ||
| 587 | # Non header cells, done. | ||
| 588 | last if scalar(grep { (!$_->getAttribute('thead')) } @cells); | ||
| 589 | unshift(@foots, pop(@rows)); } | ||
| 590 | $document->wrapNodes('ltx:thead', @heads) if @heads; | ||
| 591 | $document->wrapNodes('ltx:tbody', @rows) if @rows; | ||
| 592 | $document->wrapNodes('ltx:tfoot', @foots) if @foots; | ||
| 593 | return; } | ||
| 594 | |||
| 595 | #====================================================================== | ||
| 596 | # Build a View of the alignment, with characterized cells, for analysis. | ||
| 597 | my %ALIGNMENT_CODE = ( # CONSTANT | ||
| 598 | right => 'r', left => 'l', center => 'c', justify => 'p'); | ||
| 599 | |||
| 600 | sub collect_alignment_rows { | ||
| 601 | my ($document, $table, $alignment) = @_; | ||
| 602 | my @arows = @{ $$alignment{rows} }; | ||
| 603 | my $nrows = scalar(@arows); | ||
| 604 | my $ncols = 0; | ||
| 605 | foreach my $arow (@arows) { | ||
| 606 | my $n = scalar(@{ $$arow{columns} }); | ||
| 607 | $ncols = $n if $n > $ncols; } | ||
| 608 | my @rows = (); | ||
| 609 | my ($h, $v) = (0, 0); | ||
| 610 | foreach my $arow (@arows) { | ||
| 611 | push(@rows, []); | ||
| 612 | my @cols = @{ $$arow{columns} }; | ||
| 613 | foreach my $col (@cols) { | ||
| 614 | push(@{ $rows[-1] }, $col); | ||
| 615 | $$col{cell_type} = 'd'; | ||
| 616 | $$col{content_class} = (($$col{align} || '') eq 'justify' ? 'mx' # Assume mixed content for any justified cell??? | ||
| 617 | : ($$col{cell} ? classify_alignment_cell($document, $$col{cell}) : '?')); | ||
| 618 | $$col{content_length} = ($$col{content_class} eq 'g' ? 1000 | ||
| 619 | : ($$col{cell} ? length($$col{cell}->textContent) : 0)); | ||
| 620 | my %border = (t => 0, r => 0, b => 0, l => 0); # Decode border | ||
| 621 | map { $border{$_}++ } split(/ */, $$col{border} || ''); | ||
| 622 | $h = 1 if $border{t} || $border{b}; | ||
| 623 | $v = 1 if $border{r} || $border{l}; | ||
| 624 | map { $$col{$_} = $border{$_} } keys %border; } | ||
| 625 | # pad the columns out. | ||
| 626 | for (my $c = scalar(@cols) ; $c < $ncols ; $c++) { | ||
| 627 | my $col = {}; | ||
| 628 | push(@{ $rows[-1] }, $col); | ||
| 629 | $$col{align} = 'c'; | ||
| 630 | $$col{cell_type} = 'd'; | ||
| 631 | $$col{content_class} = '_'; | ||
| 632 | $$col{content_length} = 0; | ||
| 633 | map { $$col{$_} = 0 } qw(t r b l); } | ||
| 634 | } | ||
| 635 | # copy the characterizations to spanned cells | ||
| 636 | for (my $r = 0 ; $r < $nrows ; $r++) { | ||
| 637 | for (my $c = 0 ; $c < $ncols ; $c++) { | ||
| 638 | my $rs = $rows[$r][$c]{rowspan} || 1; | ||
| 639 | my $cs = $rows[$r][$c]{colspan} || 1; | ||
| 640 | my $ca = $rows[$r][$c]{align}; | ||
| 641 | my $cc = $rows[$r][$c]{content_class}; | ||
| 642 | my $cl = $rows[$r][$c]{content_length}; | ||
| 643 | my $rb = $rows[$r][$c]{r}; $rows[$r][$c]{r} = 0; | ||
| 644 | my $bb = $rows[$r][$c]{b}; $rows[$r][$c]{b} = 0; | ||
| 645 | for (my $sc = 1 ; $sc < $cs ; $sc++) { | ||
| 646 | $rows[$r][$c + $sc]{align} = $ca; | ||
| 647 | $rows[$r][$c + $sc]{content_class} = $cc; | ||
| 648 | $rows[$r][$c + $sc]{content_length} = $cl; } | ||
| 649 | for (my $sr = 1 ; $sr < $rs ; $sr++) { | ||
| 650 | for (my $sc = 0 ; $sc < $cs ; $sc++) { | ||
| 651 | $rows[$r + $sr][$c + $sc]{align} = $ca; | ||
| 652 | $rows[$r + $sr][$c + $sc]{content_class} = $cc; | ||
| 653 | $rows[$r + $sr][$c + $sc]{content_length} = $cl; } } | ||
| 654 | # move the outer borders | ||
| 655 | for (my $sr = 0 ; $sr < $rs ; $sr++) { | ||
| 656 | $rows[$r + $sr][$c + $cs - 1]{r} = $rb; } | ||
| 657 | for (my $sc = 0 ; $sc < $cs ; $sc++) { | ||
| 658 | $rows[$r + $rs - 1][$c + $sc]{b} = $bb; } | ||
| 659 | } } | ||
| 660 | |||
| 661 | # Now, do some border massaging... | ||
| 662 | for (my $r = 0 ; $r < $nrows ; $r++) { | ||
| 663 | $rows[$r][0]{l} = $v; | ||
| 664 | $rows[$r][0]{r} = $rows[$r][1]{l} if ($ncols > 1) && $rows[$r][1]{l}; | ||
| 665 | $rows[$r][$ncols - 1]{l} = $rows[$r][$ncols - 2]{r} if ($ncols > 1) && $rows[$r][$ncols - 2]{r}; | ||
| 666 | $rows[$r][$ncols - 1]{r} = $v; } | ||
| 667 | for (my $c = 0 ; $c < $ncols ; $c++) { | ||
| 668 | $rows[0][$c]{t} = $h; | ||
| 669 | $rows[0][$c]{b} = $rows[1][$c]{t} if ($nrows > 1) && $rows[1][$c]{t}; | ||
| 670 | $rows[$nrows - 1][$c]{t} = $rows[$nrows - 2][$c]{b} if ($nrows > 1) && $rows[$nrows - 2][$c]{b}; | ||
| 671 | $rows[$nrows - 1][$c]{b} = $h; } | ||
| 672 | for (my $r = 1 ; $r < $nrows - 1 ; $r++) { | ||
| 673 | for (my $c = 1 ; $c < $ncols - 1 ; $c++) { | ||
| 674 | $rows[$r][$c]{t} = $rows[$r - 1][$c]{b} if $rows[$r - 1][$c]{b}; | ||
| 675 | $rows[$r][$c]{b} = $rows[$r + 1][$c]{t} if $rows[$r + 1][$c]{t}; | ||
| 676 | $rows[$r][$c]{l} = $rows[$r][$c - 1]{r} if $rows[$r][$c - 1]{r}; | ||
| 677 | $rows[$r][$c]{r} = $rows[$r][$c + 1]{l} if $rows[$r][$c + 1]{l}; } } | ||
| 678 | if ($LaTeXML::Core::Alignment::DEBUG) { | ||
| 679 | print STDERR "\nCell characterizations:\n"; | ||
| 680 | for (my $r = 0 ; $r < $nrows ; $r++) { | ||
| 681 | for (my $c = 0 ; $c < $ncols ; $c++) { | ||
| 682 | my $col = $rows[$r][$c]; | ||
| 683 | print STDERR "[$r,$c]=>" . ($$col{cell_type} || '?') | ||
| 684 | . ($$col{align} ? $ALIGNMENT_CODE{ $$col{align} } : ' ') | ||
| 685 | . ($$col{content_class} || '?') | ||
| 686 | . ' ' . $$col{content_length} | ||
| 687 | . ' ' . $$col{border} . "=>" . join('', grep { $$col{$_} } qw(t r b l)) | ||
| 688 | . (($$col{rowspan} || 1) > 1 ? " rowspan=" . $$col{rowspan} : '') | ||
| 689 | . (($$col{colspan} || 1) > 1 ? " colspan=" . $$col{colspan} : '') | ||
| 690 | . "\n"; } } } | ||
| 691 | return @rows; } | ||
| 692 | |||
| 693 | # Return one of: i(nteger), t(ext), m(ath), ? (unknown) or '_' (empty) (or some combination) | ||
| 694 | # or 'mx' for alternating text & math. | ||
| 695 | sub classify_alignment_cell { | ||
| 696 | my ($document, $xcell) = @_; | ||
| 697 | my $content = $xcell->textContent; | ||
| 698 | my $class = ''; | ||
| 699 | # if($content =~ /^\s*\d+\s*$/){ | ||
| 700 | if ($content =~ /^[\s\d]+$/) { | ||
| 701 | $class = 'i'; } | ||
| 702 | else { | ||
| 703 | my @nodes = $xcell->childNodes; | ||
| 704 | while (@nodes) { | ||
| 705 | my $ch = shift(@nodes); | ||
| 706 | my $chtype = $ch->nodeType; | ||
| 707 | if ($chtype == XML_TEXT_NODE) { | ||
| 708 | my $text = $ch->textContent; | ||
| 709 | $class .= 't' | ||
| 710 | unless $text =~ /^\s*$/ || (($class eq 'm') && ($text =~ /^\s*[\.,;]\s*$/)); } | ||
| 711 | elsif ($chtype == XML_ELEMENT_NODE) { | ||
| 712 | my $chtag = $document->getModel->getNodeQName($ch); | ||
| 713 | if ($chtag eq 'ltx:text') { # Font would be useful, but haven't "resolved" it, yet! | ||
| 714 | $class .= 't' unless $class eq 't'; } | ||
| 715 | elsif ($chtag eq 'ltx:graphics') { | ||
| 716 | $class .= 'g' unless $class eq 'g'; } | ||
| 717 | elsif ($chtag eq 'ltx:Math') { | ||
| 718 | $class .= 'm' unless $class eq 'm'; } | ||
| 719 | elsif ($chtag eq 'ltx:XMText') { | ||
| 720 | $class .= 't' unless $class eq 't'; } | ||
| 721 | elsif ($chtag eq 'ltx:XMArg') { | ||
| 722 | unshift(@nodes, $ch->childNodes); } | ||
| 723 | elsif ($chtag =~ /^ltx:XM/) { | ||
| 724 | $class .= 'm' unless $class eq 'm'; } | ||
| 725 | else { | ||
| 726 | $class .= '?' unless $class; } | ||
| 727 | } } } | ||
| 728 | $class = 'mx' if $class && (($class =~ /^((m|i)t)+(m|i)?$/) || ($class =~ /^(t(m|i))+t?$/)); | ||
| 729 | return $class || '_'; } | ||
| 730 | |||
| 731 | #====================================================================== | ||
| 732 | # Scan pairs of rows/columns attempting to recognize differences that | ||
| 733 | # might indicate which are headers and which are data. | ||
| 734 | # Warning: This section is full of "magic numbers" | ||
| 735 | # guessed by sampling various test cases. | ||
| 736 | |||
| 737 | my $MIN_ALIGNMENT_DATA_LINES = 1; # (or 2?) [CONSTANT] | ||
| 738 | my $MAX_ALIGNMENT_HEADER_LINES = 4; # [CONSTANT] | ||
| 739 | |||
| 740 | # We expect to find header lines at the beginning, noticably different from the eventual data lines. | ||
| 741 | # Both header lines and data lines can consist of several neighboring lines. | ||
| 742 | # Check that header lines are `similar' to each other. So, the strategy is to look | ||
| 743 | # for a `hump' in the line differences and consider blocks containing these lines to be potential headers. | ||
| 744 | my @axisname = ('column', 'row'); | ||
| 745 | |||
| 746 | sub alignment_characterize_lines { | ||
| 747 | my ($document, $axis, $reversed, @lines) = @_; | ||
| 748 | my $n = scalar(@lines); | ||
| 749 | return if $n < 2; | ||
| 750 | local @::TABLINES = @lines; | ||
| 751 | print STDERR "\nCharacterizing $n " . ($axis ? "columns" : "rows") . "\n " | ||
| 752 | if $LaTeXML::Core::Alignment::DEBUG; | ||
| 753 | |||
| 754 | # Establish a scale of differences for the table. | ||
| 755 | my ($diffhi, $difflo, $diffavg) = (0, 99999999, 0); | ||
| 756 | for (my $l = 0 ; $l < $n - 1 ; $l++) { | ||
| 757 | my $d = alignment_compare($axis, 1, $reversed, $l, $l + 1); | ||
| 758 | $diffavg += $d; | ||
| 759 | $diffhi = $d if $d > $diffhi; | ||
| 760 | $difflo = $d if $d < $difflo; } | ||
| 761 | $diffavg = $diffavg / ($n - 1); | ||
| 762 | if ($diffhi < 0.05) { # virtually no differences. | ||
| 763 | print STDERR "Lines are almost identical => Fail\n" if $LaTeXML::Core::Alignment::DEBUG; | ||
| 764 | return; } | ||
| 765 | if (($n > 2) && (($diffhi - $difflo) < $diffhi * 0.5)) { # differences too similar to establish pattern | ||
| 766 | print STDERR "Differences between lines are almost identical => Fail\n" | ||
| 767 | if $LaTeXML::Core::Alignment::DEBUG; | ||
| 768 | return; } | ||
| 769 | # local $::TAB_THRESHOLD = $difflo + 0.4*($diffhi-$difflo); | ||
| 770 | local $::TAB_THRESHOLD = $difflo + 0.3 * ($diffhi - $difflo); | ||
| 771 | # local $::TAB_THRESHOLD = $difflo + 0.2*($diffhi-$difflo); | ||
| 772 | # local $::TAB_THRESHOLD = $diffavg; | ||
| 773 | local $::TAB_AXIS = $axis; | ||
| 774 | print STDERR "\nDifferences $difflo -- $diffhi => threshold = $::TAB_THRESHOLD\n" | ||
| 775 | if $LaTeXML::Core::Alignment::DEBUG; | ||
| 776 | # Find the first hump in differences. These are candidates for header lines. | ||
| 777 | print STDERR "Scanning for headers\n " if $LaTeXML::Core::Alignment::DEBUG; | ||
| 778 | my $diff; | ||
| 779 | my ($minh, $maxh) = (1, 1); | ||
| 780 | while (($diff = alignment_compare($axis, 1, $reversed, $maxh - 1, $maxh)) < $::TAB_THRESHOLD) { | ||
| 781 | $maxh++; } | ||
| 782 | return if $maxh > $MAX_ALIGNMENT_HEADER_LINES; # too many before even finding diffs? give up! | ||
| 783 | # while( alignment_compare($axis,1,$reversed,$maxh,$maxh+1) > $difflo + ($diff-$difflo)/6){ | ||
| 784 | while (alignment_compare($axis, 1, $reversed, $maxh, $maxh + 1) > $::TAB_THRESHOLD) { | ||
| 785 | $maxh++; } | ||
| 786 | $maxh = $MAX_ALIGNMENT_HEADER_LINES if $maxh > $MAX_ALIGNMENT_HEADER_LINES; | ||
| 787 | print STDERR "\nFound from $minh--$maxh potential headers\n" if $LaTeXML::Core::Alignment::DEBUG; | ||
| 788 | |||
| 789 | my $nn = scalar(@{ $lines[0] }) - 1; | ||
| 790 | # The sets of lines 1--$minh, .. 1--$maxh are potential headers. | ||
| 791 | for (my $nh = $maxh ; $nh >= $minh ; $nh--) { | ||
| 792 | # for(my $nh = $minh; $nh <= $maxh; $nh++){ | ||
| 793 | # Check whether the set 1..$nh is plausable. | ||
| 794 | if (my @heads = alignment_test_headers($nh)) { | ||
| 795 | # Now, change all cells marked as header from td => th. | ||
| 796 | foreach my $h (@heads) { | ||
| 797 | my $i = 0; | ||
| 798 | foreach my $cell (@{ $lines[$h] }) { | ||
| 799 | $$cell{cell_type} = 'h'; | ||
| 800 | if (my $xcell = $$cell{cell}) { | ||
| 801 | if (($$cell{content_class} eq '_') # But NOT empty cells on outer edges. | ||
| 802 | && ((($i == 0) && !$$cell{ ($axis == 0 ? 'l' : 't') }) | ||
| 803 | || (($i == $nn) && !$$cell{ ($axis == 0 ? 'r' : 'b') }))) { } | ||
| 804 | else { | ||
| 805 | $document->addSSValues($$cell{cell}, thead => $axisname[$axis]); } } | ||
| 806 | $i++; } } | ||
| 807 | return 1; } } | ||
| 808 | return; } | ||
| 809 | |||
| 810 | # Test whether $nhead lines makes a good fit for the headers | ||
| 811 | sub alignment_test_headers { | ||
| 812 | my ($nhead) = @_; | ||
| 813 | print STDERR "Testing $nhead headers\n" if $LaTeXML::Core::Alignment::DEBUG; | ||
| 814 | my ($headlength, $datalength) = (0, 0); | ||
| 815 | my @heads = (0 .. $nhead - 1); # The indices of heading lines. | ||
| 816 | $headlength = alignment_max_content_length($headlength, 0, $nhead - 1); | ||
| 817 | my $nextline = $nhead; # Start from the end of the proposed headings. | ||
| 818 | |||
| 819 | # Watch out for the assumed header being really data that is a repeated pattern. | ||
| 820 | my $nrep = scalar(@::TABLINES) / $nhead; | ||
| 821 | if (($nhead > 1) && ($nrep == int($nrep))) { | ||
| 822 | print STDERR "Check for apparent header repeated $nrep times\n" if $LaTeXML::Core::Alignment::DEBUG; | ||
| 823 | my $matched = 1; | ||
| 824 | for (my $r = 1 ; $r < $nrep ; $r++) { | ||
| 825 | $matched &&= alignment_match_head(0, $r * $nhead, $nhead); } | ||
| 826 | print STDERR "Repeated headers: " . ($matched ? "Matched=> Fail" : "Nomatch => Succeed") . "\n" if $LaTeXML::Core::Alignment::DEBUG; | ||
| 827 | return if $matched; } | ||
| 828 | |||
| 829 | # And find a following grouping of data lines. | ||
| 830 | my $ndata = alignment_skip_data($nextline); | ||
| 831 | return if $ndata < $nhead; # ???? Well, maybe if _really_ convincing??? | ||
| 832 | return if ($ndata < $nhead) && ($ndata < 2); | ||
| 833 | # Check that the content of the headers isn't dramatically larger than the content in the data | ||
| 834 | $datalength = alignment_max_content_length($datalength, $nextline, $nextline + $ndata - 1); | ||
| 835 | $nextline += $ndata; | ||
| 836 | |||
| 837 | my $nd; | ||
| 838 | # If there are more lines, they should match either the previous data block, or the head/data pattern. | ||
| 839 | while ($nextline < scalar(@::TABLINES)) { | ||
| 840 | # First try to match a repeat of the 1st data block; | ||
| 841 | # This would be the case when groups of data have borders around them. | ||
| 842 | # Could want to match a variable number of datalines, but they should be similar!!!??!?!? | ||
| 843 | if (($ndata > 1) && ($nd = alignment_match_data($nhead, $nextline, $ndata))) { | ||
| 844 | $datalength = alignment_max_content_length($datalength, $nextline, $nextline + $nd - 1); | ||
| 845 | $nextline += $nd; } | ||
| 846 | # Else, try to match the first header block; less common. | ||
| 847 | elsif (alignment_match_head(0, $nextline, $nhead)) { | ||
| 848 | push(@heads, $nextline .. $nextline + $nhead - 1); | ||
| 849 | $headlength = alignment_max_content_length($headlength, $nextline, $nextline + $nhead - 1); | ||
| 850 | $nextline += $nhead; | ||
| 851 | # Then attempt to match a new data block. | ||
| 852 | # my $d = alignment_skip_data($nextline); | ||
| 853 | # return unless ($d >= $nhead) || ($d >= 2); | ||
| 854 | # $nextline += $d; } | ||
| 855 | # No, better be the same data block? | ||
| 856 | return unless ($nd = alignment_match_data($nhead, $nextline, $ndata)); | ||
| 857 | $datalength = alignment_max_content_length($datalength, $nextline, $nextline + $nd - 1); | ||
| 858 | $nextline += $nd; } | ||
| 859 | else { return; } } | ||
| 860 | # Header content seems too large relative to data? | ||
| 861 | print STDERR "header content = $headlength; data content = $datalength\n" | ||
| 862 | if $LaTeXML::Core::Alignment::DEBUG; | ||
| 863 | ## if(($headlength > 10) && (0.3*$headlength > $datalength)){ | ||
| 864 | if (($headlength > 10) && (0.25 * $headlength > $datalength)) { | ||
| 865 | print STDERR "header content too much longer than data content\n" | ||
| 866 | if $LaTeXML::Core::Alignment::DEBUG; | ||
| 867 | return; } | ||
| 868 | # Or if a header cell has "large" content? | ||
| 869 | if ($headlength >= 1000) { # Or if a header cell has "large" content? | ||
| 870 | print STDERR "header content too large\n" | ||
| 871 | if $LaTeXML::Core::Alignment::DEBUG; | ||
| 872 | return; } | ||
| 873 | |||
| 874 | print STDERR "Succeeded with $nhead headers\n" if $LaTeXML::Core::Alignment::DEBUG; | ||
| 875 | return @heads; } | ||
| 876 | |||
| 877 | sub alignment_match_head { | ||
| 878 | my ($p1, $p2, $nhead) = @_; | ||
| 879 | print STDERR "Try match $nhead header lines from $p1 to $p2\n " if $LaTeXML::Core::Alignment::DEBUG; | ||
| 880 | my $nh = alignment_match_lines($p1, $p2, $nhead); | ||
| 881 | my $ok = $nhead == $nh; | ||
| 882 | print STDERR "\nMatched $nh header lines => " . ($ok ? "Succeed" : "Failed") . "\n" if $LaTeXML::Core::Alignment::DEBUG; | ||
| 883 | return ($ok ? $nhead : 0); } | ||
| 884 | |||
| 885 | sub alignment_match_data { | ||
| 886 | my ($p1, $p2, $ndata) = @_; | ||
| 887 | print STDERR "Try match $ndata data lines from $p1 to $p2\n " | ||
| 888 | if $LaTeXML::Core::Alignment::DEBUG; | ||
| 889 | my $nd = alignment_match_lines($p1, $p2, $ndata); | ||
| 890 | my $ok = ($nd * 1.0) / $ndata > 0.66; | ||
| 891 | print STDERR "\nMatched $nd data lines => " . ($ok ? "Succeed" : "Failed") . "\n" | ||
| 892 | if $LaTeXML::Core::Alignment::DEBUG; | ||
| 893 | return ($ok ? $nd : 0); } | ||
| 894 | |||
| 895 | # Match the $n lines starting at $i2 to those starting at $i1. | ||
| 896 | sub alignment_match_lines { | ||
| 897 | my ($p1, $p2, $n) = @_; | ||
| 898 | for (my $i = 0 ; $i < $n ; $i++) { | ||
| 899 | return $i if ($p1 + $i >= scalar(@::TABLINES)) || ($p2 + $i >= scalar(@::TABLINES)) | ||
| 900 | || alignment_compare($::TAB_AXIS, 0, 0, $p1 + $i, $p2 + $i) >= $::TAB_THRESHOLD; } | ||
| 901 | return $n; } | ||
| 902 | |||
| 903 | # Skip through a block of lines starting at $i that appear to be data, returning the number of lines. | ||
| 904 | # We'll assume the 1st line is data, compare it to following lines, | ||
| 905 | # but also accept `continuation' data lines. | ||
| 906 | sub alignment_skip_data { | ||
| 907 | my ($i) = @_; | ||
| 908 | return 0 if $i >= scalar(@::TABLINES); | ||
| 909 | print STDERR "Scanning for data\n " if $LaTeXML::Core::Alignment::DEBUG; | ||
| 910 | my $n = 1; | ||
| 911 | while ($i + $n < scalar(@::TABLINES)) { | ||
| 912 | last if (alignment_compare($::TAB_AXIS, 1, 0, $i + $n - 1, $i + $n) >= $::TAB_THRESHOLD) | ||
| 913 | # Accept an outlying `continuation line' as data, if mostly empty | ||
| 914 | && (($n < 2) | ||
| 915 | || (scalar(grep { $$_{content_class} eq '_' } @{ $::TABLINES[$i + $n] }) <= 0.4 * scalar($::TABLINES[0]))); | ||
| 916 | $n++; } | ||
| 917 | print STDERR "\nFound $n data lines at $i\n" if $LaTeXML::Core::Alignment::DEBUG; | ||
| 918 | return ($n >= $MIN_ALIGNMENT_DATA_LINES ? $n : 0); } | ||
| 919 | |||
| 920 | sub XXXalignment_max_content_length { | ||
| 921 | my ($length, $from, $to) = @_; | ||
| 922 | foreach my $j (($from .. $to)) { | ||
| 923 | foreach my $cell (@{ $::TABLINES[$j] }) { | ||
| 924 | $length = $$cell{content_length} | ||
| 925 | if $$cell{content_length} && ($$cell{content_length} > $length); } } | ||
| 926 | return $length; } | ||
| 927 | |||
| 928 | # Return the maximum "content length" for lines from $from to $to. | ||
| 929 | sub alignment_max_content_length { | ||
| 930 | my ($length, $from, $to) = @_; | ||
| 931 | foreach my $j (($from .. $to)) { | ||
| 932 | my $l = 0; | ||
| 933 | foreach my $cell (@{ $::TABLINES[$j] }) { | ||
| 934 | $l += $$cell{content_length} || 0; } | ||
| 935 | $length = $l if $l > $length; } | ||
| 936 | return $length; } | ||
| 937 | |||
| 938 | #====================================================================== | ||
| 939 | # The comparator. | ||
| 940 | # our %cell_class_diff = | ||
| 941 | # ('_'=>{'_'=>0.0, m=>0.1, i=>0.1, t=>0.1, '?'=>0.1, mx=>0.1}, | ||
| 942 | # m =>{'_'=>0.1, m=>0.0, i=>0.1, mx=>0.2}, | ||
| 943 | # i =>{'_'=>0.1, m=>0.1, i=>0.0, mx=>0.2}, | ||
| 944 | # t =>{'_'=>0.1, t=>0.0, mx=>0.2}, | ||
| 945 | # '?'=>{'_'=>0.1, '?'=>0.0, mx=>0.2}, | ||
| 946 | # mx=>{'_'=>0.1, m=>0.2, i=>0.2, t=>0.2, '?'=>0.2, mx=>0.0}); | ||
| 947 | |||
| 948 | my %cell_class_diff = ( # [CONSTANT] | ||
| 949 | '_' => { '_' => 0.0, m => 0.05, i => 0.05, t => 0.05, '?' => 0.05, mx => 0.05 }, | ||
| 950 | m => { '_' => 0.05, m => 0.0, i => 0.1, mx => 0.2 }, | ||
| 951 | i => { '_' => 0.05, m => 0.1, i => 0.0, mx => 0.2 }, | ||
| 952 | t => { '_' => 0.05, t => 0.0, mx => 0.2 }, | ||
| 953 | '?' => { '_' => 0.05, '?' => 0.0, mx => 0.2 }, | ||
| 954 | mx => { '_' => 0.05, m => 0.2, i => 0.2, t => 0.2, '?' => 0.2, mx => 0.0 }); | ||
| 955 | |||
| 956 | # Compare two lines along $axis (0=row,1=column), returning a measure of the difference. | ||
| 957 | # The borders are compared differently if | ||
| 958 | # $foradjacency: we adjacent lines that might belong to the same block, | ||
| 959 | # otherwise : comparing two lines that ought to have identical patterns (eg. in a repeated block) | ||
| 960 | sub alignment_compare { | ||
| 961 | my ($axis, $foradjacency, $reversed, $p1, $p2) = @_; | ||
| 962 | my $line1 = $::TABLINES[$p1]; | ||
| 963 | my $line2 = $::TABLINES[$p2]; | ||
| 964 | return 0 if !($line1 && $line2); | ||
| 965 | return 999999 if $line1 xor $line2; | ||
| 966 | my @cells1 = @$line1; | ||
| 967 | my @cells2 = @$line2; | ||
| 968 | my $ncells = scalar(@cells1); | ||
| 969 | my $diff = 0.0; | ||
| 970 | |||
| 971 | while (@cells1 && @cells2) { | ||
| 972 | my $cell1 = shift(@cells1); | ||
| 973 | my $cell2 = shift(@cells2); | ||
| 974 | # Annoying test avoids warnings if cells inconsistent; likely due to incorrect row/col spans | ||
| 975 | next if grep { !defined $$cell1{$_} } qw(content_class r l t b); | ||
| 976 | next if grep { !defined $$cell2{$_} } qw(content_class r l t b); | ||
| 977 | # $diff += 0.5 if (($$cell1{align}||'') ne ($$cell2{align}||'')) | ||
| 978 | $diff += 0.75 if (($$cell1{align} || '') ne ($$cell2{align} || '')) | ||
| 979 | && ($$cell1{content_class} ne '_') && ($$cell2{content_class} ne '_'); | ||
| 980 | if (my $d = $cell_class_diff{ $$cell1{content_class} }{ $$cell2{content_class} }) { | ||
| 981 | $diff += $d; } | ||
| 982 | elsif ($$cell1{content_class} ne $$cell2{content_class}) { | ||
| 983 | $diff += 0.75; } | ||
| 984 | # compare certain edges | ||
| 985 | if ($foradjacency) { # Compare edges for adjacent rows of potentially different purpose | ||
| 986 | $diff += 0.3 * scalar(grep { $$cell1{$_} != $$cell2{$_} } ($axis == 0 ? qw(r l) : qw(t b))); | ||
| 987 | # Penalty for apparent divider between. | ||
| 988 | my $pedge = ($axis == 0 ? ($reversed ? 't' : 'b') : ($reversed ? 'l' : 'r')); | ||
| 989 | if ($$cell1{$pedge} && ($$cell1{$pedge} != $$cell2{$pedge})) { | ||
| 990 | $diff += abs($$cell1{$pedge} - $$cell2{$pedge}) * 1.0; } | ||
| 991 | } | ||
| 992 | else { # Compare edges for rows from diff places for potential similarity | ||
| 993 | $diff += 0.3 * scalar(grep { $$cell1{$_} != $$cell2{$_} } qw(r l t b)); } | ||
| 994 | } | ||
| 995 | $diff /= $ncells; | ||
| 996 | print STDERR "$p1-$p2 => $diff; " if $LaTeXML::Core::Alignment::DEBUG; | ||
| 997 | return $diff; } | ||
| 998 | |||
| 999 | #====================================================================== | ||
| 1000 | # Debugging. | ||
| 1001 | sub summarize_alignment { | ||
| 1002 | my ($rows, $cols) = @_; | ||
| 1003 | my $r = 0; | ||
| 1004 | my ($nrows, $ncols) = (scalar(@$rows), scalar(@{ $$rows[0] })); | ||
| 1005 | print STDERR "\n"; | ||
| 1006 | foreach my $cell (@{ $$rows[0] }) { | ||
| 1007 | print STDERR ' ' . ($$cell{t} ? ('-' x 6) : (' ' x 6)); } | ||
| 1008 | print STDERR "\n"; | ||
| 1009 | foreach my $row (@$rows) { | ||
| 1010 | my $maxb = 0; | ||
| 1011 | print STDERR ($$row[0]{l} ? ('|' x $$row[0]{l}) : ' '); | ||
| 1012 | foreach my $cell (@$row) { | ||
| 1013 | print STDERR sprintf(" %4s ", | ||
| 1014 | ($$cell{cell_type} || '?') | ||
| 1015 | . ($$cell{align} ? $ALIGNMENT_CODE{ $$cell{align} } : ' ') | ||
| 1016 | . ($$cell{content_class} || '?') | ||
| 1017 | . ($$cell{r} ? ('|' x $$cell{r}) : ' ')); | ||
| 1018 | $maxb = $$cell{b} if $$cell{b} > $maxb; } | ||
| 1019 | # print STDERR sprintf("%.3f",alignment_compare(0,1,$$rows[$r],$$rows[$r+1])) if ($r < $nrows-1); | ||
| 1020 | print STDERR "\n"; | ||
| 1021 | for (my $b = 0 ; $b < $maxb ; $b++) { | ||
| 1022 | foreach my $cell (@$row) { | ||
| 1023 | print STDERR ' ' . ($b < $$cell{b} ? ('-' x 6) : (' ' x 6)); } | ||
| 1024 | print STDERR "\n"; } | ||
| 1025 | $r++; } | ||
| 1026 | print STDERR " "; | ||
| 1027 | # for(my $c = 0; $c < $ncols-1; $c++){ | ||
| 1028 | # print STDERR sprintf(" %.3f ",alignment_compare(1,1,$$cols[$c],$$cols[$c+1])); } | ||
| 1029 | print STDERR "\n"; | ||
| 1030 | return; } | ||
| 1031 | |||
| 1032 | #====================================================================== | ||
| 1033 | 1; | ||
| 1034 | |||
| 1035 | __END__ |