XPathScript/Stylesheet/DocBook2LaTeX.pm

filter: Statementstmt 21.6% 92 / 426 Branchbran 0.0% 0 / 154 Conditioncond 0.0% 0 / 32 MC/DCmcdc 0.0% 0 / 20 Subroutinesub 25.5% 12 / 47 Podpod 34.4% 10 / 29 totaltotal 16.1% 114 / 708 CC 98 SCAR 44.5
CC
98
Cov
15%
tc_wholedoc
377.2
render_authors
132.0
apply_templates_under
90.0
CRAP 85.9
↑ Summary XPathScript.pm »
1 package XML::XPathScript::Stylesheet::DocBook2LaTeX;
2 1 our $AUTHORITY = 'cpan:YANICK';
3 1 $XML::XPathScript::Stylesheet::DocBook2LaTeX::VERSION = '2.00';
4 # ABSTRACT: Transforms DocBook into LaTeX
5  
6 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 1 ▶use XML::XPathScript::Processor;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 1 our $processor;
13  
14 1 our $stylesheet = <<'END_STYLESHEET';
15 <%
16 $XML::XPathScript::current->interpolating( 0 );
17 $XML::XPathScript::Stylesheet::DocBook2LaTeX::processor = $processor;
18 $template->import_template(
19 $XML::XPathScript::Stylesheet::DocBook2LaTeX::template );
20 %><%~ / %>
21 END_STYLESHEET
22  
23 1 our $numbered_sections = 1;
24  
25 1 our $firstpage;
26  
27 1 our @documentclass_args = qw/ 11pt twoside a4paper /;
28 # LaTeX packages in use with their options
29 1 our @packages=(
30 ["fontenc" => "T1"],
31 ["inputenc" => "latin1"],
32 "fancybox",
33 "textcomp", # For \textcurrency
34 ["aeguill" => "cyr"],
35 "aecompl",
36 "graphicx",
37 "epsfig",
38 "amssymb",
39 "wasysym",
40 "pifont",
41 );
42 # "longtable" and "multirow" will be \usepackage'd if $fancytables=1, even
43 # though they don't belong to this list.
44  
45 # Do we want bells-n'whistles with LaTeX tables ?
46 1 our $fancytables = 1;
47  
48 # Arguments to the opening \documentclass{} macro call
49 1 our $documentclass;
50  
51 # Section hierarchy
52 1 our @sectionnames = qw(part chapter section subsection subsubsection paragraph subparagraph);
53 1 my @secttypes=qw( part chapter section sect1 sect2 sect3 sect4 sect5
54 preface refentry refsect1 refsect2 refsect3 refsect4
55 refsect5);
56  
57 1 our $TeXkludges=<<'KLUDGES';
58 \makeatletter
59 \let\IDXbacksl\@backslashchar
60 \let\IDX@oldtt\texttt
61 \def\texttt#1{{%
62 \@ifundefined{NoAutoSpaceBeforeFDP}{}{\NoAutoSpaceBeforeFDP}%
63 \IDX@oldtt{#1}}}
64 \makeatother
65 KLUDGES
66  
67  
68 # Hash table for converting Unicode to LaTeX characters or macro sequences.
69 # The keys are the Unicode character codes
70 # (http://www.unicode.org/charts/charindex.html). The corresponding values
71 # are the LaTeX counterpart to use to represent those characters. By
72 # default, whitespace and Latin1 characters are replaced with
73 # themselves; unknown characters are replaced with $uniunknown (see below)
74  
75 1 our %uniconvs=(
76 # Those are Latin1 and have no business here, except that
77 # we use them to quote things to protect during the
78 # quoting process (elegant hack if I may)
79 ord('<') => '{<}', # Also prevents kerning into "«"
80 ord('>') => '{>}',
81  
82 # TeX's shenanigans
83 ord('µ') => '\ensuremath{µ}',
84 ord('_') => '\_',
85 ord('^') => '{\^\relax}',
86 ord('$') => '\$',
87 ord('%') => '\%',
88 ord('~') => '{\string~}',
89 ord('@') => "{\\string @}",
90 ord('{') => '\{',
91 ord('}') => '\}',
92 ord('#') => '\#',
93 ord('&') => '\&',
94 ord('[') => '{[}',
95 ord(']') => '{]}',
96 ord('\\') => '{\IDXbacksl}',
97 ord('-') => '{-}', # Prevents unwanted kerning
98 ord("'") => "{'}", # Ditto
99 ord("`") => "{`}", # Ditto
100 ord(",") => "{,}", # Ditto
101  
102 # Extra Unicode characters
103 0x0152 => '{\OE}', # &OElig;
104 0x0153 => '{\oe}', # &oelig;
105  
106 0x2009 => '{\,}', # &thinsp;
107 0x2011 => '~', # &nbsp;
108 0x2013 => "{--}", # &ndash;
109 0x2014 => "{---}", # &mdash;
110 0x2026 => '...', # &hellip; - FIXME : this is OK for french
111 # only, english uses \ldots
112 0x2605 => '\ensuremath{\bigstar}',
113  
114 0x263a => '\smiley{}', # No ISO entity set, use &#x263A;
115 0x2713 => '\ding{51}', # &check;
116 0x2717 => '\ding{55}', # &cross;
117 );
118  
119 # This is the regexp that matches characters that are _not_ invariant
120 # through utf8totex(). We cache it for efficiency.
121 1 our $noninvarchar = RE_of_uniconvs(\%uniconvs);
122  
123 1 our $uniunknown= '???'; # replaces unknown unicode chars in output
124  
125 1 our $TeXpreamble=<<'PREAMBLE';
126 \cornersize*{6pt} % For fancybox
127 \setlength{\topmargin}{0.1in}
128 \setlength{\oddsidemargin}{0.5cm}
129 \setlength{\evensidemargin}{0.5cm}
130 \setlength{\textwidth}{6in}
131 \setlength{\hoffset}{0cm}
132 PREAMBLE
133  
134 1 our $TeXbegindocument=<<'BEGINDOCUMENT';
135 \sloppypar
136 BEGINDOCUMENT
137  
138 1 our $maketitle;
139 1 our $title;
140  
141 # Useful as a return value in many templates
142 1 our $_doNotProcessTitles=qq'*[name()!="title" and name() != "subtitle" and name() != "titleabbrev"]';
143  
144  
145 1 our @tablesatbeginning=qw(tableofcontents);
146 1 our @tablesatend=();
147  
148 1 our %character_emph=( pre=>'\emph{', post=>'}');
149  
150 1 our $template = XML::XPathScript::Template->new;
151  
152 1 $template->set( '*' => { testcode => \&tc_catchall } );
153 1 $template->set( beginpage => { pre => "\\newpage\n" } );
154 1 $template->set( [ qw/ article book / ]
155 => { testcode => \&tc_wholedoc } );
156 1 $template->set( 'author' => { testcode => \&tc_author } );
157 1 $template->set( [ qw/ editor collab corpauthor othercredit
158 firstname honorific surname affiliation
159 authorblurb credit publishername
160 orgname link refentrytitle productname
161 / ] => { showtag => 0 } );
162 1 $template->set( [ @secttypes ] => { testcode => \&tc_section } );
163 1 $template->set( 'para' => { testcode => \&tc_para } );
164 1 $template->set( [ qw/ screen programlisting / ]
165 => { testcode => \&tc_screen,
166 post => "\\par\n\n" } );
167 1 $template->set( 'emphasis' => {
168 testcode => \&tc_emphasis,
169 pre=>'\emph{',
170 post=>'}'
171 } );
172 1 $template->set( variablelist => { testcode => \&tc_variablelist,
173 pre => '\begin{description}',
174 post => '\end{description}', } );
175 1 $template->set( 'varlistentry' => { testcode => \&tc_varlisentry } );
176 1 $template->set( 'anchor' => { showtag => 0 } );
177 1 $template->set( [ qw/literal email command application citerefentry
178 constant token function option olink systemitem
179 classname type / ] => {
180 pre => '\texttt{',
181 post => '}',
182 } );
183 1 $template->set( quote => { testcode => \&tc_quote } );
184 1 $template->set( itemizedlist => {
185 testcode => \&tc_itemizedlist,
186 pre => '\begin{itemize}',
187 post => "\\end{itemize}\n" } );
188 1 $template->set( listitem => {
189 testcode => \&tc_listitem,
190 pre => "\n\\item ",
191 } );
192 1 $template->set( 'text()' => { testcode => \&tc_text } );
193  
194 #===== testcode functions =================================
195  
196 0 ▶sub tc_text {
Subroutine tc_text: not called CC=6 SCAR=37.4
Pod undocumented
197 0 my ($self, $t)=@_;
198  
199 0 my $value=utf8totex($self);
200 0 ▶ unless ($value =~ m/^\s+$/s) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($value =~ /^\s+$/s) 0 0 0
201 0 $t->{pre}= $value;
202 0 return DO_SELF_ONLY;
203 }
204  
205 # Here comes XML inter-tag whitespace brain twisting:
206 # </footnote> <literal> should produce whitespace
207 # </footnote> </para> . should not produce whitespace
208 # <footnote> <para>... should not (but we don't care)
209 # bla <!-- bla -->ware should render "bla ware"
210 # </footnote> <!-- ha --> </para> . should not produce whitespace!
211 # so it _looks like_ whitespace is legitimate iff we have both a
212 # preceding and following non-empty-rendering sibling element to
213 # separate from. We neglect the case of elements such as <anchor/>
214 # that have no text representation and should therefore be counted
215 # as empty.
216  
217 0 my $neighbours=0;
218 0 foreach my $axis (qw(preceding-sibling following-sibling)) {
219 $neighbours++ if grep {
220 0 ▶ $processor->is_text_node($_) ?
Branch: 2 branches
BranchTrueFalseTotal
if grep {$XML::XPathScript::Stylesheet::DocBook2LaTeX::processor->is_text_node($_) ? $XML::XPathScript::Stylesheet::DocBook2LaTeX::processor->xpath_to_string($_) =~ /\S/ : $XML::XPathScript::Stylesheet::DocBook2LaTeX::processor->is_element_node($_);} $self->findnodes("${axis}::node()") 0 0 0
$XML::XPathScript::Stylesheet::DocBook2LaTeX::processor->is_text_node($_) ? : 0 0 0
221 ($processor->xpath_to_string($_) =~ m/\S/) :
222 $processor->is_element_node($_)
223 } ($self->findnodes("${axis}::node()"));
224 };
225  
226 0 ▶ $t->{pre} = $value unless $neighbours < 2;
Branch: 1 branch
BranchTrueFalseTotal
unless $neighbours < 2 0 0 0
227  
228 0 return DO_SELF_ONLY;
229 };
230  
231 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
232  
233 # author ::=
234 # ((honorific|firstname|surname|lineage|othername|affiliation|
235 # authorblurb|contrib)+)
236 # The "+" is bizarre - we assume there are only one of each.
237  
238 0 ▶sub tc_author {
Subroutine tc_author: not called CC=4 SCAR=30.0
Pod undocumented
239 0 my ($self, $t)=@_;
240  
241 0 my @nameparts;
242  
243 0 foreach my $tag (qw(honorific firstname othername surname lineage)) {
244 0 ▶ if (my ($node)=findnodes($tag,$self)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($node) = findnodes($tag, $self)) 0 0 0
245 0 my $name=apply_templates($node);
246 0 $name =~ s/^\s*//g; $name =~ s/\s*$//g;
247 0 push(@nameparts, $name);
248 };
249 };
250  
251 0 $t->{pre}=join(" ",@nameparts);
252  
253 0 ▶ if (my ($node)=findnodes("affiliation",$self)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($node) = findnodes("affiliation", $self)) 0 0 0
254 0 $t->{pre}.=sprintf(" (%s)",apply_templates($node));
255 };
256  
257 0 return -1;
258 }
259  
260 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
261  
262 0 ▶sub tc_listitem {
Subroutine tc_listitem: not called CC=2 SCAR=17.9
Pod undocumented
263 0 my ($self,$t)=@_;
264 0 ▶ if (my $label=thelabel($self)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $label = thelabel($self)) 0 0 0
265 0 $t->{pre}.=" $label";
266 };
267 0 return 1;
268 }
269  
270 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
271  
272 0 ▶sub tc_itemizedlist {
Subroutine tc_itemizedlist: not called CC=1 SCAR=6.9
Pod undocumented
273 0 my ($self,$t)=@_;
274  
275 0 $t->{pre}=listtitle($self).$t->{pre};
276  
277 0 return '*[name()!="title"]';
278 }
279  
280 0 ▶sub tc_quote {
Subroutine tc_quote: not called CC=5 SCAR=34.0
Pod undocumented
281 0 my ($self,$t)=@_;
282  
283 0 my $lang=langofnode($self);
284 0 my ($nested)= $self->findnodes("ancestor::quote");
285  
286 0 ▶ if ($lang && $lang =~ m/^fr/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lang and $lang =~ /^fr/i) { } 0 0 0
Condition0%0/3
$lang and $lang =~ /^fr/i
!ll&&!rl&&r
000
MC/DC0%0/2
$lang and $lang =~ /^fr/i
$lang $lang =~ /^fr/i
Truth table0%0/3
A and B
A= $langB= $lang =~ /^fr/i
ABresult
0X0
100
111
287 0 ▶ if ($nested) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nested) { } 0 0 0
288 0 $t->{pre}=" ``";
289 0 $t->{post}="''";
290 } else {
291 0 $t->{pre}=" «";
292 0 $t->{post}="»";
293 };
294 } else {
295 0 ▶ if ($nested) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nested) { } 0 0 0
296 0 $t->{pre}=" `";
297 0 $t->{post}="'";
298 } else {
299 0 $t->{pre}=" ``";
300 0 $t->{post}="''";
301 };
302 };
303 0 return 1;
304 }
305  
306 0 ▶sub langofnode {
Subroutine langofnode: not called CC=1 SCAR=6.9
Pod undocumented
307 0 my $self = shift;
308 0 return $self->findvalue('(ancestor::*/@lang)[position()=last()]');
309 }
310  
311 0 ▶sub tc_varlisentry {
Subroutine tc_varlisentry: not called CC=1 SCAR=6.9
Pod undocumented
312 0 my ($self,$t)=@_;
313 my $header= join ', ',
314 0 map { apply_templates_under( $_ ) }
315 $self->findnodes("term");
316  
317 0 $t->{pre}='\item['.$header.']\\ \\\\'."\n";
318 0 $t->{post}= apply_templates_under("listitem", $self );
319  
320 0 return -1;
321 }
322  
323 0 ▶sub tc_variablelist {
Subroutine tc_variablelist: not called CC=1 SCAR=6.9
Pod undocumented
324 0 my ($self,$t)=@_;
325 0 $t->{pre}= listtitle($self) . $t->{pre};
326 0 return $_doNotProcessTitles;
327 }
328  
329 0 ▶sub listtitle {
Subroutine listtitle: not called CC=1 SCAR=6.9
Pod documented
330 0 my $title = apply_templates_under( 'title', $_[0] );
331  
332 0 return "\\paragraph*{$title}\n" x !!$title;
333 }
334  
335 0 ▶sub tc_screen {
Subroutine tc_screen: not called CC=1 SCAR=2.2
Pod undocumented
336 1 ▶ no warnings qw/ uninitialized /;
Subroutine BEGIN: called CC=1 SCAR=0.0
337 0 my ($self,$t)=@_;
338 0 my $ret= verbatimcode($self,$t,1);
339  
340 0 $t->{pre}="\\par\\noindent\n".$t->{pre};
341 0 $t->{post} .= "\n"; # *sigh*..
342  
343 0 return $ret;
344 }
345  
346 0 ▶sub tc_emphasis {
Subroutine tc_emphasis: not called CC=3 SCAR=24.8
Pod undocumented
347 0 my ($self, $t)=@_;
348 0 my $mode= $self->findvalue('@role');
349  
350 0 ▶ if ($mode && ($mode =~ m/strong|bold/i)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode and $mode =~ /strong|bold/i) 0 0 0
Condition0%0/3
$mode and $mode =~ /strong|bold/i
!ll&&!rl&&r
000
MC/DC0%0/2
$mode and $mode =~ /strong|bold/i
$mode $mode =~ /strong|bold/i
Truth table0%0/3
A and B
A= $modeB= $mode =~ /strong|bold/i
ABresult
0X0
100
111
351 0 $t->{pre}='\textbf{';
352 0 $t->{post}='}';
353 }
354  
355 0 return 1;
356 };
357  
358 # Renders text "verbatim", not as a LaTeX verbatim environment (which
359 # would badly get in the way of re-entrance w.r.t. sub-elements of
360 # verbatim-style Docbook elements), but by emitting appropriate
361 # spacing and newlines so as to respect source whitespace. If $trim is
362 # true, trims leading and trailing whitespace. $typesetbegin and
363 # $typesetend indicate which TeX markup should go at the beginning and
364 # the end of each piece of verbatim text. A line-numbering decoration
365 # is automatically added for portions of verbatim stuff inside
366 # <programlistingco> or <screenco>.
367 0 ▶sub verbatimcode {
Subroutine verbatimcode: not called CC=8 SCAR=42.8
Pod undocumented
368 0 my ($self, $t, $trim, $typesetbegin, $typesetend)=@_;
369  
370 0 ▶ $typesetbegin ||= '\texttt{';
Condition0%0/2
$typesetbegin ||= "\\texttt{"
l!l
00
MC/DC0%0/1
$typesetbegin ||= "\\texttt{"
$typesetbegin
Truth table0%0/2
A
A= $typesetbegin
Aresult
11
00
371 0 ▶ $typesetend ||= '}';
Condition0%0/2
$typesetend ||= "}"
l!l
00
MC/DC0%0/1
$typesetend ||= "}"
$typesetend
Truth table0%0/2
A
A= $typesetend
Aresult
11
00
372 0 my ($linebegin, $lineend) = ("\\hspace*{0pt}", "\\break\n");
373 # Number lines inside callout environments.
374 0 ▶ if ( $self->findvalue("name(..)") =~ m/^(programlisting|screen)co$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->findvalue("name(..)") =~ /^(programlisting|screen)co$/) 0 0 0
375 0 $linebegin = "\\markLineLeft{}".$linebegin;
376 }
377  
378 0 foreach my $subnode ( $self->findnodes('node()')) {
379 0 ▶ if ( $processor->is_text_node($subnode)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($XML::XPathScript::Stylesheet::DocBook2LaTeX::processor->is_text_node($subnode)) { } 0 0 0
elsif (is_element_node($subnode)) { } 0 0 0
380 0 my $text=utf8totex($subnode,
381 {
382 ord("\n")=>"$lineend$linebegin",
383 ord(" ")=>"\\ ",
384 ord("\t")=>"\\ "x8,
385 ord('@')=>'@',
386 # Allowing free-style line breaks like
387 # below is more questionable.
388 ord('/')=>'/\allowbreak{}',
389 ord('&')=>'\allowbreak{}\&',
390 ord('=')=>'=\allowbreak{}',
391 });
392  
393 $t->{post}=$typesetbegin.$linebegin.$text.$lineend.$typesetend
394 0 . $t->{post};
395 } elsif (is_element_node($subnode)) {
396 0 $t->{post}=apply_templates($subnode).$t->{post}; # Up to child
397 # elements to take precautions for respecting verbatim
398 # style, if appropriate.
399 };
400 };
401 0 ▶ $t->{post} =~ s/^(\\ |\n)*(.*?)(\\ |\n)*$/$2/gs if $trim;
Branch: 1 branch
BranchTrueFalseTotal
if $trim 0 0 0
402  
403 0 return -1;
404 };
405  
406 1 ▶sub RE_of_uniconvs {
Subroutine RE_of_uniconvs: called CC=1 SCAR=0.0
Pod undocumented
407 1 ▶ no warnings qw/ digit /;
Subroutine BEGIN: called CC=1 SCAR=0.0
408 1 my ($uni)=@_;
409 1 my @latin1variants=grep {$_ < 0xFF} (keys %$uni);
410 my $RE='[^\x9\xA\x20-\xFF]|'.
411 1 join("|",map {sprintf('\x%x',$_)} @latin1variants);
412 1 return qr"$RE";
413 }
414  
415 # Converts a Unicode string into a piece of text that means something
416 # to TeX: recodes some special characters in Unicode, quotes TeX's special
417 # characters, suppresses bogus paragraph breaks (unless $significantspace
418 # is set).
419  
420 1 { my %uniwarned;
421 0 ▶sub utf8totex {
Subroutine utf8totex: not called CC=7 SCAR=35.7
Pod documented
422 0 my ($uni, $significantspace)=@_;
423  
424 0 $uni = $processor->xpath_to_string($uni);
425  
426 0 my ($escapeRE,$uniref);
427 0 ▶ if ("HASH" eq ref($significantspace)) {
Branch: 1 branch
BranchTrueFalseTotal
if ('HASH' eq ref $significantspace) { } 0 0 0
428 0 $uniref={%uniconvs,%$significantspace};
429 0 $escapeRE=RE_of_uniconvs($uniref);
430 } else {
431 0 $escapeRE=$noninvarchar;
432 0 $uniref=\%uniconvs;
433 };
434 0 do {
435 1 ▶ use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
436  
437 1 ▶ no warnings qw/ digit /;
Subroutine BEGIN: called CC=1 SCAR=0.0
438 0 $uni =~ s/($escapeRE)/
439 0 my $c=ord($1);
440 0 ▶ if (exists $$uniref{$c}) { "<$c>"; } else {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $uniref->{$c}) { } 0 0 0
441 0 ▶ unless ($uniwarned{$c}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($uniwarned{$c}) 0 0 0
442 1 ▶ no utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
443 0 ▶ if (eval {require Unicode::CharName; 1; }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require Unicode::CharName; 1 } }) { } 0 0 0
444 0 warn sprintf("Unknown Unicode character (code 0x%x) : %s\n",
445 $c,Unicode::CharName::uname($c));
446 } else {
447 0 warn sprintf("Unknown Unicode character (code $c)\n");
448 };
449 0 ▶ warn "Modify me! ".
Branch: 1 branch
BranchTrueFalseTotal
unless %uniwarned 0 0 0
450 "(array \%uniconvs at the top of docbook2latex.xps)\n"
451 if (! %uniwarned);
452  
453 0 $uniwarned{$c}++;
454 };
455 0 "<?>";
456 }; /ge; # / emacs seems to have trouble with this one
457  
458 }; # End "use utf8"
459  
460 0 my $tex=utf8tolatin1($uni);
461  
462 # Insignificance of spaces: keep source indentation, remove
463 # unwanted paragraph breaks.
464  
465 0 ▶ unless ($significantspace) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($significantspace) 0 0 0
466 0 $tex =~ s/\s*\n/\n/gs;
467 0 $tex =~ s/^\n/ /;
468 };
469  
470 0 $tex =~ s/<\?>/$uniunknown/ge;
471 0 $tex =~ s/<([0-9]*)>/$$uniref{$1}/ge;
472  
473 # Will the XML deities ever forgive me for this one ? :-)
474 0 $tex =~ s/\bTeX\b/\\TeX{}/g;
475 0 $tex =~ s/\bLaTeX\b/\\LaTeX{}/g;
476  
477 0 return $tex;
478 }
479  
480 } # End of scope for %uniwarned
481  
482 1 ▶sub tc_para {
Subroutine tc_para: not called CC=2 SCAR=15.1
Pod undocumented
483 0 my ($self,$t)=@_;
484  
485 # We put a paragraph break only if there is a following element
486 # (so as not to break e.g. itemizations)
487 0 my ($brother)= $self->findnodes('following-sibling::*[1]');
488 0 ▶ $t->{post}=($brother ? "\n\n": undef );
Branch: 1 branch
BranchTrueFalseTotal
$brother ? : 0 0 0
489 0 return 1;
490 };
491  
492 0 ▶sub tc_section {
Subroutine tc_section: not called CC=8 SCAR=42.8
Pod undocumented
493 0 my ($n, $t ) = @_;
494  
495 # TODO will break for anything not directly mapped to LaTeX
496 # sections
497  
498 0 my $name = $n->getName;
499  
500 0 ▶ if( $name eq 'section' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "section") 0 0 0
501 0 my $parent = $n->parentNode->getName;
502 0 ▶ $name = 'sub'.$parent if $parent =~ /section/;
Branch: 1 branch
BranchTrueFalseTotal
if $parent =~ /section/ 0 0 0
503 }
504  
505 0 my $title = apply_templates_under('title',$n);
506 0 my( $abbrev_node ) = $n->findnodes('titleabbrev');
507 0 my $titleabbrev;
508 0 ▶ if ( $abbrev_node ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($abbrev_node) 0 0 0
509 0 $titleabbrev = apply_templates_under( $abbrev_node );
510 }
511 0 ▶ $titleabbrev ||= $title ;
Condition0%0/3
$titleabbrev ||= $title
l!l&&r!l&&!r
000
MC/DC0%0/2
$titleabbrev ||= $title
$titleabbrev $title
Truth table0%0/3
A ||= B
A= $titleabbrevB= $title
ABresult
1X1
011
000
512  
513 0 ▶ if ( $numbered_sections ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($XML::XPathScript::Stylesheet::DocBook2LaTeX::numbered_sections) { } 0 0 0
514 0 $t->{pre}="\n\n".sprintf '\%s[%s]{%s}',$name ,$titleabbrev, $title ;
515 }
516 else {
517 0 $t->{pre} = "\n\n".sprintf '\%s*{%s}',$name, $title ;
518 0 $t->{pre} .= "\\addcontentsline{toc}{$name}{$titleabbrev}\n";
519 }
520 0 $t->{pre}.=thelabel($n)."\n\n";
521  
522 0 ▶ if( $name eq 'chapter' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($name eq 'chapter') { } 0 0 0
elsif ($name eq 'section') { } 0 0 0
523 0 $t->{pre} .= "\n\\markboth{$titleabbrev}{}\n";
524 }
525 elsif( $name eq 'section' ) {
526 0 $t->{pre} .= "\n\\markright{$titleabbrev}\n";
527 }
528  
529 0 return $_doNotProcessTitles;
530 };
531  
532 0 ▶sub thelabel {
Subroutine thelabel: not called CC=3 SCAR=18.1
Pod documented
533 0 ▶ return unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 0 0
534  
535 1 ▶ no warnings qw/ uninitialized /;
Subroutine BEGIN: called CC=1 SCAR=0.0
536  
537 0 my $label = id2label( $_[0] );
538  
539 0 ▶ return $label ? "\\label{$label}\n" : q{} ;
Branch: 1 branch
BranchTrueFalseTotal
$label ? : 0 0 0
540 }
541  
542 # Handle UTF-8 braindamage and prevent utf8 tainting from propagating
543 # to the whole document (TeX dislikes UTF-8). See documentation at
544 # the end.
545 0 ▶sub utf8tolatin1 {
Subroutine utf8tolatin1: not called CC=1 SCAR=6.9
Pod documented
546 0 my $orig=shift;
547  
548 0 $orig = $processor->xpath_to_string($orig);
549  
550 0 return pack("C*",grep {$_<255} (unpack("U*",$orig)));
551 }
552  
553 0 ▶sub id2label {
Subroutine id2label: not called CC=3 SCAR=24.8
Pod documented
554 0 my ($node,$attrname)=@_;
555 0 ▶ $attrname ||= "id";
Condition0%0/2
$attrname ||= "id"
l!l
00
MC/DC0%0/1
$attrname ||= "id"
$attrname
Truth table0%0/2
A
A= $attrname
Aresult
11
00
556 0 my ($attr)= $node->findnodes( '@'.$attrname );
557 0 ▶ return undef if (! $attr);
Branch: 1 branch
BranchTrueFalseTotal
unless $attr 0 0 0
558 0 my $text=utf8tolatin1($attr);
559 0 $text =~ s/[^a-zA-Z0-9:-]/-/g;
560 0 return $text;
561 }
562  
563 0 ▶sub section_nesting_depth {
Subroutine section_nesting_depth: not called CC=4 SCAR=30.0
Pod documented
564 0 my ($self)=@_;
565 # Computing of the nesting depth, which equals the number of
566 # ancestors that are either sections or appendices.
567 0 my $p=0;
568 0 ▶ for(my $ancetre=$self;
Branch: 1 branch
BranchTrueFalseTotal
if (($ancetre) = findnodes("..", $ancetre)) 0 0 0
569 ($ancetre)=findnodes("..",$ancetre);
570 1) {
571 0 my $nom=findvalue("name()",$ancetre);
572 0 ▶ last unless grep {$nom eq $_} (@secttypes,"appendix", "glossary",
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$nom eq $_;} @secttypes, "appendix", "glossary", "bibliography", "bibliodiv" 0 0 0
573 "bibliography", "bibliodiv");
574 0 $p++;
575 };
576  
577 0 ▶ die_at($self,"Nesting too deep") if ($p > scalar(@sectionnames));
Branch: 1 branch
BranchTrueFalseTotal
if $p > scalar @XML::XPathScript::Stylesheet::DocBook2LaTeX::sectionnames 0 0 0
578  
579 0 return $p;
580 }
581  
582 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
583  
584 0 ▶sub new {
Subroutine new: not called CC=1 SCAR=6.9
Pod undocumented
585 0 my $class = shift;
586 0 my $self = XML::XPathScript::Template->new();
587 0 bless $self, $class;
588 0 return $self;
589 }
590  
591 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
592  
593 0 ▶sub tc_catchall {
Subroutine tc_catchall: not called CC=1 SCAR=6.9
Pod undocumented
594 0 my $node = shift;
595  
596 0 my $name = $node->getName;
597  
598 0 die "tag $name not recognized\n";
599 }
600  
601 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
602  
603 0 ▶sub tc_wholedoc {
Subroutine tc_wholedoc: not called CC=20 SCAR=59.3
Pod undocumented
604 0 my ($self,$t)=@_;
605  
606 0 my $documentclass = $documentclass;
607  
608 0 my %class = (
609 book => 'book',
610 article => 'article',
611 );
612  
613 0 ▶ unless( $documentclass ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($documentclass) 0 0 0
614 0 my $name = $self->getName;
615 0 ▶ $documentclass = $class{ $name } || 'report';
Condition0%0/2
$class{$name} || 'report'
l!l
00
MC/DC0%0/1
$class{$name} || 'report'
$class{$name}
Truth table0%0/2
A
A= $class{$name}
Aresult
11
00
616 }
617  
618 0 $t->{pre}= '\documentclass['
619 . join( ',', @documentclass_args )
620 . "]{$documentclass}\n";
621  
622 0 my @packages=@packages; #Huuh.
623  
624 0 ▶ push @packages, qw/ longtable multirow / if $fancytables;
Branch: 1 branch
BranchTrueFalseTotal
if $XML::XPathScript::Stylesheet::DocBook2LaTeX::fancytables 0 0 0
625  
626 0 foreach my $p (0..$#packages) {
627 0 ▶ if (ref($packages[$p]) eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $packages[$p] eq 'ARRAY') { } 0 0 0
elsif (not ref $packages[$p]) { } 0 0 0
628 0 my ($package,@options)=@{$packages[$p]};
629 0 $t->{pre}.="\\usepackage[".join(",",@options)."]{$package}\n";
630 } elsif (! ref($packages[$p])) {
631 0 my $package=$packages[$p];
632 0 $t->{pre}.="\\usepackage{$package}\n";
633 } else {
634 0 warn sprintf("No clue for entry number %p in \@packages\n");
635 };
636 };
637  
638 0 $t->{pre}.=<<"PREAMBLE";
639 $TeXkludges
640  
641 $TeXpreamble
642  
643 PREAMBLE
644  
645 0 my $titlenode;
646 0 foreach my $pos (all_paths_for_header_element("title")) {
647 0 ▶ last if (($titlenode)= $self->findnodes($pos));
Branch: 1 branch
BranchTrueFalseTotal
if ($titlenode) = $self->findnodes($pos) 0 0 0
648 };
649 0 ▶ my $title = $title ? $title
Branch: 2 branches
BranchTrueFalseTotal
$XML::XPathScript::Stylesheet::DocBook2LaTeX::title ? : 0 0 0
$titlenode ? : 0 0 0
650 : $titlenode ? apply_templates_under($titlenode)
651 : undef
652 ;
653  
654 0 my @subtitles=map { apply_templates_under($_) }
655 0 (map { $self->findnodes($_)}
656 (qw(articleinfo/subtitle artheader/subtitle bookinfo/subtitle subtitle)));
657  
658 0 my $author = render_authors('stack', $self);
659  
660 0 ▶ if (! $maketitle) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($XML::XPathScript::Stylesheet::DocBook2LaTeX::maketitle) 0 0 0
661 0 my $typeset_title=$title;
662 $typeset_title.=join("",map
663 0 {sprintf(<<'SUBTITLE',$_)} @subtitles);
664 \\
665 \vspace{1ex}
666 {\LARGE{}%s}
667 SUBTITLE
668  
669 0 ▶ if ($typeset_title) { $t->{pre}.=sprintf(<<'TITLE',$typeset_title);}
Branch: 1 branch
BranchTrueFalseTotal
if ($typeset_title) 0 0 0
670 \title{\textbf{\textsc{\Huge{}%s}}}
671 TITLE
672  
673 1 ▶ no warnings qw/ uninitialized /;
Subroutine BEGIN: called CC=1 SCAR=0.0
674 0 $t->{pre}.="\n\\author{$author}\n";
675 };
676  
677 0 $t->{pre}.="\n\n\\begin{document}\n\n";
678  
679 0 ▶ $t->{pre}.=$TeXbegindocument if $TeXbegindocument;
Branch: 1 branch
BranchTrueFalseTotal
if $XML::XPathScript::Stylesheet::DocBook2LaTeX::TeXbegindocument 0 0 0
680 0 ▶ $t->{pre}.= ( $firstpage? $firstpage : $maketitle ? (&$maketitle($title,\@subtitles,$author)) :
Branch: 3 branches
BranchTrueFalseTotal
$XML::XPathScript::Stylesheet::DocBook2LaTeX::firstpage ? : 0 0 0
$XML::XPathScript::Stylesheet::DocBook2LaTeX::maketitle ? : 0 0 0
$title ? : 0 0 0
681 ($title ? "\\maketitle\n" : "") );
682  
683 0 foreach my $subnode (all_paths_for_header_element("abstract"),
684 all_paths_for_header_element("legalnotice"),
685 "epigraph") {
686 0 ▶ if (my ($node)= $self->findnodes($subnode)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($node) = $self->findnodes($subnode)) 0 0 0
687 0 $t->{pre}.= $processor->apply_templates($node);
688 }
689 }
690  
691 0 $t->{pre}.=join("",map { "\\$_".'{}'."\n" } @tablesatbeginning);
692  
693 0 ▶ $t->{pre}.="\\clearpage\n" if(scalar(@tablesatbeginning));
Branch: 1 branch
BranchTrueFalseTotal
if scalar @XML::XPathScript::Stylesheet::DocBook2LaTeX::tablesatbeginning 0 0 0
694  
695 0 $t->{post}=join("",map { "\\$_".'{}'."\n" } @tablesatend);
696 0 $t->{post}.='\end{document}';
697  
698 0 return '*[name()!="articleinfo" and name()!="artheader" '.
699 ' and name()!="bookinfo"'.
700 ' and name()!="epigraph" and name()!="title" and name() != "subtitle"]';
701 }
702  
703 # The DTD has variants, this is annoying...
704 0 ▶sub all_paths_for_header_element {
Subroutine all_paths_for_header_element: not called CC=1 SCAR=6.9
Pod undocumented
705 0 return map { ( "articleinfo/$_", "bookinfo/$_",
706 "artheader/$_", $_ ) } @_;
707 }
708  
709 # A convenience function to pass through forbidden or unhandled tags:
710 0 ▶sub apply_templates_under {
Subroutine apply_templates_under: not called CC=9 SCAR=45.0
Pod documented
711 0 my ($xpath, $node);
712  
713 0 ▶ if (scalar(@_) == 0 || scalar(@_) > 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_ == 0 or scalar @_ > 2) 0 0 0
Condition0%0/3
scalar @_ == 0 or scalar @_ > 2
l!l&&r!l&&!r
000
MC/DC0%0/2
scalar @_ == 0 or scalar @_ > 2
scalar @_ == 0 scalar @_ > 2
Truth table0%0/3
A or B
A= scalar @_ == 0B= scalar @_ > 2
ABresult
1X1
011
000
714 0 carp sprintf("apply_templates_under() called with %d args",scalar(@_));
715 0 return "";
716 };
717  
718 0 ▶ if (scalar(@_) == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_ == 2) { } 0 0 0
719 0 ($xpath, $node)=@_;
720 } else {
721 0 ▶ if (ref $_[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0]) { } 0 0 0
722 0 ($node)=@_;
723 } else {
724 0 ($xpath)=@_;
725 };
726 }
727  
728 0 ▶ $xpath = ($xpath ? "$xpath/node()" : "node()");
Branch: 1 branch
BranchTrueFalseTotal
$xpath ? : 0 0 0
729  
730 0 ▶ unless ( $processor->is_element_node($node) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($XML::XPathScript::Stylesheet::DocBook2LaTeX::processor->is_element_node($node)) 0 0 0
731 0 confess("Wrong call to apply_templates_under");
732 };
733  
734 0 my @subnodes= $node->findnodes($xpath);
735 @subnodes=grep {
736 0 my $n=$_;
737 0 ▶ ($processor->is_element_node($n) || $processor->is_text_node($n));
Condition0%0/3
$XML::XPathScript::Stylesheet::DocBook2LaTeX::processor->is_element_node($n) || $XML::XPathScript::Stylesheet::DocBook2LaTeX::processor->is_text_node($n)
l!l&&r!l&&!r
000
MC/DC0%0/2
$XML::XPathScript::Stylesheet::DocBook2LaTeX::processor->is_element_node($n) || $XML::XPathScript::Stylesheet::DocBook2LaTeX::processor->is_text_node($n)
$XML::XPathScript::Stylesheet::DocBook2LaTeX::processor->is_element_node($n) $XML::XPathScript::Stylesheet::DocBook2LaTeX::processor->is_text_node($n)
Truth table0%0/3
A || B
A= $XML::XPathScript::Stylesheet::DocBook2LaTeX::processor->is_element_node($n)B= $XML::XPathScript::Stylesheet::DocBook2LaTeX::processor->is_text_node($n)
ABresult
1X1
011
000
738 } (@subnodes);
739  
740 0 ▶ return "" unless @subnodes;
Branch: 1 branch
BranchTrueFalseTotal
unless @subnodes 0 0 0
741 0 return $processor->apply_templates(@subnodes);
742 }
743  
744 0 ▶sub render_authors {
Subroutine render_authors: not called CC=11 SCAR=48.8
Pod documented
745 0 my ($rendermode, @authors)=@_;
746  
747 0 ▶ if (ref($authors[0])) { # Not quite the same meaning
Branch: 1 branch
BranchTrueFalseTotal
if (ref $authors[0]) 0 0 0
748 0 my $self = $authors[0];
749 0 my $nodename= $self->findvalue('name()');
750  
751 0 ▶ if ($nodename =~ m/^(?:artheader|(article|book)(info)?)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nodename =~ /^(?:artheader|(article|book)(info)?)/) 0 0 0
752 0 my @paths = qw(author corpauthor
753 authorgroup/author authorgroup/corpauthor);
754 0 ▶ if (($nodename ne "artheader") && (! $2)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nodename ne "artheader" and not $2) 0 0 0
Condition0%0/3
$nodename ne "artheader" and not $2
!ll&&!rl&&r
000
MC/DC0%0/2
$nodename ne "artheader" and not $2
$nodename ne "artheader" not $2
Truth table0%0/3
A and not(B)
A= $nodename ne "artheader"B= not $2
ABresult
0X0
100
111
755 push @paths,
756 ($1 eq "article" ?
757 0 (map { ("articleinfo/$_", "artheader/$_") } @paths) :
758 0 ▶ (map { "bookinfo/$_" } @paths));
Branch: 1 branch
BranchTrueFalseTotal
$1 eq 'article' ? : 0 0 0
759 }
760  
761 0 @authors=map { $processor->apply_templates($_) }
762 0 (map { $self->findnodes($_) } @paths);
763 }
764 }
765  
766 0 ▶ return unless @authors;
Branch: 1 branch
BranchTrueFalseTotal
unless @authors 0 0 0
767  
768 0 ▶ return $authors[0] if @authors == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @authors == 1 0 0 0
769  
770 0 ▶ if ($rendermode eq "stack") {
Branch: 1 branch
BranchTrueFalseTotal
if ($rendermode eq "stack") 0 0 0
771 0 my $a = "\\begin{tabular}{rl}\n";
772 0 $a .= join '', map "by & $_ \\\\\n", shift @authors;
773 0 $a .= $_ for map "& $_ \\\\\n", @authors;
774 0 $a.= '\end{tabular}';
775  
776 0 return $a;
777 }
778
779 0 ▶ if ($rendermode eq "ampersand") {
Branch: 1 branch
BranchTrueFalseTotal
if ($rendermode eq "ampersand") 0 0 0
780 0 my $lastauthor=pop @authors;
781 0 return join(", ",@authors)." \\& $lastauthor";
782 }
783
784 0 carp "Unknown rendermode $rendermode";
785 0 return join ", ",@authors ;
786 }
787  
788  
789  
790 0 ▶$template->{'orderedlist'}->{testcode}=sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
791 0 my ($self,$t)=@_;
792  
793 0 $t->{pre}=listtitle($self);
794  
795 0 $t->{'pre'}.="\\begin{enumerate}";
796 0 $t->{'post'}="\\end{enumerate}\n";
797  
798 # Handling of the "continuation=Continues" attribute in a context-
799 # dependent fashion (as opposed to crude hacks with global variables).
800 # Algorithm: add the number of sons of all lists that preceed and
801 # also have "continuation=Continues" set, and then another list
802 # that doesn't have it.
803  
804 0 my $cont= $self->findvalue('@continuation');
805 0 ▶ if ($cont && ($cont =~ m/continues/i)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cont and $cont =~ /continues/i) 0 0 0
Condition0%0/3
$cont and $cont =~ /continues/i
!ll&&!rl&&r
000
MC/DC0%0/2
$cont and $cont =~ /continues/i
$cont $cont =~ /continues/i
Truth table0%0/3
A and B
A= $contB= $cont =~ /continues/i
ABresult
0X0
100
111
806 0 my $num=0;
807  
808 0 my @pals=reorder_backaxis("backward",
809 findnodes('preceding::orderedlist',$self));
810  
811 0 foreach my $pal (@pals) {
812 0 $num += findvalue("count(*)",$pal);
813 0 my $cont=findvalue('@continuation',$pal);
814 0 ▶ last if ($cont && ($cont !~ m/continues/i));
Branch: 1 branch
BranchTrueFalseTotal
if $cont and not $cont =~ /continues/i 0 0 0
Condition0%0/3
$cont and not $cont =~ /continues/i
!ll&&!rl&&r
000
MC/DC0%0/2
$cont and not $cont =~ /continues/i
$cont not $cont =~ /continues/i
Truth table0%0/3
A and not(B)
A= $contB= not $cont =~ /continues/i
ABresult
0X0
100
111
815 };
816
817 0 $t->{pre}.="\n".'\makeatletter\setcounter{\@enumctr}{'.
818 "$num}\\makeatother";
819 };
820 0 return '*[name()!="title"]';
821 1 };
822  
823 0 ▶$template->{'ulink'}->{testcode}=sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
824 0 my ($self, $t)=@_;
825  
826 0 my $url="\\texttt{".utf8totex( $self->findvalue('@url'),
827 {
828 ord(" ")=>"\\ ",
829 ord('@')=>'@',
830 })."}";
831  
832 0 ▶ if ( $self->findnodes("node()") ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->findnodes('node()')) { } 0 0 0
833 0 $t->{post}=render_footnote($self, $url);
834 0 $t->{pre}="";
835 0 return 1;
836 } else {
837 0 $t->{pre}=$url;
838 0 $t->{post}="";
839 0 return -1;
840 }
841 1 };
842  
843  
844 1 our $_render_footnote;
845  
846 0 ▶sub render_footnote {
Subroutine render_footnote: not called CC=2 SCAR=17.9
Pod documented
847 0 ▶ $_render_footnote ?
Branch: 1 branch
BranchTrueFalseTotal
$XML::XPathScript::Stylesheet::DocBook2LaTeX::_render_footnote ? : 0 0 0
848 goto &$_render_footnote :
849 goto &_default_render_footnote;
850 }
851  
852 0 ▶sub _default_render_footnote {
Subroutine _default_render_footnote: not called CC=2 SCAR=17.9
853 0 my ($self, $text)=@_;
854  
855 0 ▶ if (! footnotes_allowed($self)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not footnotes_allowed($self)) { } 0 0 0
856 0 return ("\\footnotemark{}");
857 } else {
858 0 return ("\\footnote{".thelabel($self)."$text}");
859 }
860 }
861  
862 0 ▶sub collect_trapped_footnotes {
Subroutine collect_trapped_footnotes: not called CC=3 SCAR=24.8
Pod documented
863 0 my ($self)=@_;
864  
865 # my $selfpath=get_xpath_of_node($self); warn "collect_trapped_footnotes($selfpath)";
866  
867 0 ▶ return "" if ($_render_footnote);
Branch: 1 branch
BranchTrueFalseTotal
if $XML::XPathScript::Stylesheet::DocBook2LaTeX::_render_footnote 0 0 0
868 0 ▶ return "" if (! footnotes_allowed($self));
Branch: 1 branch
BranchTrueFalseTotal
unless footnotes_allowed($self) 0 0 0
869  
870 0 my ($text, @collected);
871  
872 0 do {
873 0 ▶ local $_render_footnote=sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
874 0 my ($self, $text)=@_;
875 0 my $defaultresult=_default_render_footnote(@_);
876  
877 0 ▶ if ($defaultresult eq "\\footnotemark{}") {
Branch: 1 branch
BranchTrueFalseTotal
if ($defaultresult eq '\\footnotemark{}') { } 0 0 0
878 0 push(@collected, [$self, $text]);
879 0 return "\\footnotemark{$#collected}";
880 } else {
881 0 return $defaultresult;
882 }
883 0 };
884 0 $text = apply_templates($self);
885 };
886  
887 0 return _recurse_layout_footnotetexts($text, @collected);
888 }
889  
890 0 ▶sub _recurse_layout_footnotetexts {
Subroutine _recurse_layout_footnotetexts: not called CC=4 SCAR=30.0
891 0 my ($raw_footnotetext, @context)=@_;
892  
893 #warn "_recurse_layout_footnotetexts($raw_footnotetext,...)";
894 0 my @occurences=($raw_footnotetext =~ m/\\footnotemark\{(\d+)\}/g);
895  
896 my @footnotetexts=map {
897 0 my $node;
898 0 ($node, $_)=@{$context[$_]};
899 0 my $substuff=_recurse_layout_footnotetexts($_, @context);
900 0 s/\\footnotemark\{(\d+)\}/\\footnotemark{}/g;
901 0 "\\footnotetext{".thelabel($node)."$_}\n$substuff";
902 } @occurences;
903  
904 0 ▶ die "assertion failed" unless (@footnotetexts == @occurences);
Branch: 1 branch
BranchTrueFalseTotal
unless @footnotetexts == @occurences 0 0 0
905  
906 # OK this would be enough assuming that \footnotemark and
907 # \footnotetext each run on their own counter. Unfortunately
908 # they don't: LaTeX dumbly assumes that \footnotetext is only
909 # ever used when there is exactly one outstanding
910 # \footnotemark to be terminated. Let's fiddle with the counter
911 # to compensate.
912  
913 0 ▶ if (@footnotetexts == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (@footnotetexts == 0) { } 0 0 0
elsif (@footnotetexts == 1) { } 0 0 0
914 0 return "";
915 } elsif (@footnotetexts == 1) {
916 0 return $footnotetexts[0];
917 } else {
918 0 return "\\addtocounter{footnote}{-".($#footnotetexts)."}\n".
919 join("\\addtocounter{footnote}{1}\n", @footnotetexts);
920 }
921  
922 }
923  
924 1 our @footnote_blockers;
925 1 push(@footnote_blockers, "footnote");
926 0 ▶$template->{'footnote'}->{testcode}=sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
927 0 my ($self,$t)=@_;
928  
929 0 my $retval;
930 0 $t->{pre}=render_footnote($self, apply_templates_under($self));
931 0 $t->{post}=collect_trapped_footnotes($self);
932 0 return -1;
933 1 };
934  
935 1 our $is_footnote_blocker;
936  
937 # Tells whether footnotes are allowed at $self, if $virtroot were to
938 # be the root of the document. $self itself is not taken into account
939 # even if it is a footnote blocker.
940 0 ▶sub footnotes_allowed {
Subroutine footnotes_allowed: not called CC=3 SCAR=24.8
Pod undocumented
941 0 my ($self)=@_;
942 #warn "footnotes_allowed",get_xpath_of_node($self);
943  
944 0 my ($parent)= $self->findnodes('..');
945 0 ▶ if (!defined $parent) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $parent) 0 0 0
946 #warn "footnotes_allowed hit root";
947 0 return 1
948 }
949 0 ▶ if (&$is_footnote_blocker($parent)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&$XML::XPathScript::Stylesheet::DocBook2LaTeX::is_footnote_blocker($parent)) 0 0 0
950 #warn sprintf("&\$is_footnote_blocker(%s) is true", get_xpath_of_node($parent));
951 0 return 0
952 }
953 0 return footnotes_allowed($parent);
954 }
955  
956 0 ▶$is_footnote_blocker=sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
957 0 my ($self)=@_;
958  
959 0 my $nodename= $self->findvalue('name()');
960 0 ▶ return undef if (! $nodename); # Root node
Branch: 1 branch
BranchTrueFalseTotal
unless $nodename 0 0 0
961 0 return grep {$_ eq $nodename} @footnote_blockers;
962 1 };
963 1 1;
964  
965 =pod
966  
967 =encoding UTF-8
968  
969 =head1 NAME
970  
971 XML::XPathScript::Stylesheet::DocBook2LaTeX - Transforms DocBook into LaTeX
972  
973 =head1 VERSION
974  
975 version 2.00
976  
977 =head1 SYNOPSIS
978  
979 use XML::XPathScript;
980 use XML::XPathScript::Stylesheet::DocBook2LaTeX;
981  
982 my $latex = $xps->transform(
983 $docbook => XML::XPathScript::Stylesheet::DocBook2LaTeX::stylesheet
984 );
985  
986 =head1 WARNING
987  
988 This module is still in a very beta-ish stage.
989 We heavily recommend to wait till we tell you to to use it.
990 But if you are in an adventurous mode, by all means, go ahead. :-)
991  
992 =begin devel
993  
994 =head1 NAME
995  
996 docbook2latex.xps - an XPathScript stylesheet for LaTeX.
997  
998 =head1 SYNOPSIS
999  
1000 xpathscript yourdoc.xml docbook2latex.xps > yourdoc.tex
1001  
1002 =head1 DESCRIPTION
1003  
1004 This is docbook2latex.xps version number $Revision: 32928 $, by IDEALX
1005 (http://www.idealx.org/docbook2latex/).
1006  
1007 Using Matt Sergeant's XPathScript framework (see L<SEE ALSO>), this stylesheet
1008 translates Docbook XML into LaTeX for beautiful typesetting of Docbook
1009 articles (reports, books and other kinds of whole documents defined by
1010 the DTD are not supported yet).
1011  
1012 Provided you have the Perl dependencies installed (XML::XPathScript,
1013 from CPAN, as well as all sub-dependencies of those), the command
1014 shown in the synopsis will turn any (DTD-conformant) C<mydoc.xml> into
1015 pure LaTeX (that is, using only packages included in the TeTeX
1016 distribution to compile). Every unknown Unicode character or XML tag
1017 present in the document will trigger appropriate warnings, but the
1018 stylesheet will recover nicely and still produce a valid LaTeX output.
1019  
1020 This stylesheet supports french and english typesetting, on a per-tag basis.
1021  
1022 Of course, I bet you won't be pleased with the aesthetics of the result,
1023 or maybe there are some tags (from the 400+ in Docbook) or characters (from
1024 the 30000+ in Unicode) that aren't typeset and that you absolutely want. So
1025 read on...
1026 =head1 USER DOCUMENTATION
1027  
1028 =head1 CUSTOMIZING AND ADDING FUNCTIONALITY
1029  
1030 You could just modify the stylesheet: there are plenty of comments,
1031 but grasping the big picture at once can be difficult. Fortunately,
1032 XPathScript allows for overload-oriented customization; the same
1033 philosophy is followed throughout this stylesheet, so that there are a
1034 number graft points (beside whole XML tags, as specified in the
1035 XPathScript documentation) where you can modify part of the stylesheet
1036 behaviour without interfering with the overall functionality. Working
1037 knowledge of XPathScript is assumed (see L<SEE ALSO>).
1038  
1039 =head2 An example
1040  
1041 Cut-and-paste the following text into test.xps, then run
1042 C<xpathscript mydoc.xml test.xps>:
1043  
1044 E<32>E<32><% our $inhibitOutput; $inhibitOutput++; %I<>>
1045  
1046 E<32>E<32><!--#I<>include file="docbook2latex.xps"-->
1047  
1048 E<32>E<32><% $inhibitOutput--; %I<>>
1049  
1050 <%
1051 # Change the style to add fancy headers and the word "draft" behind
1052 # every page
1053 push(@packages,"fancyhdr");
1054 push(@packages,[ "draftcopy" => "all", "english" ]);
1055  
1056 # override the varname tag to display as sans-serif
1057 delete $t->{varname}; $t->{varname}->{testcode}=sub {
1058 my ($self, $return)=@_;
1059 $return->{pre}='\textss{';
1060 $return->{post}='}';
1061 return 0;
1062 };
1063  
1064 # double the ruler on top of each table.
1065 our $typeset_tableframe;
1066 my $ORIG_typeset_tableframe=$typeset_tableframe;
1067 $typeset_tableframe=sub {
1068 return '\hline'.($ORIG_typeset_tableframe(@_));
1069 }
1070  
1071 E<32>E<32>%I<>>
1072  
1073 E<32>E<32><%= $inhibitOutput ? "" : apply_templates() %I<>>
1074 =head2 Modification points
1075  
1076 The modification points fall into 3 categories: configuration variables,
1077 overridable templates and overridable function references. The example
1078 above shows how to override all three.
1079  
1080 =over 4
1081  
1082 =item Environment variables
1083  
1084 There is no standard method yet for passing arguments to an
1085 XML::XPathScript stylesheet. Waiting for something better, the UNIX
1086 environment is used instead. At present, no environment variable is
1087 recognized and any customization must be done by a cascading
1088 stylesheet (but in order to get customization e.g. for outputting
1089 variadic documents, said stylesheet may need to read the environment).
1090  
1091 =item Configuration variables
1092  
1093 There are package-global variables that are read at runtime to
1094 customize the stylesheet's behaviour. Examples are C<$fancytables> (if
1095 true, use the C<longtable> package to typeset tables) and C<@packages>
1096 (the list of TeX packages to invoke in the preamble). The list of
1097 such configuration variables is shown in L</REFERENCE MANUAL>.
1098  
1099 =item Overridable templates
1100  
1101 As stated in the XPathScript documentation, the $t variable (which is
1102 in scope from every < % ... % > construct) holds a reference to a hash
1103 of XML element handlers keyed by element name, which can be replaced
1104 with your own (see C<<
1105 http://axkit.org/docs/xpathscript/guide.dkb?section=6 >>). The code in
1106 the templates is fully context-dependent, in that it only ever reads
1107 data from the XML document to reach a typesetting decision, and does
1108 not use any muddy global variables to pass sticky state information
1109 around (the only exception is that a function is allowed to cache its
1110 results). This means it is perfectly OK to replace only some of the
1111 element handlers with your own, without messing up with the way the
1112 others work. Beware though that some tags are not rendered as part of
1113 the C<apply_templates()> mechanism, but are treated in an ad-hoc way
1114 by the stylesheet - for example, <title> tags are always rendered in
1115 TeX as part of the parent <section>, <table>, <figure> or such.
1116  
1117 The rule of thumb for overriding templates is: B<a template for some
1118 tag is overridable if and only if it C<exist()s> in the C<$t> hash,
1119 and is not listed in the C<@abstracttags> variable> provided by the
1120 stylesheet as package-global for this purpose.
1121 =item Overridable function references
1122  
1123 In some particularly tedious places of the stylesheet (e.g. for
1124 tables), there is a function reference in a package-global variable
1125 that holds a function that will be called for typesetting
1126 something. For example, C<&$typeset_tablerow(something)> will be
1127 called to typeset a row in a table. The list of such function
1128 references and their prototypes and expected semantics is described in
1129 L</REFERENCE MANUAL>, so that you may code your own replacements for
1130 those in use in this stylesheet.
1131  
1132 =back
1133  
1134 =head2 Unicode guidelines
1135  
1136 By far the greatest pain when enhancing this stylesheet (and even
1137 before, when writing it...) is Unicode support. XML input through
1138 I<XML::Parser> always happens in Unicode, as per the XML standard;
1139 Perl stores the result in its new polymorphic strings (with UTF-8 as
1140 the in-memory representation) which exhibit the "contamination
1141 problem" (see L</XML::XPathScript::Toys::translate_node>). LaTeX barfs
1142 on Unicode input, of course. Therefore, there needs to be a kind of
1143 "unicode firewall" throughout the stylesheet(s) that correctly
1144 transcodes every kind of Unicode input into LaTeX (which for our
1145 purpose is a subset of Latin1 since we use the C<inputenc> package).
1146  
1147 =over 4
1148  
1149 =item *
1150  
1151 Text nodes explicitly computed by user code should be converted using
1152 extra utf8tolatin1() or utf8totex() calls (which see) :
1153  
1154 $t->{pre}.=findnodes("/article/articleinfo/title/text()"); # WRONG
1155  
1156 would produce a bogus C<XML::XPath::Node::Text=SCALAR(0xdeadbeef)>, while
1157  
1158 $t->{pre}.=findvalue("/article/articleinfo/title/text()"); # WRONG
1159  
1160 as suggested by the XPathScript documentation, would UTF8-taint the result.
1161  
1162 Use this instead:
1163  
1164 my ($node)=findnodes("/article/articleinfo/title/text()"); # WARNING,
1165 # scalar context would not work - see Quirks.
1166 $t->{pre}=utf8totex($node);
1167  
1168 or even simpler, use L</apply_templates_under> that was created for this
1169 very purpose:
1170  
1171 my $rendered=apply_templates_under("/article/articleinfo/title");
1172 =item *
1173  
1174 Element nodes should never be converted to text directly:
1175  
1176 $t->{pre}.=findnodes("/some/path",$self); # WRONG, as
1177 # would be any variation thereof with findvalue() or such
1178  
1179 Use something like L</apply_templates_under> instead to recurse into
1180 their substructure. The rationale is that outputting stringified
1181 element nodes only has meaning if the output is XML too, or tagless UTF-8
1182 at the very least, and has no meaning for TeX.
1183 =item *
1184  
1185 XPath values that are not nodes should be dealt with using the
1186 UTF8-to-something-else functions:
1187  
1188 $t->{pre}.=utf8totex(findvalue('@url',$self));
1189  
1190 my $filename=utf8tolatin1(findvalue('@fileref',$graphicnode));
1191  
1192 =item *
1193  
1194 If you don't copy the part of the document into the output but are
1195 merely testing something about it, then Unicode won't hurt you. For
1196 example, in
1197  
1198 $t->{pre}.="\\textbf{" if (findvalue("@role",$self) eq "strong");
1199  
1200 Here C<findvalue("@role",$self)> is UTF-8 but you won't ever have
1201 to bother since it does not make its way to the output stream. The
1202 test works as expected ("strong" is promoted to Unicode but this does
1203 not change its value), the Boolean test result is not tainted (it
1204 never is), and therefore the result, "\\textbf{" is Latin1 as it
1205 should.
1206 =back
1207  
1208 =head2 Quirks
1209  
1210 Bugs and oddities were spotted in various places of the Perl XML support
1211 software (XML::XPath version 1.12), and the following workarounds were used
1212 to circumvent them. You may find it useful to do likewise in
1213 your own extensions:
1214  
1215 =over 4
1216  
1217 =item *
1218  
1219 the clever object model in I<XML::XPath> with shadow objets geared at
1220 good garbage collection gets in the way for the I<matches()> function,
1221 which only works toward ancestors of the node (as of version 1.12);
1222  
1223 =item *
1224  
1225 findnodes() in scalar context returns an object which is I<not> a node,
1226 but an I<XML::XPath::NodeSet>. Be careful to always call it in list
1227 context if you are interested in nodes and not NodeSets; if you just
1228 want one node, say
1229  
1230 my ($attrnode)=findnodes('@url',$xrefnode);
1231 =item *
1232  
1233 apply_templates() with no arguments does what the spec does, which is
1234 exactly what you don't want (re-render the whole document through the
1235 stylesheet!). Use apply_templates_under instead:
1236  
1237 $t->{pre}.=apply_templates(findnodes("para",$node)); # WRONG if
1238 # findnodes() yields no results
1239  
1240 $t->{pre}.=apply_templates_under("para",$node); # OK
1241 =item *
1242  
1243 findnodes() performed on a backward axis (ex 'preceding::') in array
1244 context should return the value in reverse document order (according
1245 to the XPath spec and reasonable expectation), but doesn't in versions
1246 1.12 and 1.13. The manpage is not clear as to whether this is a bug or
1247 a feature. In order to accomodate both possible outcomes of this
1248 behaviour (stays the same or is reversed) in future versions of
1249 I<XML::XPath>, the I<reorder_backaxis()> function compensates this
1250 (see L</reorder_backaxis>).
1251  
1252 =back
1253  
1254 See also L</Unicode guidelines> which may, as a whole, be considered
1255 as a big quirk of its own, and also L<XML::XPathScript/Stylesheet
1256 Guidelines>.
1257  
1258 =head1 PROGRAMMING FAQ
1259  
1260 =over 4
1261  
1262 =item I<I get a strange error about an XPath query with pieces of LaTeX
1263 inside, which is nowhere to be found in my source...>
1264  
1265 This is because your {testcode} routine did not return a satisfactory
1266 value. Remember: you have to return -1 ("do not render the subtree of
1267 this node, I did it already, just output $t->{pre} and $t->{post} side
1268 by side"), 1 ("please render the subtree in full"), 0 ("render
1269 nothing at all please") or an XPath expression ("only render those
1270 subnodes that match this expression").
1271  
1272 Forgetting the C<return> altogether is a common mistake: in the
1273 following code, "\end{stuff}" would be the return value, thus causing
1274 the reported behaviour:
1275  
1276 $t->{sometag}->{testcode}=sub {
1277 my ($node,$t)=@_;
1278 $t->{pre}="\\begin{stuff}";
1279 $t->{post}="\\end{stuff}";
1280 };
1281 =item I<I get an internal error in an XML::XPath module. What next?>
1282  
1283 Please keep in mind that some XPath expressions, although
1284 syntactically correct, lead to errors. Consider the following snippet:
1285  
1286 my $targetname=findvalue("name(id($label))");
1287  
1288 It is an error for the XPath function name() to be called with
1289 anything but one stringifiable argument. Thus, if $label does not
1290 exist, you are screwed - and the evaluation of the XPath expression
1291 will produce a most cryptic error. Rewrite your code into this:
1292  
1293 my ($targetnode)=findnodes("id($label)");
1294 return "" if (! $targetnode);
1295 my $targetname=findvalue("name()",$targetnode);
1296  
1297 (but the real solution in this particular case is of course to
1298 validate your document against the DTD beforehand - that would have
1299 spotted the inexisting reference $label was supposed to point to.)
1300 =back
1301  
1302 =head1 REFERENCE MANUAL
1303  
1304 =head2 Support functions and global variables
1305  
1306 This stylesheet defines a number of convenience functions and global
1307 variables that can be reused inside your own extensions.
1308  
1309 =head3 Basic pipework
1310  
1311 =over 4
1312  
1313 =item warn_at($node, $message);
1314  
1315 =item die_at($node, $message);
1316  
1317 Same as warn() and die(), but produce appropriate messages indicating the
1318 point of the error, using get_xpath_of_node().
1319  
1320 =item my $text=framederror($error);
1321  
1322 =item my $text=centerederror($error);
1323  
1324 Typesets an error text in a 0.4\columnwidth wide framed box, which
1325 provides fancy error messages in place of missing images, bogus
1326 tables, etc. instead of quitting the stylesheet abruptly. The
1327 centerederror() function adds a centering environment around the box.
1328  
1329 =item @nodes=reorder_backaxis("forward",@nodes);
1330  
1331 =item @nodes=reorder_backaxis("backward",@nodes);
1332  
1333 Assuming that @nodes was obtained through a call to I<findnodes> on a
1334 backward axis (which has ordering issues, see L</Quirks>), Do The
1335 Right Thing and reverse them if needed (e.g. when you want your nodes
1336 backwards w.r.t. document order and the I<XML::XPath> du jour provides
1337 them forwards, or vice versa). Will die if the behaviour of the
1338 XML::XPath version in use is unknown (right now, we are backward
1339 compatible, pun intended, with all versions up to 1.13).
1340  
1341 =item my $outputtext=apply_templates_under( [ $xpath ] , [ $node ] );
1342  
1343 Same as L<XML::XPathScript/apply_templates>, but allows for "skipping"
1344 node types that are not handled directly (for example because they are
1345 abstract - see L<@abstracttags>). C<apply_templates_under($node)>
1346 applies the templates to all children of $node (excluding $node
1347 itself), and returns the concatenation of all results;
1348 C<apply_templates_under($xpath, $node)> applies the templates to those
1349 nodes that match C<$xpath> starting from C<$node>, and returns the
1350 concatenation of all results.
1351  
1352 =item call_template($node,$t,$template);
1353  
1354 Calls a template from a "testcode" routine, and updates $t accordingly
1355 as if calling the appropriate "testcode" entry in $template, a
1356 standard XML::XPathScript template structure. Returns the same value
1357 as said testcode would. This function is useful for overloading
1358 templates in cascaded stylesheets:
1359  
1360 my $oldtemplate=delete $t->{someelement};
1361 $t->{someelement}->{testcode}=sub {
1362 my ($node,$t)=@_;
1363 return call_template($node,$t,$oldtemplate);
1364 };
1365  
1366 (the above example is trivial, as it does exactly the same thing as
1367 the old template would. But you get the idea).
1368  
1369 If $template has no "testcode" tag, the functionality is emulated
1370 (e.g. $t->{pre} is set from $template->{pre} etc.)
1371 =item %uniconvs
1372  
1373 A hash whose keys are numeric Unicode codes (see L</SEE ALSO>) and whose
1374 values are the corresponding LaTeX sequences to render the character.
1375 %uniconvs need not contain space, tab, newline nor any Latin1 character
1376 (those are done automatically), but it doesn't hurt if it does.
1377  
1378 One must call reload_uniconvs() after modifying this variable.
1379 =item $uniunknown
1380  
1381 The sequence of characters rendered in place of an unknown character.
1382  
1383 =item reload_uniconvs();
1384  
1385 Refreshes the internal variables of this stylesheet (namely, a regexp
1386 cache). To be called whenever %uniconvs is modified.
1387  
1388 =item my $textinlatin1 = utf8tolatin1($textinunicode);
1389  
1390 Returns a Unicode-untainted, Latin1-only copy of its input (which may
1391 be a text node or a stringifiable object). Unicode characters above
1392 0x0fe in $textinunicode are removed.
1393  
1394 =item my $textinlatex = utf8totex($textinunicode, $significantspace);
1395  
1396 =item my $textinlatex = utf8totex($textinunicode, $translations);
1397  
1398 Converts an UTF8-encoded string, stringifiable object or text node
1399 (that is, most kinds of stuff coming down from the XML data model)
1400 into a form that is GROKked by LaTeX using the C<inputenc> package
1401 (most Latin1 characters are supported directly). This function first
1402 uses the C<%uniconvs> configuration variable (see above), then a
1403 direct Latin1 mapping if the character is either whitespace or in
1404 Latin1 range. If this also fails, C<$uniunknown> is rendered and an
1405 appropriate warning is emitted. Unless $significantspace is set to a
1406 true value, sequences of consecutive whitespace are collapsed to one
1407 and purely whitespace strings are converted to the empty string.
1408  
1409 If $translations is additionnally a hash reference, it may supply
1410 additional character transliterations that will override those in
1411 L<%uniconvs>. This is most useful for verbatim modes.
1412 =item my $labelstring = langofnode($node);
1413  
1414 Returns the language that prevails in node $node (as defined by the closest
1415 ancestor having a "lang" tag). Returns the empty string if no ancestor has
1416 a "lang" tag.
1417  
1418 =item my $text= flatten_textnodes ($node);
1419  
1420 =item my $text= flatten_textnodes ($node,$xpath);
1421  
1422 Returns a text version of $node's content, obtained by concatenating
1423 all text subnodes in $node, normalizing all whitespace to just one
1424 space, and suppressing ISO Latin1 accents. The return value is in
1425 Latin1. This is used for example in the <indexterm> template, to get
1426 alphabetic sorting right in C<makeindex>. $xpath, if specified, is an
1427 XPath expression to filter the right text subnodes in $node (the
1428 default is ".//text()").
1429  
1430 =back
1431  
1432 =head3 General LaTeX support
1433  
1434 Functions and global variables in there deal with day-to-day LaTeX,
1435 excluding character set issues (dealt with in L</Basic pipework>) and
1436 tables (see L</LaTeX tables>).
1437  
1438 =over 4
1439  
1440 =item $documentclass
1441  
1442 =item @documentclass_args
1443  
1444 The arguments to the opening \documentclass{} macro call. By default,
1445 docbook2latex produces a 11pt, twoside, a4paper report (that is,
1446 C<$documentclass="report"> and C<< @documentclass_args = ("11pt",
1447 "twoside", "a4paper") >>).
1448  
1449 =item $dvidriver or $ENV{DVIDRIVER}
1450  
1451 The name of the DVI driver used for rendering this document, such as
1452 C<dvipdfm> or C<dvips>. This variable also helps making decisions for
1453 rendering images (the <graphic> tag for example). This stylesheet
1454 indeed has support for both PostScript® and PDF document rendering,
1455 but unfortunately not through the same TeX output file (due to
1456 restrictions on LaTeX's side) so the DVI driver has to be chosen at
1457 XML-to-LaTeX conversion time.
1458  
1459 As a not-really-functional-style but oh-so-convenient temporary kludge
1460 (pending a standard means of passing stylesheet arguments on the
1461 xpathscript command line), $ENV{DVIDRIVER} is the default value of
1462 $dvidriver, that is, one can change this parameter through the
1463 environment, without even altering the stylesheet.
1464 =item @abstracttags
1465  
1466 The list of tags that are abstract, that is, that should never have
1467 apply_templates() applied to them directly. An example is <title>
1468 tags that cannot be rendered properly alone, but only as part of their
1469 parent <section>, <table> or the like. This variable is read-only and
1470 only serves as a convenience to the programmer (``is it of any use
1471 for me to overload this tag in $t ?''), modifying it has no effect.
1472  
1473 =item $fancytables
1474  
1475 If set to a true value (the default), tables are typeset using the
1476 C<longtable> and C<multirows> LaTeX packages. If set to a false value,
1477 plain C<tabular>s are used instead.
1478  
1479 =item $glosstermsinindex
1480  
1481 If set to a true value (the default), then <glossterm> nodes that do
1482 not appear in a <glosslist> will be included automatically in the
1483 index with a status of preferred entries (equivalent to <indexterm
1484 significance="preferred">).
1485  
1486 =item @packages
1487  
1488 The list of packages to be included into the LaTeX preamble. This array
1489 may contain plain strings, or references to sub-arrays for packages that
1490 want options (the package name comes first in the sub-array, then the
1491 function - see L</An example>).
1492  
1493 =item @sectionnames
1494  
1495 The sequence of section-like TeX macros, from highest (e.g. 'part') to lowest
1496 (e.g. 'subparagraph'). Customizing this is likely to be a priority for
1497 those not satisfied with the aesthetics.
1498  
1499 =item @tablesatbeginning
1500  
1501 The macros for the table(s) to be generated at the beginning of the
1502 document (without the backslash). By Default "tableofcontents" is
1503 always first and then "listoffigures" and "listoftables" (in that
1504 order) are appended iff there is at least one figure (resp. table) in
1505 the document.
1506  
1507 =item @tablesatend
1508  
1509 The macros for the table(s) to be generated at the end of the document
1510 (without the backslash). Defaults to empty, or just "printindex" if
1511 there is at least one <indexterm> in the document.
1512  
1513 =item $TeXkludges
1514  
1515 The set of macro definitions that has to be present in the document in order
1516 to get it to process. We tried very hard to keep this to a minimum - but there
1517 still was quite a bit of Knuth cursing going on at IDEALX during the making
1518 of this stylesheet. If you have solutions without those, let us know.
1519  
1520 =item $TeXpreamble
1521  
1522 A variable to append to to your liking to include TeX directives
1523 into the LaTeX preamble.
1524  
1525 =item $TeXbegindocument
1526  
1527 A variable to set to your liking to include TeX directives just after
1528 the LaTeX \begin{document}. Initially set to some general typesetting
1529 directives.
1530  
1531 =item $inhibitOutput
1532  
1533 If set to one, this stylesheet doesn't apply_templates() by itself. Useful
1534 if you want to overload it (see L</An example>)
1535  
1536 =item %boxlabels
1537  
1538 =item %boxstyles
1539  
1540 Both variables govern the rendering of I<tip>, I<remark>, I<note>,
1541 I<example>, I<warning>, I<important> and I<caution> elements. Entries
1542 in %boxstyles are keyed by element names, and the matching values are
1543 the LaTeX command that is used to wrap them, without the backslash
1544 (fancybox macros are set up by default, see the LaTeX Companion page
1545 278).
1546  
1547 %boxlabels holds the translations of the default titles for those
1548 environments. it is a hash of hashes, whose outermost keys are
1549 two-letter language abbreviations (e.g. "en" and "fr"), and whose
1550 innermost keys are the element names.
1551 =item my $TeXlength = TeXlength($docbooklength);
1552  
1553 =item my $TeXlength = TeXlength($docbooklength, $starlength);
1554  
1555 Returns the conversion of $docbooklength into a LaTeX length. If
1556 $starlength is specified, this is the value of "1*" (default is
1557 \fill).
1558  
1559 =item my $TeXlength = multiply_TeX_dimension($TeXlength, $factor);
1560  
1561 As the name implies, multiplies a TeX dimension by the given factor.
1562  
1563 =item my $label = id2label($node [, $labelname ] );
1564  
1565 Takes the attribute named $labelname ("id" by default) from $node and
1566 turns it into a string that is "more or less" unique and may be used
1567 as the argument of a \label{} or \ref{} command in TeX (e.g. bogus
1568 characters stripped). Returns undef if $node has no id (or no
1569 attribute named $labelname).
1570  
1571 =item my $labelstring = thelabel($node);
1572  
1573 Supports cross-referencing in LaTeX. If C<$node> has an C<id> tag,
1574 returns C<\label{id}>, else returns the empty string. The function id2label()
1575 above is used for this purpose.
1576  
1577 =item my $titleornothing = listtitle($node);
1578  
1579 Returns a typeset title as "\paragraph*{Title}", or the empty string,
1580 depending on whether $node has a <title> child. Appropriate for
1581 paragraph-like elements that may have a title, such as <itemizedlist>,
1582 <orderedlist>, <formalpara> etc.
1583  
1584 =item my $n = section_nesting_depth($node);
1585  
1586 Returns the depth of the current section nesting, in terms of an index
1587 into @sectionnames that would be appropriate for placing a sectionning macro
1588 for $node if it were itself a section.
1589  
1590 =item my $author_or_authors = render_authors($rendermode, $node);
1591  
1592 When $node is an <article> or <book> node, returns the typeset string
1593 of the author(s) of the article or book. $rendermode is the rendering
1594 style; recognizes modes for now are "stack" (returns multiple authors
1595 as a tabular that stacks authors vertically) and "ampersand" (returns
1596 a string of the form "Johnson, Johnson \& Johnson").
1597  
1598 =item my $author_or_authors = render_authors($rendermode, @author_names);
1599  
1600 When @author_names are already typeset author names (typically using
1601 the template for C<author>), returns the typeset string of the group
1602 of said authors according to $rendermode (see above).
1603  
1604 =item my $text=render_graphic($node);
1605  
1606 =item my $text=render_graphic($node, $scale);
1607  
1608 If $node is a <graphic> or <inlinegraphic> element node object, then
1609 render the appropriate \includegraphics{} command for it (but not the
1610 surrounding TeX material for centering or making a float of it). This
1611 is shared code for <graphic> and <inlinegraphic> templates. $scale is
1612 an optional scale factor (default is 1) to multiply the
1613 document-specified dimensions with (using L</multiply_TeX_dimension>).
1614  
1615 =back
1616  
1617 =head3 LaTeX footnotes
1618  
1619 Mostly every time some kind of tabular or minipage environment is
1620 used, the \footnote{} macro becomes nonfunctional inside it. It is
1621 still possible to typeset footnotes; the trick is page 71 of the LaTeX
1622 Companion - you have to look for it, though: instead of
1623  
1624 \begin{table}{|c|}
1625 foo\footnote{bar}
1626 \end{table}
1627  
1628 one says
1629  
1630 \begin{table}{|c|}
1631 foo\footnotemark{}
1632 \end{table}
1633 \footnotetext{bar}
1634  
1635 This looks like too tough a job for a pure context-dependent
1636 stylesheet paradigm right? Wrong :-).
1637 =over 4
1638  
1639 =item @footnote_blockers
1640  
1641 The list of element names that may typeset themselves in such a way that
1642 the \footnote{} macro does not work inside them. Stylesheet extension
1643 writers should add (or subtract, why not?) elements there according to
1644 their LaTeX design.
1645  
1646 =item my $latex = render_footnote($node, $text)
1647  
1648 Returns an appropriate LaTeX snippet for signalling a footnote as part
1649 of $node's rendering, containing $text as the text. Appropriate for
1650 implementing the templates of <footnote>, <ulink> et al. This function
1651 is not as trivial as it seems, because it handles the necessary magic
1652 of \footnotemark / \footnotetext in minipages environments
1653 (e.g. tables) where normal footnotes cannot be used because of
1654 limitations in LaTeX.
1655  
1656 =item collect_trapped_footnotes($node)
1657  
1658 =item collect_trapped_footnotes($node, @children)
1659  
1660 Returns a string made up of all \footnotetext{}'s that are to appear
1661 below $node's rendering, assuming it blocks footnotes. This list is
1662 collected by rendering @children again (by default, all of $node's
1663 children) using a skewed definition of render_footnote().
1664  
1665 =back
1666  
1667 =head3 LaTeX tables
1668  
1669 =over 4
1670  
1671 =item my $x = table_getcolXbyname($row, $name);
1672  
1673 =item my ($xstart, $xend) = table_getspanXbyname($row, $name);
1674  
1675 Returns the 1-based x coordinate(s) of a column / span in the column
1676 /span set of a table, or dies if the named column / span does not
1677 exist. These functions cache results. $row is a C<row> node object,
1678 and $name must match a C<colname> attribute in an applicable
1679 C<colspec>, resp. a C<spanname> attribute in an applicable C<spanspec>
1680 (see the CALS table model in L<SEE ALSO>). C<table_getcolXbyname>
1681 applies C<colspec> overloading according to the CALS semantics (see
1682 L</table_getcolspecbyX>).
1683  
1684 =item my $colspec = table_getcolspecbyX($row_or_entry, $x)
1685  
1686 Returns the C<colspec> in vigor for the specified, 1-based X
1687 coordinate, or undef if no such C<colspec> is in the
1688 document. Overloading of <colspec> sub-elements in C<thead> or
1689 C<tfoot> is handled according to the CALS specification, that is, if
1690 there is any C<colspec> at C<thead> or C<tfoot> model, they shadow the
1691 above ones at C<tgroup> level entirely, and only the inner set is then
1692 taken into account (e.g. shadowing, not merging, occurs when
1693 overloading).
1694  
1695 Note that CALS dictates that there should not be more than one colspec
1696 for a given column, so there is no discussion of list context for this
1697 function.
1698 =item my $spanspec = table_getspanspecbyX($row_or_entry, $xstart, $xend)
1699  
1700 =item my @several_spanspecs = table_getspanspecbyX($row_or_entry, $xstart, $xend)
1701  
1702 Returns the. C<spanspec> in vigor for the specified, 1-based X
1703 coordinates, or undef if no such C<spanspec> is in the document. In
1704 list context, I<table_getspanspecbyX()> may return several different
1705 spanspecs, in document order - in scalar context, in case of a tie,
1706 this function would only return the last relevant one in document
1707 order.
1708  
1709 =item my $colspec = table_getspecbyentry($entry, $leftcolumn);
1710  
1711 =item my $colspec = table_getspecbyentry($entry, $leftcolumn, $nojusthappen);
1712  
1713 Returns the "best" (see below) <colspec> or <spanspec> element node
1714 object associated with the column or group of columns spanned by
1715 $entry, or undef if there is no such colspec or spanspec. $leftcolumn
1716 (mandatory) is to be the 1-based column number at which $entry starts
1717 (the caller, which is typically L</typeset_tablerow>, must know
1718 this). Useful for querying style parameters from the parent column.
1719  
1720 $entry may either refer to the result by an explicit C<colname> or
1721 C<spanname> attribute in the document, or alternatively, unless
1722 $nojusthappen is set to a true value, it may also "just happen" to
1723 occupy the same column set.
1724  
1725 In case of multiple possible outcomes to this function, the
1726 "nominative" specs have priority over the "just happening" ones, the
1727 spanspecs have priority over the colspecs, and C<spanspec>s coming
1728 last in document order have priority in the "just happening" mode.
1729 =back
1730  
1731 =head2 Overridable function references
1732  
1733 Extension authors may wish to re-use part of this stylesheet's
1734 functionality at a sub-template level: typically, one may want to
1735 alter the outlook of tables without having to duplicate the tedious,
1736 stateful table filling algorithm that transcodes XML CALS tables into
1737 LaTeX. This stylesheet supports that by defining overridable function
1738 references at appropriate points, that extension authors may replace
1739 with their own implementation (see L</Modification points>).
1740  
1741 =head3 Pluggable LaTeX
1742  
1743 =over 4
1744  
1745 =item my $outputtext = &$typeset_pageref($node,$linkend);
1746  
1747 Typesets a reference containing a page number, to be put right after
1748 the \ref{$linkend} in the typesetting of $node, wich is an <xref>,
1749 without an intervening space. Possible values are " (page
1750 \pageref{$linkend})" (mind the leading space) or something like that,
1751 or the empty string if you don't want pagerefs. The default function
1752 tries to be smart and avoid the double closing parentheses problem
1753 when the <xref> is itself between parentheses. $linkend will be passed
1754 properly escaped, in such a way that outputting it to TeX in forms
1755 such as "\\ref{$linkend}" and "\\pageref{$linkend}" without any further
1756 transformation will produce the correct links.
1757  
1758 =item my $outputtext = &$maketitle($title,\@subtitles,@authors);
1759  
1760 This function shall typeset a titlepage (to be put just after the
1761 \begin{document}). If not set, the standard \title, \author,
1762 \maketitle mechanism of LaTeX will be used instead. zero, one or more
1763 subtitles may be passed as a list reference in the second argument.
1764  
1765 =item &$typeset_bibentry($node,$t,$lang);
1766  
1767 This function shall typeset a <biblioentry> or <biblioset>, ignoring the
1768 <biblioset> children. $node is the node to typeset in language $lang. There
1769 is a concept of $t->{pre} and $t->{post} analogous to the second argument
1770 of a testcode function; the semantics is that when an article and its
1771 proceedings are to be typeset together, the result will be made up with
1772 $tarticle->{pre}, $tproceedings->{pre}, $tproceedings->{post} and
1773 $tarticle->{post} (which is the normal way in french and in english, so
1774 that page numbers and the like appear last).
1775  
1776 The return value is ignored. Unrecognized element children should be
1777 appropriately warned.
1778 =back
1779  
1780 =head3 Pluggable table rendering
1781  
1782 =over 4
1783  
1784 =item my $outputtext = &$typeset_tablerow($style,@row);
1785  
1786 This function shall typeset a row in a table, given a style (which is
1787 either 'thead', 'tbody' or 'tfoot' --- typesetting happens in that
1788 order), and a list of hashrefs containing a description of the cells
1789 in this line: $row[0]->{height} and $row[0]->{width} contain the
1790 dimensions of the cell, and $row[0]->{cell} contains either undef (a
1791 blank cell - in this case height and width are always 1) or a
1792 reference to the XML::XPath::Element::Node object for this cell (an
1793 <entry> tag - <entrytbl>s are not supported yet).
1794  
1795 The entries are positionned according to their upper left corner;
1796 elements in @row that have an undef ->{cell} represent coordinate
1797 points under a multiple-cell entry, to be skipped. @row is guaranteed
1798 to be of the same width as the whole table. Warning, though, many
1799 XPath functions (and functions in this stylesheet) start numbering at
1800 1, while Perl starts numbering at 0; the code for your very own
1801 version of &$typeset_tablerow should therefore probably start like
1802 this:
1803  
1804 my ($style, @row)=@_;
1805 for(my $colnum=1; $colnum <= (scalar @row); $colnum++) {
1806 my $elem=$row[$colnum - 1];
1807 # Do stuff
1808 }
1809  
1810 =item my $outputtext = &$typeset_tablerule($style,\@rowbefore,\@rowafter);
1811  
1812 This function shall typeset a separator between two rows. It also gets
1813 called before the first row in a group (the second parameter is then undef),
1814 and after the last row in a group (the first parameter is undef). A I<group>
1815 is the amount of rows represented by a whole <thead>, <tbody> or <tfoot>
1816 element. The contents of the lists pointed to by the second and third
1817 parameters (if defined) are not to be modified, and have the same structure
1818 as @row above. $style is as above.
1819  
1820 =item my $outputtext = &$typeset_tableframe($tgroup,$headtxt,$bodytxt,$foottxt);
1821  
1822 This function shall re-order $headtxt, $bodytxt and $foottxt (which
1823 are rendered TeX snippets for their respective parts of the $tgroup
1824 element node object, or undef if said <tgroup> lacks one of them) and
1825 eventually produce a valid overall TeX code for the whole table. This
1826 function is B<not> responsible for outputting the C<\begin{table}> or
1827 C<\end{table}> stuff; on the other hand, it shall render the table
1828 caption and the cross-reference label(s) (in $fancytables mode
1829 only). It had better pay attention to the value of the global variable
1830 $fancytables, since the surrounding TeX table frame will be very
1831 different according to its boolean value (tabular vs. longtable).
1832  
1833 By default, the function Does The Right Thing for multipage tables to
1834 work properly with longtable (if enabled).
1835 =item my $outputtext= &$typeset_tablecolumnpattern($node,$kind,$tgroup,$width);
1836  
1837 This function shall typeset the TeX column specification, this is, the
1838 "c|" part of "\begin{table}{c|}". The "|" after the "c" is meant:
1839 indeed, the CALS specification dictates that columns, spans and
1840 entries specify the rulings which lie on their right, except for the
1841 rightmost column (that you need not worry about; the stylesheet will
1842 take care of removing any separator material at the end of your column
1843 pattern if needed).
1844  
1845 This function shall apply both to <colspec> nodes (in order to render
1846 the TeX table header), <spanspec> nodes (for \multicolumn patterns
1847 inside the table) and <entry> nodes (for another, one-column
1848 \multicolumn that is the only way in TeX to typeset one cell centered,
1849 for example, when all the others in the same column are
1850 left-justified). $kind will be set to either "colspec", "spanspec" or
1851 "entry", respectively. The first argument may be undef for columns
1852 that don't have a colspec, and for multicolumn cells that do not
1853 specify a spanspec. In this case, it is still possible to get
1854 typesetting data using $tgroup, which always contains an element node
1855 object pointing to the table's <tgroup> element.
1856  
1857 By default, &$typeset_tablecolumnpattern() handles the 'colwidth' and
1858 'align' attributes only. A width may also be specified by caller using
1859 the optional $width argument, in which case
1860 &$typeset_tablecolumnpattern() should attempt to honor it by priority.
1861 =back
1862  
1863 =head2 Self-test
1864  
1865 The I<integrationtest()> function tests the behaviour of foreign
1866 packages that this stylesheet depends on (namely Perl itself
1867 for the UTF8-tainting issues, and I<XML::XPath> for minor API
1868 issues). The following derived stylesheet, when run on any document,
1869 will produce a text output compatible with L<Test::Harness>:
1870  
1871 E<32>E<32><% our $inhibitOutput; $inhibitOutput++; %I<>>
1872  
1873 E<32>E<32><!--#I<>include file="docbook2latex.xps"-->
1874  
1875 E<32>E<32><% integrationtest() %I<>>
1876 =head1 DOCBOOK EXTENSIONS
1877  
1878 The I<tgroupstyle> attribute of <tgroup> nodes is interpreted as a
1879 comma-separated list of LaTeX commands to wrap all cells with. A
1880 useful example is "footnotesize", for large tables.
1881  
1882 =head1 NONSTANDARD DOCBOOK CONSTRUCTIONS
1883  
1884 When using a format attribute "linespecific" in a <graphic> element,
1885 the LaTeX mechanism of selecting a file by trying various extensions
1886 is used. In this case, and contrary to what the DTD documentation
1887 says, one should omit the extension in the "fileref" attribute.
1888  
1889 Cross references are rendered in a context-sensitive way which is much
1890 more like Perl's DWIM (Do What I Mean) than XML's OTFA
1891 (One Template Fits All): the stylesheet parses the surrounding text to
1892 determine which one of "Figure 3.2, page 42", "Figure 3.2 (page 42)"
1893 or "3.2 (page 42)" is the correct rendering for <xref linkend="FIG-3-2">.
1894 This is to overcome a design limitation in the DTD spec, which make
1895 <xref>s inappropriate for any language but english.
1896  
1897 The words "TeX" and "LaTeX" are rendered as you might imagine they
1898 should. This is the only form of "semantic kerning" that should occur
1899 in the stylesheet, though (e.g. "---" really produces 3 dashes in the
1900 DVI and is not he same as "&mdash;" in the XML source).
1901 =head1 BUGS / TODO / LIMITATIONS
1902  
1903 Only a subset of DocBook is implemented. Adding tags is easy most of
1904 the time though.
1905  
1906 MediaObject's are the only portable, kosher way of dealing with
1907 multi-format graphics (such as PostScript® vs. PNG in PDF's). They are
1908 not implemented.
1909  
1910 Bibliography support is far from optimal and will result in bogus
1911 punctuation and label spacing every so often.
1912  
1913 There is no support for variadic typesetting of characters according
1914 to the language (for example, &hellip; is rendered the same way under
1915 french and english, but shouldn't). Using additional character
1916 packages on-demand (that is, usepackage'ing them only when some
1917 Unicode characters are present in the input) isn't possible. Both
1918 restrictions stem from the flat Unicode character space in XML that
1919 disregards the level of strangeness of character entities (e.g. it is
1920 impossible to construct an XPath formula meaning "give me all strange
1921 characters in this document"). Building a list of all characters in
1922 the document from Perl would be a solution, although I cannot think of
1923 an efficient way of doing that.
1924 =head1 SEE ALSO
1925  
1926 XPathScript documentation:
1927  
1928 http://axkit.org/docs/xpathscript/guide.dkb
1929  
1930 XPath documentation from W3C:
1931  
1932 http://www.w3.org/TR/xpath
1933  
1934 The Docbook DTD:
1935  
1936 http://www.docbook.org/tdg/en/html/docbook.html
1937  
1938 The CALS table model:
1939  
1940 http://www.oasis-open.org/specs/a502.htm
1941  
1942 Unicode character table (needed to add more character support into a
1943 stylesheet):
1944  
1945 http://www.unicode.org/charts/charindex.html
1946  
1947 Ditto, less complete but more LaTeX-friendly:
1948  
1949 http://www.bitjungle.com/~isoent/
1950 =head1 COPYRIGHT
1951  
1952 This program is copyright (C) Dominique Quatravaux
1953 <dom@idealx.com>, all rights reserved. This program is free software; you
1954 can redistribute it and/or modify it under the same terms as Perl itself.
1955  
1956  
1957  
1958 =end devel
1959  
1960 =head1 AUTHORS
1961  
1962 =over 4
1963  
1964 =item *
1965  
1966 Yanick Champoux <yanick@cpan.org>
1967  
1968 =item *
1969  
1970 Dominique Quatravaux <domq@cpan.org>
1971  
1972 =item *
1973  
1974 Matt Sergeant <matt@sergeant.org>
1975  
1976 =back
1977  
1978 =head1 COPYRIGHT AND LICENSE
1979  
1980 This software is copyright (c) 2019, 2018, 2008, 2007 by Matt Sergeant.
1981  
1982 This is free software; you can redistribute it and/or modify it under
1983 the same terms as the Perl 5 programming language system itself.
1984  
1985 =cut
1986  
1987 __END__
↑ Summary XPathScript.pm »