blib/lib/Text/TEI/Markup.pm

filter: Statementstmt 90.4% 255 / 282 Branchbran 79.2% 111 / 140 Conditioncond 70.8% 17 / 24 MC/DCmcdc 28.5% 4 / 14 Subroutinesub 100% 14 / 14 Podpod 100% 2 / 2 totaltotal 84.6% 403 / 476 CC 87 SCAR 29.1
CC
87
Cov
86%
_process_line
25.8
to_xml
20.5
_wrap_children
20.1
CRAP 18.4
↑ Summary
1 package Text::TEI::Markup;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use vars qw( $VERSION @EXPORT_OK );
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use XML::LibXML;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 1 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 1 $VERSION = '1.9';
12 1 @EXPORT_OK = qw( &to_xml &word_tag_wrap );
13  
14 =head1 NAME
15  
16 Text::TEI::Markup - a transcription markup syntax for TEI XML
17  
18 =head1 SYNOPSIS
19  
20 use Text::TEI::Markup qw( to_xml );
21 my $xml_string = to_xml( file => $markup_file,
22 template => $template_xml_string,
23 %opts ); # see below for available options
24  
25 use Text::TEI::Markup qw( word_tag_wrap );
26 my $word_wrapped_xml = word_tag_wrap( $tei_xml_string );
27  
28 =head1 DESCRIPTION
29  
30 TEI XML is a wonderful thing. The elements defined therein allow a
31 transcriber to record and represent just about any feature of a text that
32 he or she encounters.
33  
34 The problem is the transcription itself. When I am transcribing a
35 manuscript, especially if that manuscript is in a bunch of funny characters
36 on the keymap for another language, I do not want to be switching back and
37 forth between keyboard layouts in order to type "<tag attr="attr>"
38 arrow-arrow-arrow-arrow-arrow "</tag> every six seconds. It's prone to
39 typo, it's astonishingly slow, and it makes my wrists hurt just to think
40 about it. I also don't really want to fire up an XML editor, select the
41 words or characters that need to be tagged, and click a lot. That way is
42 not prone to typo, but it's still pretty darn slow, and it makes my wrists
43 hurt B<even more> to think about.
44  
45 Text::TEI::Markup is my solution to that problem. It defines a bunch of
46 single- or double-character sigils that represent tags. These are a lot
47 faster and easier to type; I don't have to worry about typos; and I can do
48 it all with a plain text editor, thus minimizing use of the mouse.
49  
50 I have tried to pick sigils that don't conflict with characters that are
51 found in manuscripts. I have succeeded for my particular set of
52 manuscripts, but I have not succeeded for the general case. If you like the
53 idea behind this module, you are still almost guaranteed to hate the sigils
54 I've picked. That's okay; you can re-define them.
55  
56 =head2 Extra bonus solution: word wrapping with <w/> and <seg/>
57  
58 Even if you are happy as a clam in the graphical XML editor of your choice,
59 this module exports a function that may be useful to you. The TEI P5
60 guidelines include a module called "analysis", which allows the user to tag
61 sentences, clauses, words, morphemes, or any other sort of semantic segment
62 of a text. This is really good for programmatic applications, but very
63 boring and repetitive to have to tag.
64  
65 The function B<word_tag_wrap> solves part of this problem for you. It takes
66 an XML string as input, looks for words (defined by whitespace separation)
67 and returns an XML string with each of these words wrapped in an
68 appropriate tag. If the word has complex elements (e.g. editorial
69 expansion), it will be wrapped in a <seg type="word/> tag. If not, it will
70 be in a simple <w/> tag. It handles line breaks and page breaks within
71 words, as long as there is no trailing whitespace before the <lb/> (or
72 <pb/>) tag, and as long as the whitespace after the tag contains a carriage
73 return.
74  
75 =head1 MARKUP SYNTAX
76  
77 The input file has a header and a body. The header begins with a '=HEAD'
78 tag, and consists of a colon-separated list of key_value pairs. These keys,
79 which are case insensitive, get directly substituted into an XML template;
80 the idea is that your TEI header won't change very much between files, so
81 you write it once with template values, pass it to &to_xml, and the
82 substitution happens as if by magic. The keyword /MAIN/i is reserved for
83 the content between the <body></body> tags - that is, all the content that
84 will be generated after the '=BODY' tag.
85  
86 A very simple template looks like this:
87  
88 <?xml version="1.0" encoding="UTF-8">
89 <TEI>
90 <teiHeader>
91 <fileDesc>
92 <titleStmt>
93 <title>__TITLE__</title>
94 <author__AUTHOR__</author>
95 <respStmt xml:id="#__MYINITIALS__">
96 <resp>Transcription by</resp>
97 <name>__MYNAME__</name>
98 </respStmt>
99 </titleStmt>
100 </fileDesc>
101 </teiHeader>
102 <text>
103 <body>
104 __MAIN__
105 </body>
106 </text>
107 </TEI>
108  
109 Your input file should then begin something like this:
110  
111 =HEAD
112 title:My Summer Vacation: a novel
113 author:John Smith
114 myinitials:tla
115 myname:Tara L Andrews
116 =BODY
117 The ^real^ text b\e\gins +(above)t+here.
118 ...
119  
120  
121 The real work begins after the '=BODY' tag. The currently-defined sigil
122 list is:
123  
124 %SIGILS = (
125 'comment' => '##',
126 'add' => '+',
127 'del' => '-',
128 'subst' => "\x{b1}", # Unicode PLUS-MINUS SIGN
129 'div' => "\x{a7}", # Unicode SECTION SIGN
130 'p' => "\x{b6}", # Unicode PILCROW SIGN
131 'ex' => '\\',
132 'expan' => '^',
133 'supplied' => '@',
134 'abbr' => [ '{', '}' ],
135 'num' => '%',
136 'pb' => [ '[', ']' ],
137 'cb' => '|',
138 'hi' => '*',
139 'unclear' => '?',
140 'q' => "\x{2020}", # Unicode DAGGER
141 );
142  
143 Non-identical matched sets of sigla (e.g. '{}' for abbreviations) should be
144 specified in a listref, as seen here.
145  
146 Whitespace is only significant at the end of lines. If a line which
147 contains non-tag text (i.e. words) ends in whitespace, it is assumed that
148 the previous word is a complete word. If the line ends with a
149 non-whitespace character, it is assume that the word continues onto the
150 next line.
151  
152 All the sigils must be balanced, and they must nest properly. Remember that
153 this is a shorthand for XML. I could be convinced to try to autocorrect
154 some unbalanced sigils, but it would be worth at least a few pints of cider
155 (or, of course, a patch.)
156  
157 =head2 Tag arguments
158  
159 Certain of the tags can be passed extra arguments:
160  
161 =over 4
162  
163 =item C<add / del>
164  
165 Anything that appears in parentheses immediately after the add/del opening
166 sigil ( + or - in the examples above) will get added as an attribute. If
167 the string in parentheses has no '=' sign in it, the attribute for the
168 "add" tag will be "place", and the attribute for the "del" tag will be
169 "type". Ergo:
170  
171 +(margin)This is an addition+
172 -(overwrite)and a deletion- to the sentence.
173  
174 will get translated to
175  
176 <add place="margin">This is an addition</add>
177 <del type="overwrite">and a deletion</del> to the sentence.
178  
179 This behavior ought to be more configurable and/or flexible; make it worth
180 my while.
181  
182 =item C<num>
183  
184 A number value can calculated using a number_conversion function, or it can
185 simply be specified. It is also possible to specify the type of number being
186 represented (B<card>inal, B<ord>inal, B<frac>tion, B<perc>entage). The arguments
187 are separated with a comma, and in the order "value", "type". So for example:
188  
189 The lead was taken by the Exeter %(8)VIII%. This was their
190 %(13,ord)thirteenth% straight win.
191  
192 will become:
193  
194 The lead was taken by the Exeter <num value="8">VIII</num>. This was their
195 <num value="13" type="ordinal">thirteenth</num> straight win.
196  
197 =item C<hi>
198  
199 When text highlighting is encoded, it is almost always a good idea to say
200 something about how the highlight was rendered. This information can be passed
201 as an argument:
202  
203 *(red)IN the beginning* was the word
204
205 will become
206  
207 <hi rend="red">IN the beginning</hi> was the word
208
209 =back
210  
211 =head1 SUBROUTINES
212  
213 =over 4
214  
215 =item B<to_xml>( file => '$filename', %opts );
216  
217 Takes the name of a file that holds a marked-up version of text. Returns a
218 TEI XML string to represent that text. Options include:
219  
220 =over 4
221  
222 =item C<template>
223  
224 a string containing the XML template that you want to use for the markup.
225 If none is specified, there is a default. That default is useful for me,
226 but is very unlikely to be useful for you. =item C<fileopen_mode>
227  
228 a mode string to pass to the open() call on the file. Default "<:utf8".
229  
230 =item C<number_conversion>
231  
232 a subroutine ref that will calculate the value of number representations.
233 Useful for, e.g., Latin numerals. This is optional - if nothing is passed,
234 no number value calculation will be attempted. =item C<sigils>
235  
236 a hashref containing the preferred sigil representations of TEI tags.
237 Defaults to the list above.
238  
239 =item C<wrap_words>
240  
241 Defaults to "true". If you pass a false value, the word wrapping will be
242 skipped.
243  
244 =item C<format>
245  
246 Defaults to 0. Controls whether rudimentary formatting is applied to the
247 XML returned. Possible values are 0, 1, and "more than 1". See
248 XML::LibXML::Document::serialize for more information. (Personally I just
249 xmllint it separately.)
250  
251 =back
252  
253 The return string is run through the basic formatting mechanism provided by
254 XML::LibXML. You may wish to pass it through a pretty printer more to your
255 taste.
256  
257 =cut
258  
259 # Default list of funky signs I use.
260 # TODO: Add header support
261 1 my %SIGILS = (
262 'comment' => '##',
263 'add' => '+',
264 'del' => '-',
265 'subst' => "\x{b1}",
266 'div' => "\x{a7}",
267 'p' => "\x{b6}",
268 'ex' => '\\',
269 'expan' => '^',
270 'supplied' => '@',
271 'abbr' => [ '{', '}' ],
272 'num' => '%',
273 'pb' => [ '[', ']' ],
274 'cb' => '|',
275 'hi' => '*',
276 'unclear' => '?',
277 'q' => "\x{2020}",
278 );
279
280 1 my @DTL = <DATA>;
281 1 my $DEFAULT_TEMPLATE = join( '', @DTL );
282  
283 2 ▶sub to_xml {
Subroutine to_xml: called CC=17 SCAR=30.2
Pod documented
284 2 my %opts = (
285 'number_conversion' => undef,
286 'fileopen_mode' => '<:utf8',
287 'wrap_words' => 1,
288 'sigils' => \%SIGILS,
289 'template' => undef,
290 'format' => 0,
291 @_,
292 );
293  
294 2 ▶ unless( defined( $opts{'file'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $opts{"file"}) 0 2 2
295 0 warn "No file specified! Doing nothing.";
296 0 return undef;
297 }
298  
299 2 ▶ if( defined $opts{'number_conversion'}
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"number_conversion"} and ref $opts{"number_conversion"} ne "CODE") 0 2 2
Condition33%1/3
defined $opts{"number_conversion"} and ref $opts{"number_conversion"} ne "CODE"
!ll&&!rl&&r
020
MC/DC0%0/2
defined $opts{"number_conversion"} and ref $opts{"number_conversion"} ne "CODE"
defined $opts{"number_conversion"} ref $opts{"number_conversion"} ne "CODE"
Truth table33%1/3
A and B
A= defined $opts{"number_conversion"}B= ref $opts{"number_conversion"} ne "CODE"
ABresult
0X0
100
111
300 && ref( $opts{'number_conversion'} ) ne 'CODE' ) {
301 0 warn "number_conversion argument must be a subroutine ref";
302 0 $opts{'number_conversion'} = undef;
303 }
304  
305 2 my $inbody;
306
307 2 my $rc = open( FILE, $opts{'fileopen_mode'}, $opts{'file'} );
308 2 ▶ unless( $rc ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rc) 0 2 2
309 0 warn "Could not open $opts{'file'}: $@";
310 0 return undef;
311 }
312  
313 2 my $tmpl;
314 2 ▶ if( defined $opts{'template'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{'template'}) { } 1 1 2
315 1 $tmpl = $opts{'template'};
316 } else {
317 1 $tmpl = $DEFAULT_TEMPLATE;
318 }
319  
320 2 my $main_xml;
321  
322 2 my( $in_p, $in_div ) = ( undef, undef );
323 2 ▶ while(<FILE>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline FILE)) 52 2 54
324 52 s/\R+$//g; # chomp, no matter the newline char
325 52 ▶ next if /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if /^\s*$/ 0 52 52
326 52 s/^\s*//; # but keep trailing spaces - they're significant!
327 52 _current_context( $_ );
328
329 52 ▶ if( /^=BODY/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (/^=BODY/) 2 50 52
330 2 $inbody = 1;
331 # Have we found a responsible person?
332 2 ▶ unless( exists $opts{'resp'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $opts{"resp"}) 0 2 2
333 0 warn "No responsible person specified for edits!";
334 }
335 2 next;
336 }
337
338 50 ▶ if( /^(\w+)\s*:\s*(.*)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (/^(\w+)\s*:\s*(.*)$/) 19 31 50
339 # Make the header template substitution.
340 19 ▶ _make_warning( "We are in the BODY section but this looks like a header" )
Branch: 1 branch
BranchTrueFalseTotal
if $inbody 0 19 19
341 if $inbody;
342 19 my( $key, $val ) = ( lc( $1 ), $2 );
343 19 $val =~ s/\s+$//;
344 19 ▶ if( $key eq 'main' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key eq 'main') { } 0 19 19
345 0 warn "You cannot use '$key' as a substitution key!";
346 } else {
347 19 $tmpl =~ s/__${key}__/$val/gi;
348 }
349 19 ▶ if( $key eq 'transcriberid' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key eq "transcriberid") 2 17 19
350 2 $opts{'resp'} = '#' . $val;
351 }
352 }
353
354 50 ▶ if( $inbody ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inbody) 29 21 50
355 # Send it to the parser.
356 29 my $line;
357 ## TODO: Upgrade to perl 5.10 to get state variables.
358 29 ( $line, $in_div, $in_p ) = _process_line( $_, $in_div, $in_p, %opts );
359 29 $main_xml .= $line;
360 }
361 }
362 2 close FILE;
363  
364 2 $tmpl =~ s/__MAIN__/$main_xml/;
365 2 ▶ if( $opts{'wrap_words'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{'wrap_words'}) { } 1 1 2
366 1 $tmpl = word_tag_wrap( $tmpl, $opts{'format'} );
367 } else {
368 # Just make sure it parses, and format it if asked.
369 1 my $parser = XML::LibXML->new();
370 1 my $doc;
371 1 my $ok = eval{ $doc = $parser->parse_string( $tmpl ); };
372 1 ▶ unless( $ok ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 1 1
373 0 warn "Parsing of the new XML doc failed: $@";
374 0 return undef;
375 }
376 1 $tmpl = decode( $doc->encoding, $doc->serialize( $opts{'format'} ) );
377 }
378 2 return $tmpl;
379 }
380  
381 29 ▶sub _process_line {
Subroutine _process_line: called CC=25 SCAR=32.5
382 29 my( $line, $in_div, $in_p, %opts ) = @_;
383 29 chomp $line;
384 29 my $checkline = $line; # This should be well-formed by the end
385 29 my $clopts = { %opts, 'nowarn' => 1 };
386 # Look for paragraph and div markers, i.e. our tags that can span multiple lines
387 # and that should be disregarded in the checkline.
388 29 my $sigils = $opts{'sigils'};
389 29 my( $divsig, $pgsig ) = ( $sigils->{'div'}, $sigils->{'p'} );
390 29 ▶ while( $line =~ /\Q$divsig\E(\d*)/g ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\Q$divsig\E(\d*)/g) 4 29 33
391 4 my $divno = $1;
392 # Calculate the starting position.
393 4 my $pos = pos( $line ) - 1;
394 4 ▶ $pos -= length( $divno ) if $divno;
Branch: 1 branch
BranchTrueFalseTotal
if $divno 0 4 4
395
396 4 ▶ if( $in_div ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($in_div) { } 2 2 4
397 2 ▶ _make_warning( "Nonsensical division number at end-division tag; are your '$divsig' tags balanced?" )
Branch: 1 branch
BranchTrueFalseTotal
if $divno 0 2 2
398 if $divno;
399 2 substr( $line, $pos, 1, '</div>' );
400 } else {
401 2 ▶ my $divstr = '<div' . ( $divno ? " n=\"$divno\"" : '' ) . ">";
Branch: 1 branch
BranchTrueFalseTotal
$divno ? : 0 2 2
402 2 substr( $line, $pos, pos( $line ) - $pos, $divstr );
403 }
404 4 $in_div = !$in_div;
405 }
406 29 $checkline =~ s/\Q$divsig\E//g;
407
408 29 ▶ while( $line =~ /\Q$pgsig\E/g ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\Q$pgsig\E/g) 8 29 37
409 8 ▶ my $p_str = '<' . ( $in_p ? '/' : '' ) . 'p>';
Branch: 1 branch
BranchTrueFalseTotal
$in_p ? : 4 4 8
410 8 substr( $line, pos( $line ) - 1, 1, $p_str );
411 8 $in_p = !$in_p;
412 }
413 29 $checkline =~ s/\Q$pgsig\E//g;
414
415 # Add and delete tags. Do this first so that we do not stomp later
416 # instances of the dash (e.g. in XML comments).
417 29 my $add_del_re = qr/([-+])(\(([^\)]+)\))?(.*?)\1/;
418 29 ▶ while( $line =~ /$add_del_re/g ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /$add_del_re/g) 5 29 34
419 5 my( $op, $attr, $word ) = ( $1, $3, $4 );
420 # Calculate starting position.
421 5 my $pos = pos( $line ) - ( length( $word ) + 2 );
422 # Also for the checkline.
423 5 $checkline =~ /$add_del_re/g;
424 5 my $cpos = pos( $checkline ) - ( length( $word ) + 2 );
425 5 ▶ $pos -= ( length( $attr ) + 2 ) if $attr;
Branch: 1 branch
BranchTrueFalseTotal
if $attr 3 2 5
426 5 ▶ $cpos -= ( length( $attr ) + 2 ) if $attr;
Branch: 1 branch
BranchTrueFalseTotal
if $attr 3 2 5
427 # Figure out what the attribute string, if any, should be.
428 5 my $attr_str;
429 5 ▶ if( $attr && $attr =~ /\=/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($attr and $attr =~ /\=/) { } 0 5 5
elsif ($attr) { } 3 2 5
Condition66%2/3
$attr and $attr =~ /\=/
!ll&&!rl&&r
230
MC/DC0%0/2
$attr and $attr =~ /\=/
$attr $attr =~ /\=/
Truth table66%2/3
A and B
A= $attrB= $attr =~ /\=/
ABresult
0X0
100
111
430 0 $attr_str = $attr;
431 } elsif ( $attr ) {
432 3 ▶ $attr_str = ( $op eq '+' ? "place" : "type" )
Branch: 1 branch
BranchTrueFalseTotal
$op eq '+' ? : 3 0 3
433 . "=\"$attr\"";
434 }
435 5 ▶ my $interp_str = '<' . ( $op eq '+' ? 'add' : 'del' )
Branch: 3 branches
BranchTrueFalseTotal
$op eq '+' ? : 3 2 5
$attr_str ? : 3 2 5
$op eq '+' ? : 3 2 5
436 . ( $attr_str ? " $attr_str" : '' )
437 . ">$word</" . ( $op eq '+' ? 'add' : 'del' ) . '>';
438 5 substr( $line, $pos, pos( $line ) - $pos, $interp_str );
439 5 substr( $checkline, $cpos, pos( $checkline ) - $cpos, $interp_str );
440 }
441  
442 # All the tags that are not very special cases.
443 29 foreach my $tag ( qw( subst abbr hi ex expan num unclear q supplied ) ) {
444 261 my $tag_sig = $sigils->{$tag};
445 261 my( $tag_open, $tag_close );
446 261 ▶ if( ref( $tag_sig ) eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $tag_sig eq 'ARRAY') { } 29 232 261
447 29 ( $tag_open, $tag_close ) = @$tag_sig;
448 } else {
449 232 $tag_open = $tag_close = $tag_sig;
450 }
451 261 $line =~ s|\Q$tag_open\E(.*?)\Q$tag_close\E|_open_tag( $tag, $1, \%opts ) . "</$tag>"|ge;
452 261 $checkline =~ s|\Q$tag_open\E(.*?)\Q$tag_close\E|_open_tag( $tag, $1, $clopts ) . "</$tag>"|ge;
453 }
454  
455 # Standalone tags that aren't special cases. Currently only cb.
456 29 foreach my $tag ( qw( cb ) ) {
457 29 my $tag_sig = $sigils->{$tag};
458 29 $line =~ s|\Q$tag_sig\E|"<$tag/>"|ge;
459 29 $checkline =~ s|\Q$tag_sig\E|"<$tag/>"|ge;
460 }
461
462
463 # Page breaks. Defined by the delimiters, plus an optional
464 # page/folio number & recto/verso indicator, on a line by itself.
465 # Of course other languages may use other sigils to indicate recto
466 # verso, so do not look for 'r' and 'v' specifically.
467 29 my $pb_sig = $sigils->{'pb'};
468 29 my ( $pb_open, $pb_close );
469 29 ▶ if( ref( $pb_sig ) eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $pb_sig eq 'ARRAY') { } 29 0 29
470 29 ( $pb_open, $pb_close ) = @$pb_sig;
471 } else {
472 0 $pb_open = $pb_sig;
473 0 $pb_close = $pb_sig;
474 }
475 29 $line =~ s|^\Q$pb_open\E(\d+(.)?)\Q$pb_close\E\s*$|<pb n=\"$1\"/>|;
476 29 $checkline =~ s|^\Q$pb_open\E(\d+(.)?)\Q$pb_close\E\s*$|<pb n=\"$1\"/>|;
477
478 # XML comments. Convert ## text ## to <!-- text -->
479 29 my $com_sig = $sigils->{'comment'};
480 29 my ( $com_open, $com_close );
481 29 ▶ if( ref( $com_sig ) eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $com_sig eq 'ARRAY') { } 0 29 29
482 0 ( $com_open, $com_close ) = @$com_sig;
483 } else {
484 29 $com_open = $com_close = $com_sig;
485 }
486 29 $line =~ s|\Q$com_open\E(.*?)\Q$com_close\E|<!--$1-->|g;
487 29 $checkline =~ s|\Q$com_open\E(.*?)\Q$com_close\E|<!--$1-->|g;
488
489 # At this point our check-line should be well-balance. Send a warning if not.
490 29 my $parser = XML::LibXML->new();
491 29 my $fragment;
492 29 my $ok = eval{ $fragment = $parser->parse_balanced_chunk( "<TAG>$checkline</TAG>" ); };
493 29 ▶ unless( $ok ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 29 29
494 0 _make_warning( "Sigils are not properly nested." );
495 }
496  
497 # Finally, every line with text outside an XML tag must have a line
498 # break. Any lb tag should be inside a cb, p, or div tag.
499 29 my $testline = $line;
500 29 $testline =~ s/<[^>]*>//g;
501 29 ▶ if( $testline =~ /\S/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($testline =~ /\S/) 19 10 29
502 1 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
503 19 $line =~ s!(</p>|</div>|<cb/>)?$!<lb/>$1!;
504 }
505  
506 # Return the expanded line.
507 29 return( "$line\n", $in_div, $in_p );
508 }
509  
510 100 ▶sub _open_tag {
Subroutine _open_tag: called CC=17 SCAR=28.7
511 100 my( $tag, $text, $opts ) = @_;
512  
513 100 my $opened_tag;
514 # Does the tag take a parenthesized argument?
515 100 my $arg = '';
516 100 ▶ if( $text =~ /^\(([^\)]+)\)(.*)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /^\(([^\)]+)\)(.*)$/) 8 92 100
517 8 ( $arg, $text ) = ( $1, $2 );
518 }
519 100 ▶ if( $tag =~ /^(ex|expan|supplied)$/ ) {
Branch: 4 branches
BranchTrueFalseTotal
if ($tag =~ /^(ex|expan|supplied)$/) { } 76 24 100
elsif ($tag eq 'q') { } 0 24 24
elsif ($tag eq 'num') { } 12 12 24
elsif ($tag eq 'hi') { } 4 8 12
520 # It takes a resp agent.
521 76 $opened_tag = '<'. $tag .' resp="' . $opts->{'resp'} . "\">$text";
522 } elsif ( $tag eq 'q' ) {
523 # Special case - we mean a biblical quote.
524 0 $opened_tag = '<q type="biblical">' . $text;
525 } elsif ( $tag eq 'num' ) {
526 # Derive the number's value if requested.
527 12 my $nv;
528 12 ▶ if( $arg ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($arg) 6 6 12
529 6 my $nt;
530 6 my %ntabbr = (
531 'ord' => 'ordinal',
532 'card' => 'cardinal',
533 'frac' => 'fraction',
534 'perc' => 'percentage' );
535 6 ( $nv, $nt ) = split( /,/, $arg );
536 6 ▶ $nt = $ntabbr{$nt} || $nt;
Condition66%2/3
$ntabbr{$nt} || $nt
l!l&&r!l&&!r
402
MC/DC50%1/2
$ntabbr{$nt} || $nt
$ntabbr{$nt} $nt
Truth table66%2/3
A || B
A= $ntabbr{$nt}B= $nt
ABresult
1X1
011
000
537 6 ▶ if( $nt ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nt) { } 4 2 6
538 4 $opened_tag = sprintf( '<num value="%s" type="%s">%s',
539 $nv, $nt, $text );
540 } else {
541 2 $opened_tag = sprintf( '<num value="%s">%s', $nv, $text );
542 }
543 }
544 12 ▶ unless( defined $nv ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $nv) 6 6 12
545 6 my $numconvert = $opts->{'number_conversion'};
546 6 ▶ if( defined $numconvert ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $numconvert) 6 0 6
547 # Strip any XML markup from the element contents.
548 6 my $parser = XML::LibXML->new();
549 6 my $fragment;
550 6 my $ok = eval{ $fragment = $parser->parse_balanced_chunk( $text ); };
551 6 ▶ if( $ok ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ok) { } 6 0 6
552 6 $nv = &$numconvert( uc( $fragment->textContent() ) );
553 } else {
554 _make_warning( "Unbalanced chunk in number tag: $text" )
555 0 ▶ unless $opts->{nowarn};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts->{"nowarn"} 0 0 0
556 }
557 6 ▶ $opened_tag = sprintf( '<num value="%s">%s', $nv, $text )
Branch: 1 branch
BranchTrueFalseTotal
if defined $nv 6 0 6
558 if defined $nv;
559 }
560 }
561 } elsif ( $tag eq 'hi' ) {
562 4 ▶ unless( $arg ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($arg) 2 2 4
563 _make_warning( "What kind of highlighting is this?" )
564 2 ▶ unless $opts->{nowarn};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts->{"nowarn"} 1 1 2
565 2 $arg = 'DEFAULT';
566 }
567 4 $arg =~ s/\s+/_/g;
568 4 $opened_tag = sprintf( '<%s rend="%s">%s', $tag, $arg, $text );
569 }
570  
571 # The default
572 100 ▶ $opened_tag = "<$tag>$text" unless $opened_tag;
Branch: 1 branch
BranchTrueFalseTotal
unless $opened_tag 8 92 100
573 100 return $opened_tag;
574 }
575  
576 1 ▶sub _make_warning {
Subroutine _make_warning: called CC=1 SCAR=0.0
577 1 my $message = shift;
578 1 my $context = _current_context();
579 1 my $warning = "($.) $context\n\tPossible problem! $message";
580 1 warn $warning;
581 }
582  
583  
584 ## Utility to keep track of where we are
585 {
586 1 my $curr_line;
587
588 53 ▶ sub _current_context {
Subroutine _current_context: called CC=2 SCAR=6.9
589 53 ▶ if( @_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 52 1 53
590 52 $curr_line = shift;
591 }
592 53 return $curr_line;
593 }
594 }
595  
596 =item B<word_tag_wrap>( $xml_string )
597  
598 Takes a string containing a TEI XML document, and returns that
599 document with all its words wrapped in <w/> (or <seg/>) tags. A
600 "word" is defined as a series of text characters separated by
601 whitespace. A word can have a line break, or even a page break, in
602 the middle; if this is the case, there I<may not> be any whitespace
603 between the end of the first word segment and the <lb/> (or <pb/>)
604 tag. Conversely, there I<must> be whitespace separating the <lb/> (or
605 <pb/>) from a complete word.
606  
607 =cut
608  
609 1 ▶sub word_tag_wrap {
Subroutine word_tag_wrap: called CC=12 SCAR=25.5
Pod documented
610 4 my( $xml, $format ) = @_;
611  
612 4 my $ret;
613 my $doc;
614 4 my $root;
615 4 ▶ if( !ref( $xml ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not ref $xml) { } 2 2 4
elsif (ref $xml eq 'XML::LibXML::Document') { } 2 0 2
elsif (ref $xml eq 'XML::LibXML::Element') { } 0 0 0
616 2 $ret = 'string';
617 2 my $parser = XML::LibXML->new();
618 2 $doc = $parser->parse_string( $xml );
619 2 $root = $doc->getDocumentElement();
620 } elsif( ref( $xml ) eq 'XML::LibXML::Document' ) {
621 2 $ret = 'xml';
622 2 $root = $xml->getDocumentElement();
623 } elsif( ref( $xml ) eq 'XML::LibXML::Element' ) {
624 0 $ret = 'xml';
625 0 $root = $xml;
626 } else {
627 0 die "Passed argument is neither string, Document, or Element";
628 }
629
630 4 my @paragraphs;
631 4 foreach my $t ( $root->getElementsByTagName( 'text' ) ) {
632 # Get the paragraphs in this text node; if it is already the same as
633 # a paragraph in our list, skip it.
634 6 foreach my $p ( $t->getElementsByTagName( 'p' ) ) {
635 10 ▶ next if grep { $_->isSameNode( $p ) } @paragraphs;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$_->isSameNode($p);} @paragraphs 2 8 10
636 8 push( @paragraphs, $p );
637 }
638 }
639 4 foreach my $p ( @paragraphs ) {
640 8 my $new_p = _wrap_children( $p );
641 # Remove the final whitespace from the paragraphs
642 8 my $lc = $new_p->lastChild;
643 8 ▶ if( ref( $lc ) eq 'XML::LibXML::Text' && $lc->data =~ /^\s+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $lc eq "XML::LibXML::Text" and $lc->data =~ /^\s+$/) 5 3 8
Condition66%2/3
ref $lc eq "XML::LibXML::Text" and $lc->data =~ /^\s+$/
!ll&&!rl&&r
305
MC/DC50%1/2
ref $lc eq "XML::LibXML::Text" and $lc->data =~ /^\s+$/
ref $lc eq "XML::LibXML::Text" $lc->data =~ /^\s+$/
Truth table66%2/3
A and B
A= ref $lc eq "XML::LibXML::Text"B= $lc->data =~ /^\s+$/
ABresult
0X0
100
111
644 5 $new_p->removeChild( $lc );
645 }
646 8 $p->replaceNode( $new_p );
647 }
648
649 # Annoyingly, we have to decode the encoding that takes place when
650 # the string is returned.
651 4 ▶ if( $ret eq 'string' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ret eq "string") 2 2 4
652 2 ▶ $format = 0 unless $format;
Branch: 1 branch
BranchTrueFalseTotal
unless $format 2 0 2
653 2 return decode( $doc->encoding(), $doc->serialize( $format ) );
654 } # else the doc has been modified and we need return nothing.
655 }
656  
657 8 ▶sub _wrap_children {
Subroutine _wrap_children: called CC=19 SCAR=30.0
658 8 my $node = shift;
659 8 my @children = $node->childNodes;
660  
661 # Make a new version of the element in question, with its name & attributes
662 8 my $new_node = XML::LibXML::Element->new( $node->nodeName );
663 # Set the namespace
664 8 my $docns = $node->namespaceURI;
665 8 $new_node->setNamespace( $docns );
666 8 foreach my $attr ( $node->attributes ) {
667 0 my( $aname, $aval ) = split( /=/, $attr );
668 0 $aname =~ s/\s+//g;
669 0 $aval =~ s/\"//g;
670 0 $new_node->setAttribute( $aname, $aval );
671 }
672 8 my $open_word_node = undef;
673 8 foreach my $c ( @children ) {
674 # Is it a text node?
675 227 ▶ if( ref( $c ) eq 'XML::LibXML::Text' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $c eq 'XML::LibXML::Text') { } 112 115 227
676 # Get the text.
677 112 my $str = $c->textContent;
678 # Strip out carriage returns and their surrounding spaces.
679 # Carriage returns should only occur after <lb/> elements,
680 # and the spaces around them should therefore be insignificant.
681 112 $str =~ s/^\s*\n\s*//gs;
682 # If there is nothing at all but a newline + initial spaces,
683 # pretend that the node isn't there at all.
684 112 ▶ next unless $str;
Branch: 1 branch
BranchTrueFalseTotal
unless $str 8 104 112
685  
686 # Get the individual words.
687 104 my @words = split( /\s+/, $str );
688  
689 # Finish out the last word if we need to.
690 104 ▶ if( $open_word_node ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($open_word_node) 85 19 104
691 # If there are any words in this text string, the
692 # first one should be used to close out the open node.
693 # If the first word is empty, it's a space and the
694 # word should just be closed. If there are no words
695 # at all, it was just a space. If the first word was
696 # all there is, we haven't encountered a space yet and
697 # need to keep the word open.
698 85 ▶ if( @words ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@words) { } 58 27 85
699 58 my $first = shift @words;
700 58 ▶ $open_word_node->appendText( $first ) if $first;
Branch: 1 branch
BranchTrueFalseTotal
if $first 38 20 58
701 } else {
702 27 ▶ $open_word_node = undef unless @words;
Branch: 1 branch
BranchTrueFalseTotal
unless @words 27 0 27
703 }
704 }
705  
706 104 foreach( @words ) {
707 # Skip whitespace "words"
708 427 ▶ next unless /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless /\S/ 0 427 427
709  
710 # Make a new node for the word
711 427 my $word_node = XML::LibXML::Element->new( 'w' );
712 427 $word_node->setNamespace( $docns );
713 427 $word_node->appendText( $_ );
714 427 $new_node->appendChild( $word_node );
715 427 $new_node->appendText(' ');
716 # ...and keep it open until we find a new word or a space
717 427 $open_word_node = $word_node;
718 }
719
720 # Close the last word node if our text node ends in a space.
721 104 ▶ if( $str =~ /\s+$/s ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str =~ /\s+$/s) 73 31 104
722 73 $open_word_node = undef;
723 }
724 } else {
725 115 my $wrapped_child;
726 115 ▶ if ( ref( $c ) ne 'XML::LibXML::Comment' && $c->textContent ne ''
Branch: 1 branch
BranchTrueFalseTotal
if (ref $c ne "XML::LibXML::Comment" and $c->textContent ne "" and $c->textContent =~ /\s+/) 0 115 115
Condition83%5/6
ref $c ne "XML::LibXML::Comment" and $c->textContent ne "" and $c->textContent =~ /\s+/
!ll&&!rl&&r
41740
ref $c ne "XML::LibXML::Comment" and $c->textContent ne ""
!ll&&!rl&&r
33874
MC/DC0%0/3
ref $c ne "XML::LibXML::Comment" and $c->textContent ne "" and $c->textContent =~ /\s+/
ref $c ne "XML::LibXML::Comment" $c->textContent ne "" $c->textContent =~ /\s+/
Truth table75%3/4
A and B and C
A= ref $c ne "XML::LibXML::Comment"B= $c->textContent ne ""C= $c->textContent =~ /\s+/
ABCresult
0XX0
10X0
1100
1111
727 && $c->textContent =~ /\s+/ ) {
728 # Recurse on any node that itself contains whitespace-separated text.
729 0 my $new_c = _wrap_children( $c );
730 0 $wrapped_child = ( $c->toString() ne $new_c->toString() );
731 0 $c = $new_c;
732 }
733
734 # If there is an open word node, make it a seg and append
735 # our result there; if the child has text content but no
736 # word children, wrap it in a new seg; otherwise just pass
737 # it on through.
738 115 ▶ if( $open_word_node ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($open_word_node) { } 37 78 115
elsif (ref $c eq 'XML::LibXML::Comment' or $c->textContent eq '' or $wrapped_child) { } 24 54 78
739 37 $open_word_node->setNodeName( 'seg' );
740 37 $open_word_node->setAttribute( 'type', 'word' );
741 37 $open_word_node->appendChild( $c );
742 ▶ } elsif( ref( $c ) eq 'XML::LibXML::Comment' || $c->textContent eq ''
Condition83%5/6
ref $c eq "XML::LibXML::Comment" or $c->textContent eq "" or $wrapped_child
l!l&&r!l&&!r
24054
ref $c eq "XML::LibXML::Comment" or $c->textContent eq ""
l!l&&r!l&&!r
32154
MC/DC66%2/3
ref $c eq "XML::LibXML::Comment" or $c->textContent eq "" or $wrapped_child
ref $c eq "XML::LibXML::Comment" $c->textContent eq "" $wrapped_child
Truth table75%3/4
A or B or C
A= ref $c eq "XML::LibXML::Comment"B= $c->textContent eq ""C= $wrapped_child
ABCresult
1XX1
01X1
0011
0000
743 || $wrapped_child ) {
744 24 $new_node->appendChild( $c );
745 } else {
746 54 my $segment_node = XML::LibXML::Element->new( 'seg' );
747 54 $segment_node->setNamespace( $docns );
748 54 $segment_node->setAttribute( 'type', 'word' );
749 54 $segment_node->appendChild( $c );
750 54 $new_node->appendChild( $segment_node );
751 54 $new_node->appendText(' ');
752 # Keep it open in case there is not a leading space on the next
753 # text node.
754 54 $open_word_node = $segment_node;
755 }
756 }
757 }
758  
759 8 return $new_node;
760 }
761  
762 1 1;
763  
764 =back
765  
766 =head1 BUGS / TODO
767  
768 The XML is not currently validated against a schema. This is mostly
769 because I have been unable to get RelaxNG validation to work against
770 certain TEI schemas.
771  
772 This module is currently in a state that I know to be useful to me.
773 If it looks like it might be useful to you, but something is bugging
774 you about it, report it!
775  
776 =head1 LICENSE
777  
778 This package is free software and is provided "as is" without express
779 or implied warranty. You can redistribute it and/or modify it under
780 the same terms as Perl itself.
781  
782 =head1 AUTHOR
783  
784 Tara L Andrews, L<aurum@cpan.org>
785  
786  
787 =cut
788  
789 __DATA__
↑ Summary