Fix remaining single quotes in main.idp
[scpubgit/stemmatology.git] / base / lib / Text / Tradition / Parser / CTE.pm
CommitLineData
6f4946fb 1package Text::Tradition::Parser::CTE;
2
3use strict;
4use warnings;
a188b944 5use feature 'say';
c9158e60 6use Encode qw/ decode /;
00311328 7use Text::Tradition::Error;
4d85a60e 8use Text::Tradition::Parser::Util qw/ collate_variants /;
6f4946fb 9use XML::LibXML;
10use XML::LibXML::XPathContext;
f60f9e0f 11use TryCatch;
6f4946fb 12
13=head1 NAME
14
15Text::Tradition::Parser::CTE
16
17=head1 DESCRIPTION
18
19Parser module for Text::Tradition, given a TEI file exported from
20Classical Text Editor.
21
22=head1 METHODS
23
a445ce40 24=head2 parse
6f4946fb 25
26my @apparatus = read( $xml_file );
27
28Takes a Tradition object and a TEI file exported from Classical Text
4d85a60e 29Editor using double-endpoint-attachment critical apparatus encoding;
30initializes the Tradition from the file.
6f4946fb 31
32=cut
33
4d85a60e 34my %sigil_for; # Save the XML IDs for witnesses.
35my %apps; # Save the apparatus XML for a given ID.
f6e19c7c 36my %has_ac; # Keep track of witnesses that have corrections.
6f4946fb 37
38sub parse {
dfc37e38 39 my( $tradition, $opts ) = @_;
4d85a60e 40 my $c = $tradition->collation; # Some shorthand
41
e9442e1c 42 ## DEBUG/TEST
43 $opts->{interpret_transposition} = 1;
44
4d85a60e 45 # First, parse the XML.
c9158e60 46 my( $tei, $xpc ) = _remove_formatting( $opts );
47 return unless $tei; # we have already warned.
4d85a60e 48
49 # CTE uses a DTD rather than any xmlns-based parsing. Thus we
50 # need no namespace handling.
4d85a60e 51 # Get the witnesses and create the witness objects.
52 foreach my $wit_el ( $xpc->findnodes( '//sourceDesc/listWit/witness' ) ) {
53 # The witness xml:id is used internally, and is *not* the sigil name.
54 my $id= $wit_el->getAttribute( 'xml:id' );
92de40a6 55 # If the witness element has an abbr element, that is the sigil. Otherwise
56 # the whole thing is the sigil.
57 my $sig = $xpc->findvalue( 'abbr', $wit_el );
58 my $identifier = 'CTE witness';
59 if( $sig ) {
60 # The sigil is what is in the <abbr/> tag; the identifier is anything
61 # that follows.
62 $identifier = _tidy_identifier(
63 $xpc->findvalue( 'child::text()', $wit_el ) );
64 } else {
65 my @sig_parts = $xpc->findnodes( 'descendant::text()', $wit_el );
66 $sig = _stringify_sigil( @sig_parts );
67 }
68 say STDERR "Adding witness $sig ($identifier)";
69 $tradition->add_witness( sigil => $sig, identifier => $identifier,
70 sourcetype => 'collation' );
b8f262e8 71 $sigil_for{'#'.$id} = $sig; # Make life easy by keying on the ID ref syntax
4d85a60e 72 }
c9158e60 73
4d85a60e 74 # Now go through the text and find the base tokens, apparatus tags, and
75 # anchors. Make a giant array of all of these things in sequence.
76 # TODO consider combining this with creation of graph below
77 my @base_text;
78 foreach my $pg_el ( $xpc->findnodes( '/TEI/text/body/p' ) ) {
79 foreach my $xn ( $pg_el->childNodes ) {
82a45078 80 push( @base_text, _get_base( $xn ) );
4d85a60e 81 }
6f4946fb 82 }
4d85a60e 83 # We now have to work through this array applying the alternate
84 # apparatus readings to the base text. Essentially we will put
85 # everything on the graph, from which we will delete the apps and
86 # anchors when we are done.
f6e19c7c 87
9e0a9786 88 # First, put the base tokens, apps, and anchors in the graph. Save the
89 # app siglorum separately as it has to be processed in order.
90 my @app_sig;
4d85a60e 91 my $counter = 0;
92 my $last = $c->start;
93 foreach my $item ( @base_text ) {
94 my $r;
95 if( $item->{'type'} eq 'token' ) {
12720144 96 $r = $c->add_reading( { id => 'n'.$counter++,
97 text => $item->{'content'} } );
4d85a60e 98 } elsif ( $item->{'type'} eq 'anchor' ) {
10e4b1ac 99 $r = $c->add_reading( { id => '__ANCHOR_' . $item->{'content'} . '__',
12720144 100 is_ph => 1 } );
4d85a60e 101 } elsif ( $item->{'type'} eq 'app' ) {
10e4b1ac 102 my $tag = '__APP_' . $counter++ . '__';
12720144 103 $r = $c->add_reading( { id => $tag, is_ph => 1 } );
f60f9e0f 104 my $app = $item->{'content'};
105 # Apparatus should be differentiable by type attribute; apparently
106 # it is not. Peek at the content to categorize it.
9e0a9786 107 # Apparatus criticus is type a1; app siglorum is type a2
f60f9e0f 108 my @sigtags = $xpc->findnodes( 'descendant::*[name(witStart) or name(witEnd)]', $app );
109 if( @sigtags ) {
110 push( @app_sig, $app );
9e0a9786 111 } else {
f60f9e0f 112 $apps{$tag} = $app;
9e0a9786 113 }
4d85a60e 114 }
f6e19c7c 115 $c->add_path( $last, $r, $c->baselabel );
4d85a60e 116 $last = $r;
6f4946fb 117 }
f6e19c7c 118 $c->add_path( $last, $c->end, $c->baselabel );
4d85a60e 119
120 # Now we can parse the apparatus entries, and add the variant readings
121 # to the graph.
4d85a60e 122 foreach my $app_id ( keys %apps ) {
e9442e1c 123 _add_readings( $c, $app_id, $opts );
6f4946fb 124 }
9e0a9786 125 _add_lacunae( $c, @app_sig );
4d85a60e 126
f6e19c7c 127 # Finally, add explicit witness paths, remove the base paths, and remove
128 # the app/anchor tags.
dead25ca 129 try {
130 _expand_all_paths( $c );
f60f9e0f 131 } catch( Text::Tradition::Error $e ) {
132 throw( $e->message );
133 } catch {
134 throw( $@ );
dead25ca 135 }
861c3e27 136
137 # Save the text for each witness so that we can ensure consistency
138 # later on
a188b944 139 unless( $opts->{'nocalc'} ) {
dead25ca 140 try {
141 $tradition->collation->text_from_paths();
142 $tradition->collation->calculate_ranks();
143 $tradition->collation->flatten_ranks();
f60f9e0f 144 } catch( Text::Tradition::Error $e ) {
145 throw( $e->message );
146 } catch {
147 throw( $@ );
dead25ca 148 }
a188b944 149 }
6f4946fb 150}
151
4d85a60e 152sub _stringify_sigil {
153 my( @nodes ) = @_;
154 my @parts = grep { /\w/ } map { $_->data } @nodes;
222d58f1 155 my $whole = join( '', @parts );
156 $whole =~ s/\W//g;
157 return $whole;
4d85a60e 158}
6f4946fb 159
92de40a6 160sub _tidy_identifier {
161 my( $str ) = @_;
162 $str =~ s/^\W+//;
163 return $str;
164}
165
c9158e60 166# Get rid of all the formatting elements that get in the way of tokenization.
167sub _remove_formatting {
168 my( $opts ) = @_;
169
170 # First, parse the original XML
171 my $parser = XML::LibXML->new();
172 my $doc;
173 if( exists $opts->{'string'} ) {
174 $doc = $parser->parse_string( $opts->{'string'} );
175 } elsif ( exists $opts->{'file'} ) {
176 $doc = $parser->parse_file( $opts->{'file'} );
dead25ca 177 } elsif ( exists $opts->{'xmlobj'} ) {
178 $doc = $opts->{'xmlobj'};
c9158e60 179 } else {
180 warn "Could not find string or file option to parse";
181 return;
182 }
00311328 183
c9158e60 184 # Second, remove the formatting
185 my $xpc = XML::LibXML::XPathContext->new( $doc->documentElement );
186 my @useless = $xpc->findnodes( '//hi' );
187 foreach my $n ( @useless ) {
188 my $parent = $n->parentNode();
189 my @children = $n->childNodes();
190 my $first = shift @children;
7c2ed85e 191 if( $first ) {
192 $parent->replaceChild( $first, $n );
193 foreach my $c ( @children ) {
194 $parent->insertAfter( $c, $first );
195 $first = $c;
196 }
197 } else {
198 $parent->removeChild( $n );
c9158e60 199 }
200 }
201
202 # Third, write out and reparse to merge the text nodes.
00311328 203 my $enc = $doc->encoding || 'UTF-8';
204 my $result = decode( $enc, $doc->toString() );
c9158e60 205 my $tei = $parser->parse_string( $result )->documentElement;
00311328 206 unless( $tei->nodeName =~ /^tei(corpus)?$/i ) {
207 throw( "Parsed document has non-TEI root element " . $tei->nodeName );
208 }
c9158e60 209 $xpc = XML::LibXML::XPathContext->new( $tei );
210 return( $tei, $xpc );
211}
212
213## Helper function to help us navigate through nested XML, picking out
214## the words, the apparatus, and the anchors.
4d85a60e 215
216sub _get_base {
217 my( $xn ) = @_;
218 my @readings;
219 if( $xn->nodeType == XML_TEXT_NODE ) {
220 # Base text, just split the words on whitespace and add them
221 # to our sequence.
222 my $str = $xn->data;
223 $str =~ s/^\s+//;
c9158e60 224 my @tokens = split( /\s+/, $str );
92de40a6 225 push( @readings, map { { type => 'token', content => $_ } } @tokens );
4d85a60e 226 } elsif( $xn->nodeName eq 'app' ) {
227 # Apparatus, just save the entire XML node.
92de40a6 228 push( @readings, { type => 'app', content => $xn } );
4d85a60e 229 } elsif( $xn->nodeName eq 'anchor' ) {
230 # Anchor to mark the end of some apparatus; save its ID.
82a45078 231 if( $xn->hasAttribute('xml:id') ) {
92de40a6 232 push( @readings, { type => 'anchor',
233 content => $xn->getAttribute( 'xml:id' ) } );
82a45078 234 } # if the anchor has no XML ID, it is not relevant to us.
92de40a6 235 } elsif( $xn->nodeName !~ /^(note|seg|milestone|emph)$/ ) { # Any tag we don't know to disregard
a188b944 236 say STDERR "Unrecognized tag " . $xn->nodeName;
6f4946fb 237 }
4d85a60e 238 return @readings;
6f4946fb 239}
240
c9158e60 241sub _append_tokens {
242 my( $list, @tokens ) = @_;
243 if( @$list && $list->[-1]->{'content'} =~ /\#JOIN\#$/ ) {
244 # The list evidently ended mid-word; join the next token onto it.
245 my $t = shift @tokens;
246 if( ref $t && $t->{'type'} eq 'token' ) {
247 # Join the word
248 $t = $t->{'content'};
249 } elsif( ref $t ) {
250 # An app or anchor intervened; end the word.
251 unshift( @tokens, $t );
252 $t = '';
253 }
254 $list->[-1]->{'content'} =~ s/\#JOIN\#$/$t/;
255 }
256 foreach my $t ( @tokens ) {
257 unless( ref( $t ) ) {
258 $t = { 'type' => 'token', 'content' => $t };
259 }
260 push( @$list, $t );
261 }
262}
263
4d85a60e 264sub _add_readings {
e9442e1c 265 my( $c, $app_id, $opts ) = @_;
4d85a60e 266 my $xn = $apps{$app_id};
9e0a9786 267 my $anchor = _anchor_name( $xn->getAttribute( 'to' ) );
92de40a6 268
4d85a60e 269 # Get the lemma, which is all the readings between app and anchor,
270 # excluding other apps or anchors.
9e0a9786 271 my @lemma = _return_lemma( $c, $app_id, $anchor );
272 my $lemma_str = join( ' ', map { $_->text } grep { !$_->is_ph } @lemma );
92de40a6 273
4d85a60e 274 # For each reading, send its text to 'interpret' along with the lemma,
275 # and then save the list of witnesses that these tokens belong to.
3a5d151b 276 my %wit_rdgs; # Maps from witnesses to the variant text
4d85a60e 277 my $ctr = 0;
278 my $tag = $app_id;
10e4b1ac 279 $tag =~ s/^\__APP_(.*)\__$/$1/;
c9158e60 280
4d85a60e 281 foreach my $rdg ( $xn->getChildrenByTagName( 'rdg' ) ) {
e9442e1c 282 my @witlist = split( /\s+/, $rdg->getAttribute( 'wit' ) );
4d85a60e 283 my @text;
4d85a60e 284 foreach ( $rdg->childNodes ) {
285 push( @text, _get_base( $_ ) );
286 }
12720144 287 my( $interpreted, $flag ) = ( '', undef );
288 if( @text ) {
289 ( $interpreted, $flag ) = interpret(
e9442e1c 290 join( ' ', map { $_->{'content'} } @text ), $lemma_str, $anchor, $opts );
12720144 291 }
e9442e1c 292 next if( $interpreted eq $lemma_str ) && !keys %$flag; # Reading is lemma.
b8f262e8 293
4d85a60e 294 my @rdg_nodes;
b8f262e8 295 if( $interpreted eq '#LACUNA#' ) {
10e4b1ac 296 push( @rdg_nodes, $c->add_reading( { id => 'r'.$tag.".".$ctr++,
b8f262e8 297 is_lacuna => 1 } ) );
e9442e1c 298 } elsif( $flag->{'TR'} ) {
299 # Our reading is transposed to after the given string. Look
300 # down the collation base text and try to find it.
301 # The @rdg_nodes should remain blank here, so that the correct
302 # omission goes into the graph.
f9ffe014 303 my @transp_nodes;
e9442e1c 304 foreach my $w ( split( /\s+/, $interpreted ) ) {
305 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
306 text => $w } );
307 push( @transp_nodes, $r );
308 }
309 if( $anchor && @lemma ) {
f9ffe014 310 my $success = _attach_transposition( $c, \@lemma, $anchor,
311 \@transp_nodes, \@witlist, $flag->{'TR'} );
312 unless( $success ) {
313 # If we didn't manage to insert the displaced reading,
314 # then restore it here rather than silently deleting it.
315 push( @rdg_nodes, @transp_nodes );
316 }
e9442e1c 317 }
b8f262e8 318 } else {
319 foreach my $w ( split( /\s+/, $interpreted ) ) {
10e4b1ac 320 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
b8f262e8 321 text => $w } );
322 push( @rdg_nodes, $r );
323 }
4d85a60e 324 }
92de40a6 325
f6e19c7c 326 # For each listed wit, save the reading.
a5978ac8 327 # If an A.C. or P.C. reading is implied rather than explicitly noted,
328 # this is where it will be dealt with.
e9442e1c 329 foreach my $wit ( @witlist ) {
330 $wit .= '_ac' if $flag->{'AC'};
f6e19c7c 331 $wit_rdgs{$wit} = \@rdg_nodes;
a5978ac8 332 # If the PC flag is set, there is a corresponding AC that
333 # follows the lemma and has to be explicitly declared.
334 if( $flag->{'PC'} ) {
335 $wit_rdgs{$wit.'_ac'} = \@lemma;
336 }
f6e19c7c 337 }
12720144 338
3a5d151b 339 # Does the reading have an ID? If so it probably has a witDetail
a5978ac8 340 # attached, and we need to read it. If an A.C. or P.C. reading is
341 # declared explicity, this is where it will be dealt with.
3a5d151b 342 if( $rdg->hasAttribute( 'xml:id' ) ) {
12720144 343 warn "Witdetail on meta reading" if $flag; # this could get complicated.
f6e19c7c 344 my $rid = $rdg->getAttribute( 'xml:id' );
345 my $xpc = XML::LibXML::XPathContext->new( $xn );
346 my @details = $xpc->findnodes( './witDetail[@target="'.$rid.'"]' );
347 foreach my $d ( @details ) {
348 _parse_wit_detail( $d, \%wit_rdgs, \@lemma );
349 }
3a5d151b 350 }
f6e19c7c 351 }
352
4d85a60e 353 # Now collate the variant readings, since it is not done for us.
12720144 354 collate_variants( $c, \@lemma, values %wit_rdgs );
b8f262e8 355
92de40a6 356 # Now add the witness paths for each reading. If we don't have an anchor
357 # (e.g. with an initial witStart) there was no witness path to speak of.
9e0a9786 358 foreach my $wit_id ( keys %wit_rdgs ) {
359 my $witstr = _get_sigil( $wit_id, $c->ac_label );
360 my $rdg_list = $wit_rdgs{$wit_id};
361 _add_wit_path( $c, $rdg_list, $app_id, $anchor, $witstr );
92de40a6 362 }
4d85a60e 363}
6f4946fb 364
4d85a60e 365sub _anchor_name {
366 my $xmlid = shift;
367 $xmlid =~ s/^\#//;
10e4b1ac 368 return sprintf( "__ANCHOR_%s__", $xmlid );
6f4946fb 369}
370
4d85a60e 371sub _return_lemma {
372 my( $c, $app, $anchor ) = @_;
10e4b1ac 373 my @nodes = grep { $_->id !~ /^__A(PP|NCHOR)/ }
12720144 374 $c->reading_sequence( $c->reading( $app ), $c->reading( $anchor ),
375 $c->baselabel );
4d85a60e 376 return @nodes;
377}
6f4946fb 378
e9442e1c 379# Make a best-effort attempt to attach a transposition farther down the line.
380# $lemmaseq contains the Reading objects of the lemma
381# $anchor contains the point at which we should start scanning for a match
382# $rdgseq contains the Reading objects of the transposed reading
383# (should be identical to the lemma)
384# $witlist contains the list of applicable witnesses
385# $reftxt contains the text to match, after which the $rdgseq should go.
386sub _attach_transposition {
387 my( $c, $lemmaseq, $anchor, $rdgseq, $witlist, $reftxt ) = @_;
388 my @refwords = split( /\s+/, $reftxt );
389 my $checked = $c->reading( $anchor );
390 my $found;
f9ffe014 391 my $success;
e9442e1c 392 while( $checked ne $c->end && !$found ) {
393 my $next = $c->next_reading( $checked, $c->baselabel );
394 if( $next->text eq $refwords[0] ) {
395 # See if the entire sequence of words matches.
396 $found = $next;
397 foreach my $w ( 1..$#refwords ) {
398 $found = $c->next_reading( $next, $c->baselabel );
399 unless( $found->text eq $refwords[$w] ) {
400 $found = undef;
401 last;
402 }
403 }
404 }
405 $checked = $next;
406 }
407 if( $found ) {
408 # The $found variable should now contain the reading after which we
409 # should stick the transposition.
410 my $fnext = $c->next_reading( $found, $c->baselabel );
411 my $aclabel = $c->ac_label;
412 foreach my $wit_id ( @$witlist ) {
413 my $witstr = _get_sigil( $wit_id, $aclabel );
414 _add_wit_path( $c, $rdgseq, $found->id, $fnext->id, $witstr );
415 }
416 # ...and add the transposition relationship between lemma and rdgseq.
417 if( @$lemmaseq == @$rdgseq ) {
418 foreach my $i ( 0..$#{$lemmaseq} ) {
419 $c->add_relationship( $lemmaseq->[$i], $rdgseq->[$i],
420 { type => 'transposition', annotation => 'Detected by CTE' } );
421 }
f9ffe014 422 $success = 1;
e9442e1c 423 } else {
dead25ca 424 throw( "Lemma at $found and transposed sequence different lengths?!" );
e9442e1c 425 }
426 } else {
427 say STDERR "WARNING: Unable to find $reftxt in base text for transposition";
e9442e1c 428 }
f9ffe014 429 return $success;
e9442e1c 430}
431
a445ce40 432=head2 interpret( $reading, $lemma )
433
434Given a string in $reading and a corresponding lemma in $lemma, interpret what
435the actual reading should be. Used to deal with apparatus-ese shorthands for
436marking transpositions, prefixed or suffixed words, and the like.
437
438=cut
439
6f4946fb 440sub interpret {
4d85a60e 441 # A utility function to change apparatus-ese into a full variant.
e9442e1c 442 my( $reading, $lemma, $anchor, $opts ) = @_;
4d85a60e 443 return $reading if $reading eq $lemma;
444 my $oldreading = $reading;
445 # $lemma =~ s/\s+[[:punct:]]+$//;
e9442e1c 446 my $flag = {}; # To pass back extra info about the interpretation
4d85a60e 447 my @words = split( /\s+/, $lemma );
f9ffe014 448 # Discard any 'sic' notation - that rather goes without saying.
a5978ac8 449 $reading =~ s/([[:punct:]]+)?sic([[:punct:]]+)?//g;
f9ffe014 450
451 # Now look for common jargon.
452 if( $reading =~ /^(.*) praem.$/ || $reading =~ /^praem\. (.*)$/ ) {
4d85a60e 453 $reading = "$1 $lemma";
f9ffe014 454 } elsif( $reading =~ /^(.*) add.$/ || $reading =~ /^add\. (.*)$/ ) {
4d85a60e 455 $reading = "$lemma $1";
b8f262e8 456 } elsif( $reading =~ /locus [uv]acuus/
457 || $reading eq 'def.'
c9158e60 458 || $reading eq 'illeg.'
a5978ac8 459 || $reading eq 'desunt'
f6e19c7c 460 ) {
b8f262e8 461 $reading = '#LACUNA#';
462 } elsif( $reading eq 'om.' ) {
4d85a60e 463 $reading = '';
c9158e60 464 } elsif( $reading =~ /^in[uv]\.$/
a5978ac8 465 || $reading =~ /^tr(ans(p)?)?\.$/ ) {
4d85a60e 466 # Hope it is two words.
a188b944 467 say STDERR "WARNING: want to invert a lemma that is not two words"
4d85a60e 468 unless scalar( @words ) == 2;
469 $reading = join( ' ', reverse( @words ) );
12720144 470 } elsif( $reading =~ /^iter(\.|at)$/ ) {
4d85a60e 471 # Repeat the lemma
472 $reading = "$lemma $lemma";
a5978ac8 473 } elsif( $reading =~ /^(.*?)\s*\(?in marg\.\)?$/ ) {
474 $reading = $1;
475 if( $reading ) {
476 # The given text is a correction.
477 $flag->{'PC'} = 1;
478 } else {
479 # The lemma itself was the correction; the witness carried
480 # no reading pre-correction.
481 $flag->{'AC'} = 1;
482 }
12720144 483 } elsif( $reading =~ /^(.*) \.\.\. (.*)$/ ) {
4d85a60e 484 # The first and last N words captured should replace the first and
485 # last N words of the lemma.
486 my @begin = split( /\s+/, $1 );
487 my @end = split( /\s+/, $2 );
488 if( scalar( @begin ) + scalar ( @end ) > scalar( @words ) ) {
489 # Something is wrong and we can't do the splice.
dead25ca 490 throw( "$lemma is too short to accommodate $oldreading" );
4d85a60e 491 } else {
492 splice( @words, 0, scalar @begin, @begin );
493 splice( @words, -(scalar @end), scalar @end, @end );
494 $reading = join( ' ', @words );
495 }
e9442e1c 496 } elsif( $opts->{interpret_transposition} &&
a5978ac8 497 ( $reading =~ /^post\s*(?<lem>.*?)\s+tr(ans(p)?)?\.$/ ||
498 $reading =~ /^tr(ans(p)?)?\. post\s*(?<lem>.*)$/) ) {
e9442e1c 499 # Try to deal with transposed readings
500 ## DEBUG
501 say STDERR "Will attempt transposition: $reading at $anchor";
502 $reading = $lemma;
a5978ac8 503 $flag->{'TR'} = $+{lem};
12720144 504 }
505 return( $reading, $flag );
4d85a60e 506}
507
f6e19c7c 508sub _parse_wit_detail {
509 my( $detail, $readings, $lemma ) = @_;
510 my $wit = $detail->getAttribute( 'wit' );
511 my $content = $detail->textContent;
a5978ac8 512 if( $content =~ /^a\.?\s*c(orr)?\.$/ ) {
f6e19c7c 513 # Replace the key in the $readings hash
514 my $rdg = delete $readings->{$wit};
515 $readings->{$wit.'_ac'} = $rdg;
516 $has_ac{$sigil_for{$wit}} = 1;
a5978ac8 517 } elsif( $content =~ /^p\.?\s*c(orr)?\.$/ || $content =~ /^s\.?\s*l\.$/ ) {
f6e19c7c 518 # If no key for the wit a.c. exists, add one pointing to the lemma
519 unless( exists $readings->{$wit.'_ac'} ) {
520 $readings->{$wit.'_ac'} = $lemma;
521 }
522 $has_ac{$sigil_for{$wit}} = 1;
a5978ac8 523 } else { #...not sure what it is?
524 say STDERR "WARNING: Unrecognized sigil addendum $content";
525 }
f6e19c7c 526}
527
9e0a9786 528sub _add_lacunae {
529 my( $c, @apps ) = @_;
530 # Go through the apparatus entries in order, noting where to start and stop our
531 # various witnesses.
532 my %lacunose;
533 my $ctr = 0;
534 foreach my $app ( @apps ) {
535 # Find the anchor, if any. This marks the point where the text starts
536 # or ends.
537 my $anchor = $app->getAttribute( 'to' );
538 my $aname;
539 if( $anchor ) {
c8010abf 540 $anchor =~ s/^\#//;
9e0a9786 541 $aname = _anchor_name( $anchor );
542 }
543
544 foreach my $rdg ( $app->getChildrenByTagName( 'rdg' ) ) {
545 my @witlist = map { _get_sigil( $_, $c->ac_label ) }
546 split( /\s+/, $rdg->getAttribute( 'wit' ) );
547 my @start = $rdg->getChildrenByTagName( 'witStart' );
548 my @end = $rdg->getChildrenByTagName( 'witEnd' );
549 if( @start && @end ) {
550 throw( "App sig entry at $anchor has both witStart and witEnd!" );
551 }
552 if( @start && $anchor &&
553 $c->prior_reading( $aname, $c->baselabel ) ne $c->start ) {
554 # We are picking back up after a hiatus. Find the last end and
555 # add a lacuna link between there and here.
556 foreach my $wit ( @witlist ) {
557 my $stoppoint = delete $lacunose{$wit};
f60f9e0f 558 my $stopname = $stoppoint ? _anchor_name( $stoppoint ) : $c->start->id;
559 say STDERR "Adding lacuna for $wit between $stopname and $anchor";
9e0a9786 560 my $lacuna = $c->add_reading( { id => "as_$anchor.".$ctr++,
561 is_lacuna => 1 } );
562 _add_wit_path( $c, [ $lacuna ], $stopname, $aname, $wit );
563 }
564 } elsif( @end && $anchor &&
565 $c->next_reading( $aname, $c->baselabel ) ne $c->end ) {
566 # We are stopping. If we've already stopped for the given witness,
567 # flag an error; otherwise record the stopping point.
568 foreach my $wit ( @witlist ) {
569 if( $lacunose{$wit} ) {
570 throw( "Trying to end $wit at $anchor when already ended at "
571 . $lacunose{$wit} );
572 }
573 $lacunose{$wit} = $anchor;
574 }
575 }
576 }
577 }
578
579 # For whatever remains in the %lacunose hash, add a lacuna between that spot and
580 # $c->end for each of the witnesses.
581 foreach my $wit ( keys %lacunose ) {
582 next unless $lacunose{$wit};
583 my $aname = _anchor_name( $lacunose{$wit} );
584 say STDERR "Adding lacuna for $wit from $aname to end";
585 my $lacuna = $c->add_reading( { id => 'as_'.$lacunose{$wit}.'.'.$ctr++,
586 is_lacuna => 1 } );
587 _add_wit_path( $c, [ $lacuna ], $aname, $c->end, $wit );
588 }
589}
590
a445ce40 591sub _get_sigil {
592 my( $xml_id, $layerlabel ) = @_;
f6e19c7c 593 if( $xml_id =~ /^(.*)_ac$/ ) {
594 my $real_id = $1;
a445ce40 595 return $sigil_for{$real_id} . $layerlabel;
f6e19c7c 596 } else {
597 return $sigil_for{$xml_id};
598 }
599}
600
a445ce40 601sub _expand_all_paths {
f6e19c7c 602 my( $c ) = @_;
603
604 # Walk the collation and fish out the paths for each witness
605 foreach my $wit ( $c->tradition->witnesses ) {
606 my $sig = $wit->sigil;
12720144 607 my @path = grep { !$_->is_ph }
f6e19c7c 608 $c->reading_sequence( $c->start, $c->end, $sig );
609 $wit->path( \@path );
610 if( $has_ac{$sig} ) {
12720144 611 my @ac_path = grep { !$_->is_ph }
861c3e27 612 $c->reading_sequence( $c->start, $c->end, $sig.$c->ac_label );
f6e19c7c 613 $wit->uncorrected_path( \@ac_path );
614 }
615 }
616
617 # Delete the anchors
12720144 618 foreach my $anchor ( grep { $_->is_ph } $c->readings ) {
f6e19c7c 619 $c->del_reading( $anchor );
620 }
12720144 621 # Delete the base edges
622 map { $c->del_path( $_, $c->baselabel ) } $c->paths;
f6e19c7c 623
624 # Make the path edges
625 $c->make_witness_paths();
7c2ed85e 626
627 # Now remove any orphan nodes, and warn that we are doing so.
82a45078 628 while( $c->sequence->predecessorless_vertices > 1 ) {
629 foreach my $v ( $c->sequence->predecessorless_vertices ) {
630 my $r = $c->reading( $v );
631 next if $r->is_start;
632 say STDERR "Deleting orphan reading $r / " . $r->text;
633 $c->del_reading( $r );
634 }
7c2ed85e 635 }
4d85a60e 636}
637
638sub _add_wit_path {
f6e19c7c 639 my( $c, $rdg, $app, $anchor, $wit ) = @_;
4d85a60e 640 my @nodes = @$rdg;
f6e19c7c 641 push( @nodes, $c->reading( $anchor ) );
4d85a60e 642
f6e19c7c 643 my $cur = $c->reading( $app );
4d85a60e 644 foreach my $n ( @nodes ) {
f6e19c7c 645 $c->add_path( $cur, $n, $wit );
4d85a60e 646 $cur = $n;
6f4946fb 647 }
6f4946fb 648}
649
00311328 650sub throw {
651 Text::Tradition::Error->throw(
652 'ident' => 'Parser::CTE error',
653 'message' => $_[0],
654 );
655}
656
6f4946fb 657=head1 LICENSE
658
659This package is free software and is provided "as is" without express
660or implied warranty. You can redistribute it and/or modify it under
661the same terms as Perl itself.
662
663=head1 AUTHOR
664
665Tara L Andrews, aurum@cpan.org
666
667=cut
668
6691;
670