]> git.donarmstrong.com Git - lilypond.git/blob - lilypond-texi2html.init
Use hashlib instead of deprecated md5 module if Python >= 2.5 is present
[lilypond.git] / lilypond-texi2html.init
1 #!/usr/bin/env perl
2 # -*- coding: utf-8; -*-
3
4 ### texi2html customization script for Lilypond
5 ### Author: Reinhold Kainhofer <reinhold@kainhofer.com>, 2008.
6 ###         Some code parts copied from texi2html and adapted. These functions
7 ###         were written mainly by Patrice Dumas
8 ### License: GPLv2+
9 ###
10 ###
11 ### Features implemented here:
12 ### -) For split manuals, the main page is index.html.
13 ### -) All @unnumbered* sections are placed into the same file
14 ###    (implemented by split_at_numbered_sections)
15 ### -) Use our custom CSS file, with IE-specific fixes in another CSS file,
16 ###    impelmented by lilypond_css_lines
17 ### -) TOC (folded, with the current page highlighted) in an overflown <div>
18 ###    is added to every page; implemented by:
19 ###           lilypond_print_element_header -- building of the TOC
20 ###           lilypond_toc_body -- generation of customized TOC output
21 ###           lilypond_print_page_head -- start <div id="main">
22 ###           print_lilypond_page_foot -- closing id=main, output of footer & TOC
23 ### -) External refs are formatted only as "Text of the node" (not as >>see
24 ###    "NODE" section "SECTION" in "BOOK"<< like with default texi2html). Also,
25 ###    the leading "(book-name)" is removed.
26 ###    Implemented by overriding lilypond_external_ref
27 ### -) Navigation bars on top/bottom of the page and between sections are not
28 ###    left-aligned, but use a combination of left/center/right aligned table
29 ###    cells; For this, I heavily extend the texi2html code to allow for
30 ###    differently aligned cells and for multi-line tables);
31 ###    Implemented in lilypond_print_navigation
32 ### -) Different formatting than the default: example uses the same formatting
33 ###    as quote.
34 ### -) Allow translated section titles: All section titles can be translated,
35 ###    the original (English) title is associated with @translationof. This is
36 ###    needed, because the file name / anchor is generated from the original
37 ###    English title, since otherwise language-autoselection would break with
38 ###    posted links.
39 ###    Since it is then no longer possible to obtain the file name from the
40 ###    section title, I keep a sectionname<=>filename/anchor around. This way,
41 ###    xrefs from other manuals can simply load that map and retrieve the
42 ###    correct file name for the link. Implemented in:
43 ###           lilypond_unknown (handling of @translationof, in case
44 ###                             extract_texi_filenames.py messes up...)
45 ###           lilypond_element_file_name (correct file name: use the map)
46 ###           lilypond_element_target_name (correct anchor: use the map)
47 ###           lilypond_init_map (read in the externally created map from disk)
48 ###           lilypond_external_href (load the map for xrefs, use the correct
49 ###                                   link target)
50 ### -) The HTML anchors for all sections are derived from the node name /
51 ###    section title (pre-generated in the .xref-map file). Implemented by:
52 ###           lilypond_element_target_name (adjust section anchors)
53 ### -) Use the standard footnote format "<sup>nr</sup> text" instead of the
54 ###    ugly format of texi2html (<h3>(nr)</h3><p>text</p>). Implemented in
55 ###           makeinfo_like_foot_line_and_ref
56 ###           makeinfo_like_foot_lines
57 ###           makeinfo_like_paragraph
58 ###
59 ###
60 ### Useful helper functions:
61 ### -) texinfo_file_name($node_name): returns a texinfo-compatible file name
62 ###    for the given string $node_name (whitespace trimmed/replaced by -,
63 ###    non-standard chars replaced by _xxxx (ascii char code) and forced to
64 ###    start with a letter by prepending t_g if necessary)
65
66
67 package Texi2HTML::Config;
68
69 #############################################################################
70 ### TRANSLATIONS
71 #############################################################################
72
73 use utf8;
74 my $LY_LANGUAGES = {};
75 $LY_LANGUAGES->{'fr'} = {
76     'Back to Documentation Index' => 'Retour à l\'accueil de la documentation',
77 };
78 $LY_LANGUAGES->{'es'} = {
79     'Back to Documentation Index' => 'Volver al índice de la documentación',
80 };
81 $LY_LANGUAGES->{'de'} = {
82     'Back to Documentation Index' => 'Zur Dokumentationsübersicht',
83 };
84
85
86 sub ly_get_string () {
87     my $lang = $Texi2HTML::THISDOC{current_lang};
88     my $string = shift;
89     if ($lang and $lang ne "en" and $LY_LANGUAGES->{$lang}->{$string}) {
90         return $LY_LANGUAGES->{$lang}->{$string};
91     } else {
92         return $string;
93     }
94 }
95
96
97 #############################################################################
98 ###  SETTINGS FOR TEXI2HTML
99 #############################################################################
100
101 @Texi2HTML::Config::CSS_REFS      = (
102     {FILENAME => "lilypond-mccarty.css", TITLE => "Patrick McCarty's design"}
103 );
104 @Texi2HTML::Config::ALT_CSS_REFS      = (
105     {FILENAME => "lilypond.css", TITLE => "Andrew Hawryluk's design" },
106     {FILENAME => "lilypond-blue.css", TITLE => "Kurt Kroon's blue design" },
107 );
108 $Texi2HTML::Config::USE_ACCESSKEY = 1;
109 $Texi2HTML::Config::USE_LINKS     = 1;
110 $Texi2HTML::Config::USE_REL_REV   = 1;
111 $Texi2HTML::Config::SPLIT_INDEX   = 0;
112 $Texi2HTML::Config::SEPARATED_FOOTNOTES = 0; # Print footnotes on same page, not separated
113 if ($Texi2HTML::Config::SPLIT eq 'section') {
114   $Texi2HTML::Config::element_file_name    = \&lilypond_element_file_name;
115 }
116 $Texi2HTML::Config::element_target_name  = \&lilypond_element_target_name;
117 $default_print_element_header = $Texi2HTML::Config::print_element_header;
118 $Texi2HTML::Config::print_element_header = \&lilypond_print_element_header;
119 $Texi2HTML::Config::print_page_foot      = \&print_lilypond_page_foot;
120 $Texi2HTML::Config::print_navigation     = \&lilypond_print_navigation;
121 $Texi2HTML::Config::external_ref         = \&lilypond_external_ref;
122 $default_external_href = $Texi2HTML::Config::external_href;
123 $Texi2HTML::Config::external_href        = \&lilypond_external_href;
124 $default_toc_body = $Texi2HTML::Config::toc_body;
125 $Texi2HTML::Config::toc_body             = \&lilypond_toc_body;
126 $Texi2HTML::Config::css_lines            = \&lilypond_css_lines;
127 $default_unknown = $Texi2HTML::Config::unknown;
128 $Texi2HTML::Config::unknown              = \&lilypond_unknown;
129 $default_print_page_head = $Texi2HTML::Config::print_page_head;
130 $Texi2HTML::Config::print_page_head      = \&lilypond_print_page_head;
131 # $Texi2HTML::Config::foot_line_and_ref    = \&lilypond_foot_line_and_ref;
132 $Texi2HTML::Config::foot_line_and_ref  = \&makeinfo_like_foot_line_and_ref;
133 $Texi2HTML::Config::foot_lines         = \&makeinfo_like_foot_lines;
134 $Texi2HTML::Config::paragraph          = \&makeinfo_like_paragraph;
135
136
137
138 # Examples should be formatted similar to quotes:
139 $Texi2HTML::Config::complex_format_map->{'example'} = {
140   'begin' => q{"<blockquote>"},
141   'end' => q{"</blockquote>\n"},
142   'style' => 'code',
143  };
144
145 %Texi2HTML::config::misc_pages_targets = (
146    'Overview' => 'Overview',
147    'Contents' => 'Contents',
148    'About' => 'About'
149 );
150
151
152 my @section_to_filename;
153
154
155
156
157 #############################################################################
158 ###  DEBUGGING
159 #############################################################################
160
161 use Data::Dumper;
162 $Data::Dumper::Maxdepth = 2;
163
164 sub print_element_info($)
165 {
166   my $element = shift;
167   print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
168   print "Element: $element\n";
169   print Dumper($element);
170 }
171
172
173
174
175
176 #############################################################################
177 ###  HELPER FUNCTIONS
178 #############################################################################
179
180 # Convert a given node name to its proper file name (normalization as explained
181 # in the texinfo manual:
182 # http://www.gnu.org/software/texinfo/manual/texinfo/html_node/HTML-Xref-Node-Name-Expansion.html
183 sub texinfo_file_name($)
184 {
185   my $text = shift;
186   my $result = '';
187   # File name normalization by texinfo:
188   # 1/2: letters and numbers are left unchanged
189   # 3/4: multiple, leading and trailing whitespace is removed
190   $text = main::normalise_space($text);
191   # 5/6: all remaining spaces are converted to '-', all other 7- or 8-bit
192   #      chars are replaced by _xxxx (xxxx=ascii character code)
193   while ($text ne '') {
194     if ($text =~ s/^([A-Za-z0-9]+)//o) { # number or letter stay unchanged
195       $result .= $1;
196     } elsif ($text =~ s/^ //o) { # space -> '-'
197       $result .= '-';
198     } elsif ($text =~ s/^(.)//o) { # Otherwise use _xxxx (ascii char code)
199       my $ccode = ord($1);
200       if ( $ccode <= 0xFFFF ) {
201         $result .= sprintf("_%04x", $ccode);
202       } else {
203         $result .= sprintf("__%06x", $ccode);
204       }
205     }
206   }
207   # 7: if name does not begin with a letter, prepend 't_g' (so it starts with a letter)
208   if ($result !~ /^[a-zA-Z]/) {
209     $result = 't_g' . $result;
210   }
211   # DONE
212   return $result
213 }
214
215
216 # Load a file containing a nodename<=>filename map (tab-sepatared, i.e.
217 # NODENAME\tFILENAME\tANCHOR
218 # Returns a ref to a hash "Node title" => ["FilenameWithoutExt", "Anchor"]
219 sub load_map_file ($)
220 {
221     my $mapfile = shift;
222     my $node_map = ();
223
224     if (open(XREFFILE, $mapfile)) {
225         my $line;
226         while ( $line = <XREFFILE> ) {
227             # parse the tab-separated entries and insert them into the map:
228             chomp($line);
229             my @entries = split(/\t/, $line);
230             if (scalar (@entries) == 3) {
231               $node_map->{$entries[0]} = [$entries[1], $entries[2]];
232             } else {
233               print STDERR "Invalid entry in the node file $mapfile: $line\n";
234             }
235         }
236         close (XREFFILE);
237     } else {
238         print STDERR "WARNING: Unable to load the map file $mapfile\n";
239     }
240     return $node_map;
241 }
242
243
244 # Split the given path into dir and basename (with .texi removed). Used mainly
245 # to get the path/basename of the original texi input file
246 sub split_texi_filename ($)
247 {
248   my $docu = shift;
249   my ($docu_dir, $docu_name);
250   if ($docu =~ /(.*\/)/) {
251     chop($docu_dir = $1);
252     $docu_name = $docu;
253     $docu_name =~ s/.*\///;
254   } else {
255      $docu_dir = '.';
256      $docu_name = $docu;
257   }
258   $docu_name =~ s/\.te?x(i|info)?$//;
259   return ($docu_dir, $docu_name);
260 }
261
262
263
264
265
266 #############################################################################
267 ###  CSS HANDLING
268 #############################################################################
269
270 # Include our standard CSS file, not hard-coded CSS code directly in the HTML!
271 # For IE, conditionally include the lilypond-ie-fixes.css style sheet
272 sub lilypond_css_lines ($$)
273 {
274     my $import_lines = shift;
275     my $rule_lines = shift;
276     return if (defined($Texi2HTML::THISDOC{'CSS_LINES'}));
277     if (@$rule_lines or @$import_lines)
278     {
279         $Texi2HTML::THISDOC{'CSS_LINES'} = "<style type=\"text/css\">\n<!--\n";
280         $Texi2HTML::THISDOC{'CSS_LINES'} .= join('',@$import_lines) . "\n" if (@$import_lines);
281         $Texi2HTML::THISDOC{'CSS_LINES'} .= join('',@$rule_lines) . "\n" if (@$rule_lines);
282         $Texi2HTML::THISDOC{'CSS_LINES'} .= "-->\n</style>\n";
283     }
284     foreach my $ref (@CSS_REFS)
285     {
286         $Texi2HTML::THISDOC{'CSS_LINES'} .= "<link rel=\"stylesheet\" type=\"text/css\" title=\"$ref->{TITLE}\" href=\"$ref->{FILENAME}\">\n";
287     }
288     foreach my $ref (@Texi2HTML::Config::ALT_CSS_REFS)
289     {
290         $Texi2HTML::THISDOC{'CSS_LINES'} .= "<link rel=\"alternate stylesheet\" type=\"text/css\" href=\"$ref->{FILENAME}\" title=\"$ref->{TITLE}\">\n";
291     }
292     $Texi2HTML::THISDOC{'CSS_LINES'} .= "<!--[if lte IE 7]>\n<link href=\"lilypond-ie-fixes.css\" rel=\"stylesheet\" type=\"text/css\">\n<![endif]-->\n";
293 }
294
295
296
297
298
299 #############################################################################
300 ###  SPLITTING BASED ON NUMBERED SECTIONS
301 #############################################################################
302
303 my $lastfilename;
304 my $docnr = 0;
305 my $node_to_filename_map = ();
306
307
308 # This function makes sure that files are only generated for numbered sections,
309 # but not for unnumbered ones. It is called after texi2html has done its own
310 # splitting and simply returns the filename for the node given as first argument
311 # Nodes with the same filename will be printed out to the same filename, so
312 # this really all we need. Also, make sure that the file names for sections
313 # are derived from the section title. We also might want to name the anchors
314 # according to node titles, which works by simply overriding the id element of
315 # the $element hash.
316 # If an external nodename<=>filename/anchor map file is found (loaded in
317 # the command handler, use the externally created values, otherwise use the
318 # same logic here.
319 sub lilypond_element_file_name($$$)
320 {
321   my $element = shift;
322   my $type = shift;
323   my $docu_name = shift;
324   my $docu_ext = $Texi2HTML::Config::EXTENSION;
325
326   my $node_name = main::remove_texi($element->{'node_ref'}->{'texi'});
327   # the snippets page does not use nodes for the snippets, so in this case
328   # we'll have to use the section name!
329   if ($node_name eq '') {
330     $node_name = main::remove_texi($element->{'texi'});
331   }
332
333   # If we have an entry in the section<=>filename map, use that one, otherwise
334   # generate the filename/anchor here. In the latter case, external manuals
335   # will not be able to retrieve the file name for xrefs!!! Still, I already
336   # had that code, so I'll leave it in in case something goes wrong with the
337   # extract_texi_filenames.py script in the lilypond build process!
338   if (exists ($node_to_filename_map->{$node_name})) {
339     (my $filename, my $anchor) = @{$node_to_filename_map->{$node_name}};
340     $filename .= ".$docu_ext" if (defined($docu_ext));
341
342     # unnumbered sections (except those at top-level!) always go to the same
343     # file as the previous numbered section
344     if (not ($element->{number}) and not ($lastfilename eq '') and ($element->{level} > 1)) {
345       $filename = $lastfilename;
346     }
347     if (($filename eq $lastfilename)) {
348       $$element{doc_nr} = $docnr;
349     } else {
350       $docnr += 1;
351       $$element{doc_nr} = $docnr;
352       $lastfilename = $filename;
353     }
354     return $filename;
355
356   } elsif ($type eq "top" or $type eq "toc" or $type eq "doc" or $type eq "stoc" or $type eq "foot" or $type eq "about") {
357     return;
358   } else {
359     print STDERR "WARNING: Node '$node_name' was NOT found in the map\n"
360         unless ($node_name eq '') or ($element->{'tag'} eq 'unnumberedsec')
361                or ($node_name =~ /NOT REALLY USED/);
362
363     # Numbered sections will get a filename Node_title, unnumbered sections will use
364     # the file name of the previous numbered section:
365     if (($element->{number}) or ($lastfilename eq '') or ($element->{level} == 1)) {
366       # normalize to the same file name as texinfo
367       if ($element->{translationof}) {
368         $node_name = main::remove_texi($element->{translationof});
369       }
370       my $filename = texinfo_file_name($node_name);
371       $filename .= ".$docu_ext" if (defined($docu_ext));
372       $docnr += 1;
373       $$element{doc_nr} = $docnr;
374       $lastfilename = $filename;
375       return $filename;
376     } else {
377       $$element{doc_nr} = $docnr;
378       return $lastfilename;
379     }
380   }
381
382   return;
383 }
384
385 sub lilypond_element_target_name($$$)
386 {
387   my $element = shift;
388   my $target = shift;
389   my $id = shift;
390   # Target is based on node name (or sec name for secs without node attached)
391   my $node_name = main::remove_texi($element->{'node_ref'}->{'texi'});
392   if ($node_name eq '') {
393     $node_name = main::remove_texi($element->{'texi'});
394   }
395
396   # If we have an entry in the section<=>filename map, use that one, otherwise
397   # generate the anchor here.
398   if (exists ($node_to_filename_map->{$node_name})) {
399     (my $filename, $target) = @{$node_to_filename_map->{$node_name}};
400   } else {
401     my $anchor = $node_name;
402     if ($element->{translationof}) {
403       $anchor = main::remove_texi($element->{translationof});
404     }
405     # normalize to the same file name as texinfo
406     $target = texinfo_file_name($anchor);
407   }
408   # TODO: Once texi2html correctly prints out the target and not the id for
409   #       the sections, change this back to ($id, $target)
410   return ($target, $target);
411 }
412
413
414 ## Load the map file for the corrently processed texi file. We do this
415 #  using a command init handler, since texi2html does not have any
416 #  other hooks that are called after THISDOC is filled but before phase 2
417 #  of the texi2html conversion.
418 sub lilypond_init_map ()
419 {
420     my ($docu_dir, $docu_name) = split_texi_filename ($Texi2HTML::THISDOC{'input_file_name'});
421     my $map_filename = main::locate_include_file ("${docu_name}.$Texi2HTML::THISDOC{current_lang}.xref-map")
422         || main::locate_include_file ("${docu_name}.xref-map");
423     $node_to_filename_map = load_map_file ($map_filename);
424 }
425 push @Texi2HTML::Config::command_handler_init, \&lilypond_init_map;
426
427
428
429 #############################################################################
430 ###  CLEANER LINK TITLE FOR EXTERNAL REFS
431 #############################################################################
432
433 # The default formatting of external refs returns e.g.
434 # "(lilypond-internals)Timing_translator", so we remove all (...) from the
435 # file_and_node argument. Also, we want only a very simple format, so we don't
436 # even call the default handler!
437 sub lilypond_external_ref($$$$$$)
438 {
439   my $type = shift;
440   my $section = shift;
441   my $book = shift;
442   my $file_node = shift;
443   my $href = shift;
444   my $cross_ref = shift;
445
446   my $displaytext = '';
447
448   # 1) if we have a cross ref name, that's the text to be displayed:
449   # 2) For the top node, use the (printable) name of the manual, unless we
450   #    have an explicit cross ref name
451   # 3) In all other cases use the section name
452   if ($cross_ref ne '') {
453     $displaytext = $cross_ref;
454   } elsif (($section eq '') or ($section eq 'Top')) {
455     $displaytext = $book;
456   } else {
457     $displaytext = $section;
458   }
459
460   $displaytext = &$anchor('', $href, $displaytext) if ($displaytext ne '');
461   return &$I('%{node_file_href}', { 'node_file_href' => $displaytext });
462 }
463
464
465
466
467
468 #############################################################################
469 ###  HANDLING TRANSLATED SECTIONS: handle @translationof, secname<->filename
470 ###                  map stored on disk, xrefs in other manuals load that map
471 #############################################################################
472
473
474 # Try to make use of @translationof to generate files according to the original
475 # English section title...
476 sub lilypond_unknown($$$$$)
477 {
478     my $macro = shift;
479     my $line = shift;
480     my $pass = shift;
481     my $stack = shift;
482     my $state = shift;
483
484     # the @translationof macro provides the original English section title,
485     # which should be used for file/anchor naming, while the title will be
486     # translated to each language
487     # It is already used by extract_texi_filenames.py, so this should not be
488     # necessary here at all. Still, I'll leave the code in just in case the
489     # python script messed up ;-)
490     if ($pass == 1 and $macro eq "translationof") {
491       if (ref($state->{'element'}) eq 'HASH') {
492         $state->{'element'}->{'translationof'} = main::normalise_space($line);
493       }
494       return ('', 1, undef, undef);
495     } else {
496       return &$default_unknown($macro, $line, $pass, $stack, $state);
497     }
498 }
499
500
501
502
503 my %translated_books = ();
504 # Construct a href to an external source of information.
505 # node is the node with texinfo @-commands
506 # node_id is the node transliterated and transformed as explained in the
507 #         texinfo manual
508 # node_xhtml_id is the node transformed such that it is unique and can
509 #     be used to make an html cross ref as explained in the texinfo manual
510 # file is the file in '(file)node'
511 sub lilypond_external_href($$$)
512 {
513   my $node = shift;
514   my $node_id = shift;
515   my $node_hxmlt_id = shift;
516   my $file = shift;
517
518   # 1) Keep a hash of book->section_map
519   # 2) if not file in keys hash => try to load the map (assign empty map if
520   #    non-existent => will load only once!)
521   # 3) if node in the section=>(file, anchor) map, replace node_id and
522   #    node_xhtml_id by the map's values
523   # 4) call the default_external_href with these values (or the old ones if not found)
524
525   if (($node_id ne '') and defined($file) and ($node_id ne 'Top')) {
526     my $map_name = $file;
527     $map_name =~ s/-big-page//;
528
529     # Load the map if we haven't done so already
530     if (!exists($translated_books{$map_name})) {
531       my ($docu_dir, $docu_name) = split_texi_filename ($Texi2HTML::THISDOC{'input_file_name'});
532       my $map_filename = main::locate_include_file ("${map_name}.$Texi2HTML::THISDOC{current_lang}.xref-map")
533           || main::locate_include_file ("${map_name}.xref-map");
534       $translated_books{$map_name} = load_map_file ($map_filename);
535     }
536
537     # look up translation. use these values instead of the old filename/anchor
538     my $section_name_map = $translated_books{$map_name};
539     my $node_text = main::remove_texi($node);
540     if (defined($section_name_map->{$node_text})) {
541       ($node_id, $node_hxmlt_id) = @{$section_name_map->{$node_text}};
542     } else {
543       print STDERR "WARNING: Unable to find node '$node_text' in book $map_name.\n";
544     }
545   }
546
547   if (defined $file) {
548     return &$default_external_href($node, $node_id, $node_hxmlt_id, $file);
549   } else {
550     return &$default_external_href($node, $node_id, $node_hxmlt_id);
551   }
552 }
553
554
555
556
557
558 #############################################################################
559 ###  CUSTOM TOC FOR EACH PAGE (in a frame on the left)
560 #############################################################################
561
562 my $page_toc_depth = 2;
563 my @default_toc = [];
564
565
566 # Initialize the toc_depth to 1 if the command-line option -D=short_toc is given
567 sub lilypond_init_toc_depth ()
568 {
569   if (exists($main::value{'short_toc'}) and not exists($main::value{'bigpage'})) {
570     $page_toc_depth = 1;
571   }
572 }
573 # Set the TOC-depth (depending on a texinfo variable short_toc) in a 
574 # command-handler, so we have them available when creating the pages
575 push @Texi2HTML::Config::command_handler_process, \&lilypond_init_toc_depth;
576
577
578 # recursively generate the TOC entries for the element and its children (which
579 # are only shown up to maxlevel. All ancestors of the current element are also
580 # shown with their immediate children, irrespective of their level.
581 # Unnumbered entries are only printed out if they are at top-level or 2nd level 
582 # or their parent element is an ancestor of the currently viewed node.
583 # The conditions to call this method to print the entry for a child node is:
584 # -) the parent is an ancestor of the current page node
585 # -) the parent is a numbered element at top-level toplevel (i.e. show numbered 
586 #    and unnumbered 2nd-level children of numbered nodes)
587 # -) the child element is a numbered node below level maxlevel
588 sub generate_ly_toc_entries($$$)
589 {
590   my $element = shift;
591   my $element_path = shift;
592   my $maxlevel = shift;
593   # Skip undefined sections, plus all sections generated by index splitting
594   return() if (not defined($element) or exists($element->{'index_page'}));
595   my @result = ();
596   my $level = $element->{'toc_level'};
597   my $is_parent_of_current = $element->{'id'} && $element_path->{$element->{'id'}};
598   my $ind = '  ' x $level;
599   my $this_css_class = $is_parent_of_current ? " class=\"toc_current\"" : "";
600
601   my $entry = "$ind<li$this_css_class>" . &$anchor ($element->{'tocid'}, "$element->{'file'}#$element->{'target'}",$element->{'text'});
602
603   push (@result, $entry);
604   my $children = $element->{'section_childs'};
605   if (defined($children) and (ref($children) eq "ARRAY")) {
606     my $force_children = $is_parent_of_current or ($level == 1 and $element->{'number'});
607     my @child_result = ();
608     foreach my $c (@$children) {
609       my $is_numbered_child = defined ($c->{'number'});
610       my $below_maxlevel = $c->{'toc_level'} le $maxlevel;
611       if ($force_children or ($is_numbered_child and $below_maxlevel)) {
612         my @child_res = generate_ly_toc_entries($c, $element_path, $maxlevel);
613         push (@child_result, @child_res);
614       }
615     }
616     # if no child nodes were generated, e.g. for the index, where expanded pages
617     # are ignored, don't generate a list at all...
618     if (@child_result) {
619       push (@result, "\n$ind<ul$NO_BULLET_LIST_ATTRIBUTE>\n");
620       push (@result, @child_result);
621       push (@result, "$ind</ul>\n");
622     }
623   }
624   push (@result, "$ind</li>\n");
625   return @result;
626 }
627
628
629 # Print a customized TOC, containing only the first two levels plus the whole
630 # path to the current page
631 sub lilypond_generate_page_toc_body($)
632 {
633     my $element = shift;
634     my $current_element = $element;
635     my %parentelements;
636     $parentelements{$element->{'id'}} = 1;
637     # Find the path to the current element
638     while ( defined($current_element->{'sectionup'}) and
639            ($current_element->{'sectionup'} ne $current_element) )
640     {
641       $parentelements{$current_element->{'sectionup'}->{'id'}} = 1
642               if ($current_element->{'sectionup'}->{'id'} ne '');
643       $current_element = $current_element->{'sectionup'};
644     }
645     return () if not defined($current_element);
646     # Create the toc entries recursively
647     my @toc_entries = ("<div class=\"contents\">\n", "<ul$NO_BULLET_LIST_ATTRIBUTE>\n");
648     my $children = $current_element->{'section_childs'};
649     foreach ( @$children ) {
650       push (@toc_entries, generate_ly_toc_entries($_, \%parentelements, $page_toc_depth));
651     }
652     push (@toc_entries, "</ul>\n");
653     push (@toc_entries, "</div>\n");
654     return @toc_entries;
655 }
656
657 sub lilypond_print_toc_div ($$)
658 {
659   my $fh = shift;
660   my $tocref = shift;
661   my @lines = @$tocref;
662   # use default TOC if no custom lines have been generated
663   @lines = @default_toc if (not @lines);
664   if (@lines) {
665   
666     print $fh "\n\n<div id=\"tocframe\">\n";
667     
668     # Remove the leading "GNU LilyPond --- " from the manual title
669     my $topname = $Texi2HTML::NAME{'Top'};
670     $topname =~ s/^GNU LilyPond(:| &[mn]dash;) //;
671     
672     # construct the top-level Docs index (relative path and including language!)
673     my $lang = $Texi2HTML::THISDOC{current_lang};
674     if ($lang and $lang ne "en") {
675       $lang .= ".";
676     } else {
677       $lang = "";
678     }
679     my $reldir = "";
680     $reldir = "../" if ($Texi2HTML::Config::SPLIT eq 'section');
681     my $uplink = $reldir."index.${lang}html";
682
683     print $fh "<p class=\"toc_uplink\"><a href=\"$uplink\" 
684          title=\"Documentation Index\">&lt;&lt; " .
685          &ly_get_string ('Back to Documentation Index') .
686          "</a></p>\n";
687
688     print $fh '<h4 class="toc_header"> ' . &$anchor('',
689                                     $Texi2HTML::HREF{'Top'},
690                                     $topname,
691                                     'title="Start of the manual"'
692                                    ) . "</h4>\n";
693     foreach my $line (@lines) {
694       print $fh $line;
695     }
696     print $fh "</div>\n\n";
697   }
698 }
699
700 # Create the custom TOC for this page (partially folded, current page is
701 # highlighted) and store it in a global variable. The TOC is written out after
702 # the html contents (but positioned correctly using CSS), so that browsers with
703 # css turned off still show the contents first.
704 our @this_page_toc = ();
705 sub lilypond_print_element_header
706 {
707   my $first_in_page = shift;
708   my $previous_is_top = shift;
709   if ($first_in_page and not @this_page_toc) {
710     if (defined($Texi2HTML::THIS_ELEMENT)) {
711       # Create the TOC for this page
712       @this_page_toc = lilypond_generate_page_toc_body($Texi2HTML::THIS_ELEMENT);
713     }
714   }
715   return &$default_print_element_header( $first_in_page, $previous_is_top);
716 }
717
718 # Generate the HTML output for the TOC
719 sub lilypond_toc_body($)
720 {
721     my $elements_list = shift;
722     # Generate a default TOC for pages without THIS_ELEMENT
723     @default_toc = lilypond_generate_page_toc_body(@$elements_list[0]);
724     return &$default_toc_body($elements_list);
725 }
726
727 # Print out the TOC in a <div> at the beginning of the page
728 sub lilypond_print_page_head($)
729 {
730     my $fh = shift;
731     &$default_print_page_head($fh);
732     print $fh "<div id=\"main\">\n";
733 }
734
735 # Print out the TOC in a <div> at the end of th page, which will be formatted as a
736 # sidebar mimicking a TOC frame
737 sub print_lilypond_page_foot($)
738 {
739   my $fh = shift;
740   my $program_string = &$program_string();
741 #   print $fh "<p><font size='-1'>$program_string</font><br>$PRE_BODY_CLOSE</p>\n";
742   print $fh "<!-- FOOTER -->\n\n";
743   print $fh "<!-- end div#main here -->\n</div>\n\n";
744
745   # Print the TOC frame and reset the TOC:
746   lilypond_print_toc_div ($fh, \@this_page_toc);
747   @this_page_toc = ();
748
749   # Close the page:
750   print $fh "</body>\n</html>\n";
751 }
752
753
754
755
756
757 #############################################################################
758 ###  NICER / MORE FLEXIBLE NAVIGATION PANELS
759 #############################################################################
760
761 sub get_navigation_text
762 {
763   my $button = shift;
764   my $text = $NAVIGATION_TEXT{$button};
765   if ( ($button eq 'Back') or ($button eq 'FastBack') ) {
766     $text = $text . $Texi2HTML::NODE{$button} . "&nbsp;";
767   } elsif ( ($button eq 'Forward') or ($button eq 'FastForward') ) {
768     $text = "&nbsp;" . $Texi2HTML::NODE{$button} . $text;
769   } elsif ( $button eq 'Up' ) {
770     $text = "&nbsp;".$text.":&nbsp;" . $Texi2HTML::NODE{$button} . "&nbsp;";
771   }
772   return $text;
773 }
774
775
776 # Don't automatically create left-aligned table cells for every link, but
777 # instead create a <td> only on an appropriate '(left|right|center)-aligned-cell-n'
778 # button text. It's alignment as well as the colspan will be taken from the
779 # name of the button. Also, add 'newline' button text to create a new table
780 # row. The texts of the buttons are generated by get_navigation_text and
781 # will contain the name of the next/previous section/chapter.
782 sub lilypond_print_navigation
783 {
784     my $buttons = shift;
785     my $vertical = shift;
786     my $spacing = 1;
787     my $result = "<table class=\"nav_table\">\n";
788
789     $result .= "<tr>" unless $vertical;
790     my $beginofline = 1;
791     foreach my $button (@$buttons)
792     {
793         $result .= qq{<tr valign="top" align="left">\n} if $vertical;
794         # Allow (left|right|center)-aligned-cell and newline as buttons!
795         if ( $button =~ /^(.*)-aligned-cell-(.*)$/ )
796         {
797           $result .= qq{</td>} unless $beginofline;
798           $result .= qq{<td valign="middle" align="$1" colspan="$2">};
799           $beginofline = 0;
800         }
801         elsif ( $button eq 'newline' )
802         {
803           $result .= qq{</td>} unless $beginofline;
804           $result .= qq{</tr>};
805           $result .= qq{<tr>};
806           $beginofline = 1;
807
808         }
809         elsif (ref($button) eq 'CODE')
810         {
811             $result .= &$button($vertical);
812         }
813         elsif (ref($button) eq 'SCALAR')
814         {
815             $result .= "$$button" if defined($$button);
816         }
817         elsif (ref($button) eq 'ARRAY')
818         {
819             my $text = $button->[1];
820             my $button_href = $button->[0];
821             # verify that $button_href is simple text and text is a reference
822             if (defined($button_href) and !ref($button_href) 
823                and defined($text) and (ref($text) eq 'SCALAR') and defined($$text))
824             {             # use given text
825                 if ($Texi2HTML::HREF{$button_href})
826                 {
827                   my $anchor_attributes = '';
828                   if ($USE_ACCESSKEY and (defined($BUTTONS_ACCESSKEY{$button_href})) and ($BUTTONS_ACCESSKEY{$button_href} ne ''))
829                   {
830                       $anchor_attributes = "accesskey=\"$BUTTONS_ACCESSKEY{$button_href}\"";
831                   }
832                   if ($USE_REL_REV and (defined($BUTTONS_REL{$button_href})) and ($BUTTONS_REL{$button_href} ne ''))
833                   {
834                       $anchor_attributes .= " rel=\"$BUTTONS_REL{$button_href}\"";
835                   }
836                   $result .=  "" .
837                         &$anchor('',
838                                     $Texi2HTML::HREF{$button_href},
839                                     get_navigation_text($$text),
840                                     $anchor_attributes
841                                    );
842                 }
843                 else
844                 {
845                   $result .=  get_navigation_text($$text);
846                 }
847             }
848         }
849         elsif ($button eq ' ')
850         {                       # handle space button
851             $result .= 
852                 ($ICONS && $ACTIVE_ICONS{' '}) ?
853                     &$button_icon_img($BUTTONS_NAME{$button}, $ACTIVE_ICONS{' '}) :
854                         $NAVIGATION_TEXT{' '};
855             #next;
856         }
857         elsif ($Texi2HTML::HREF{$button})
858         {                       # button is active
859             my $btitle = $BUTTONS_GOTO{$button} ?
860                 'title="' . $BUTTONS_GOTO{$button} . '"' : '';
861             if ($USE_ACCESSKEY and (defined($BUTTONS_ACCESSKEY{$button})) and ($BUTTONS_ACCESSKEY{$button} ne ''))
862             {
863                 $btitle .= " accesskey=\"$BUTTONS_ACCESSKEY{$button}\"";
864             }
865             if ($USE_REL_REV and (defined($BUTTONS_REL{$button})) and ($BUTTONS_REL{$button} ne ''))
866             {
867                 $btitle .= " rel=\"$BUTTONS_REL{$button}\"";
868             }
869             if ($ICONS && $ACTIVE_ICONS{$button})
870             {                   # use icon
871                 $result .= '' .
872                     &$anchor('',
873                         $Texi2HTML::HREF{$button},
874                         &$button_icon_img($BUTTONS_NAME{$button},
875                                    $ACTIVE_ICONS{$button},
876                                    $Texi2HTML::SIMPLE_TEXT{$button}),
877                         $btitle
878                       );
879             }
880             else
881             {                   # use text
882                 $result .= 
883                     '[' .
884                         &$anchor('',
885                                     $Texi2HTML::HREF{$button},
886                                     get_navigation_text($button),
887                                     $btitle
888                                    ) .
889                                        ']';
890             }
891         }
892         else
893         {                       # button is passive
894             $result .= 
895                 $ICONS && $PASSIVE_ICONS{$button} ?
896                     &$button_icon_img($BUTTONS_NAME{$button},
897                                           $PASSIVE_ICONS{$button},
898                                           $Texi2HTML::SIMPLE_TEXT{$button}) :
899
900                                               "[" . get_navigation_text($button) . "]";
901         }
902         $result .= "</td>\n" if $vertical;
903         $result .= "</tr>\n" if $vertical;
904     }
905     $result .= "</td>" unless $beginofline;
906     $result .= "</tr>" unless $vertical;
907     $result .= "</table>\n";
908     return $result;
909 }
910
911
912 @Texi2HTML::Config::SECTION_BUTTONS =
913     ('left-aligned-cell-1', 'FastBack',
914      'center-aligned-cell-3', 'Top', 'Contents', 'Index', 'About',
915      'right-aligned-cell-1', 'FastForward',
916      'newline',
917      'left-aligned-cell-2', 'Back',
918      'center-aligned-cell-1', 'Up',
919      'right-aligned-cell-2', 'Forward'
920     );
921
922 # buttons for misc stuff
923 @Texi2HTML::Config::MISC_BUTTONS = ('center-aligned-cell-3', 'Top', 'Contents', 'Index', 'About');
924
925 # buttons for chapter file footers
926 # (and headers but only if SECTION_NAVIGATION is false)
927 @Texi2HTML::Config::CHAPTER_BUTTONS =
928     ('left-aligned-cell-1', 'FastBack',
929      'center-aligned-cell-3', 'Top', 'Contents', 'Index', 'About',
930      'right-aligned-cell-1', 'FastForward',
931     );
932
933 # buttons for section file footers
934 @Texi2HTML::Config::SECTION_FOOTER_BUTTONS =
935     ('left-aligned-cell-1', 'FastBack',
936      'center-aligned-cell-3', 'Top', 'Contents', 'Index', 'About',
937      'right-aligned-cell-1', 'FastForward',
938      'newline',
939      'left-aligned-cell-2', 'Back',
940      'center-aligned-cell-1', 'Up',
941      'right-aligned-cell-2', 'Forward'
942     );
943
944 @Texi2HTML::Config::NODE_FOOTER_BUTTONS =
945     ('left-aligned-cell-1', 'FastBack',
946      'center-aligned-cell-3', 'Top', 'Contents', 'Index', 'About',
947      'right-aligned-cell-1', 'FastForward',
948      'newline',
949      'left-aligned-cell-2', 'Back',
950      'center-aligned-cell-1', 'Up',
951      'right-aligned-cell-2', 'Forward'
952     );
953
954
955
956
957
958 #############################################################################
959 ###  FOOTNOTE FORMATTING
960 #############################################################################
961
962 # Format footnotes in a nicer way: Instead of printing the number in a separate
963 # (nr) heading line, use the standard way of prepending <sup>nr</sup> immediately
964 # before the fn text.
965
966
967 # The following code is copied from texi2html's examples/makeinfo.init and
968 # should be updated when texi2html makes some changes there!
969
970 my $makekinfo_like_footnote_absolute_number = 0;
971
972 sub makeinfo_like_foot_line_and_ref($$$$$$$$)
973 {
974     my $foot_num = shift;
975     my $relative_num = shift;
976     my $footid = shift;
977     my $docid = shift;
978     my $from_file = shift;
979     my $footnote_file = shift;
980     my $lines = shift;
981     my $state = shift;
982
983     $makekinfo_like_footnote_absolute_number++;
984
985     # this is a bit obscure, this allows to add an anchor only if formatted
986     # as part of the document.
987     $docid = '' if ($state->{'outside_document'} or $state->{'multiple_pass'});
988
989     if ($from_file eq $footnote_file)
990     {
991         $from_file = $footnote_file = '';
992     }
993
994     my $foot_anchor = "<sup>" . &$anchor($docid, "$footnote_file#$footid", $relative_num) . "</sup>";
995     $foot_anchor = &$anchor($docid, "$footnote_file#$footid", "($relative_num)") if ($state->{'preformatted'});
996
997 #    unshift @$lines, "<li>";
998 #    push @$lines, "</li>\n";
999     return ($lines, $foot_anchor);
1000 }
1001
1002 sub makeinfo_like_foot_lines($)
1003 {
1004     my $lines = shift;
1005     unshift @$lines, "<hr>\n<h4>$Texi2HTML::I18n::WORDS->{'Footnotes_Title'}</h4>\n";
1006 #<ol type=\"1\">\n";
1007 #    push @$lines, "</ol>";
1008     return $lines;
1009 }
1010
1011 my %makekinfo_like_paragraph_in_footnote_nr;
1012
1013 sub makeinfo_like_paragraph ($$$$$$$$$$$$$)
1014 {
1015     my $text = shift;
1016     my $align = shift;
1017     my $indent = shift;
1018     my $paragraph_command = shift;
1019     my $paragraph_command_formatted = shift;
1020     my $paragraph_number = shift;
1021     my $format = shift;
1022     my $item_nr = shift;
1023     my $enumerate_style = shift;
1024     my $number = shift;
1025     my $command_stack_at_end = shift;
1026     my $command_stack_at_begin = shift;
1027     my $state = shift;
1028 #print STDERR "format: $format\n" if (defined($format));
1029 #print STDERR "paragraph @$command_stack_at_end; @$command_stack_at_begin\n";
1030     $paragraph_command_formatted = '' if (!defined($paragraph_command_formatted) or
1031           exists($special_list_commands{$format}->{$paragraph_command}));
1032     return '' if ($text =~ /^\s*$/);
1033     foreach my $style(t2h_collect_styles($command_stack_at_begin))
1034     {
1035        $text = t2h_begin_style($style, $text);
1036     }
1037     foreach my $style(t2h_collect_styles($command_stack_at_end))
1038     {
1039        $text = t2h_end_style($style, $text);
1040     }
1041     if (defined($paragraph_number) and defined($$paragraph_number))
1042     {
1043          $$paragraph_number++;
1044          return $text  if (($format eq 'itemize' or $format eq 'enumerate') and
1045             ($$paragraph_number == 1));
1046     }
1047     my $open = '<p';
1048     if ($align)
1049     {
1050         $open .= " align=\"$paragraph_style{$align}\"";
1051     }
1052     my $footnote_text = '';
1053     if (defined($command_stack_at_begin->[0]) and $command_stack_at_begin->[0] eq 'footnote')
1054     {
1055         my $state = $Texi2HTML::THISDOC{'state'};
1056         $makekinfo_like_paragraph_in_footnote_nr{$makekinfo_like_footnote_absolute_number}++;
1057         if ($makekinfo_like_paragraph_in_footnote_nr{$makekinfo_like_footnote_absolute_number} <= 1)
1058         {
1059            $open.=' class="footnote"';
1060            my $document_file = $state->{'footnote_document_file'};
1061            if ($document_file eq $state->{'footnote_footnote_file'})
1062            {
1063                $document_file = '';
1064            }
1065            my $docid = $state->{'footnote_place_id'};
1066            my $doc_state = $state->{'footnote_document_state'};
1067            $docid = '' if ($doc_state->{'outside_document'} or $doc_state->{'multiple_pass'});
1068            my $foot_label = &$anchor($state->{'footnote_footnote_id'},
1069                  $document_file . "#$state->{'footnote_place_id'}",
1070                  "$state->{'footnote_number_in_page'}");
1071            $footnote_text = "<small>[${foot_label}]</small> ";
1072         }
1073     }
1074     return $open.'>'.$footnote_text.$text.'</p>';
1075 }
1076
1077
1078 #############################################################################
1079 ###  OTHER SETTINGS
1080 #############################################################################
1081
1082 # For split pages, use index.html as start page!
1083 if ($Texi2HTML::Config::SPLIT eq 'section') {
1084   $Texi2HTML::Config::TOP_FILE = 'index.html';
1085 }
1086
1087
1088 return 1;