#!/usr/bin/env perl
# -*- coding: utf-8; -*-

### texi2html customization script for LilyPond
### Author: Reinhold Kainhofer <reinhold@kainhofer.com>, 2008.
###         Some code parts copied from texi2html and adapted. These functions
###         were written mainly by Patrice Dumas
### License: GPLv3+
###
###
### Features implemented here:
### -) For split manuals, the main page is index.html.
### -) All @unnumbered* sections are placed into the same file
###    (implemented by split_at_numbered_sections)
### -) Use our custom CSS file, with IE-specific fixes in another CSS file,
###    implemented by lilypond_css_lines
### -) TOC (folded, with the current page highlighted) in an overflown <div>
###    is added to every page; implemented by:
###           lilypond_print_page_head -- start <div id="main">
###           lilypond_print_page_foot -- closing id=main, output of footer & TOC
### -) Internal refs are formatted without the 'section ' prefix.
### -) External refs are formatted only as "Text of the node" (not as >>see
###    "NODE" section "SECTION" in "BOOK"<< like with default texi2html). Also,
###    the leading "(book-name)" is removed.
###    Implemented by overriding lilypond_external_ref
### -) Custom navigation bars on top/bottom of the page and between sections;
###    Implemented in lilypond_print_navigation
### -) Different formatting than the default: example uses the same formatting
###    as quote.
### -) Allow translated section titles: All section titles can be translated,
###    the original (English) title is associated with @translationof. This is
###    needed, because the file name / anchor is generated from the original
###    English title, since otherwise language-autoselection would break with
###    posted links.
###    Since it is then no longer possible to obtain the file name from the
###    section title, I keep a sectionname<=>filename/anchor around. This way,
###    xrefs from other manuals can simply load that map and retrieve the
###    correct file name for the link. Implemented in:
###           lilypond_unknown (handling of @translationof, in case
###                             extract_texi_filenames.py messes up...)
###           lilypond_element_file_name (correct file name: use the map)
###           lilypond_element_target_name (correct anchor: use the map)
###           lilypond_init_map (read in the externally created map from disk)
###           lilypond_external_href (load the map for xrefs, use the correct
###                                   link target)
### -) The HTML anchors for all sections are derived from the node name /
###    section title (pre-generated in the .xref-map file). Implemented by:
###           lilypond_element_target_name (adjust section anchors)
### -) Use the standard footnote format "<sup>nr</sup> text" instead of the
###    ugly format of texi2html (<h3>(nr)</h3><p>text</p>). Implemented in
###           makeinfo_like_foot_line_and_ref
###           makeinfo_like_foot_lines
###           makeinfo_like_paragraph
### -) In tables, don't wrap <p> around the contents. Implemented in
###           makeinfo_like_paragraph
###
###
### Useful helper functions:
### -) texinfo_file_name($node_name): returns a texinfo-compatible file name
###    for the given string $node_name (whitespace trimmed/replaced by -,
###    non-standard chars replaced by _xxxx (ascii char code) and forced to
###    start with a letter by prepending t_g if necessary)

package main;
$original_normalise_node = \&normalise_node;

sub t2h_default_normalise_node($)
{
    my $text = shift;
    $original_normalise_node->($text);
}

*normalise_node = sub($)
{
    my $text = shift;
    return &$Texi2HTML::Config::normalise_node($text);
};

package Texi2HTML::Config;
##$normalise_node = \&t2h_default_normalise_node;
$normalise_node = \&lilypond_normalise_node;


use utf8;
use Encode qw(decode);

sub ly_get_language () {
    my $lang = $Texi2HTML::THISDOC{'documentlanguage'};
    # Old key for texi2html-1.82
    $lang = $Texi2HTML::THISDOC{'current_lang'} if !defined $lang;
    return $lang;
}

# Translations declared in lilypond-texi2html-lang.init.

sub ly_get_string () {
    my $lang = ly_get_language ();
    my $string = shift;
    if ($lang and $lang ne "en" and $LY_LANGUAGES->{$lang}->{$string}) {
	return $LY_LANGUAGES->{$lang}->{$string};
    } else {
	return $string;
    }
}


#############################################################################
### FUNCTIONALITY FOR MAIN WEB PAGES
#############################################################################

our $web_manual;

#############################################################################
###  SETTINGS FOR TEXI2HTML
#############################################################################

# Validation fix for texi2html<=1.82
$Texi2HTML::Config::DOCTYPE = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">';

@Texi2HTML::Config::CSS_REFS = (
    {FILENAME => "lilypond-manuals.css", TITLE => "Default style"},
    {FILENAME => "lilypond-highlighting.css"}
    );
@Texi2HTML::Config::ALT_CSS_REFS      = (
    );

sub web_settings() {
  print STDERR "Processing web site: [" . ly_get_language () . "]\n";
  $Texi2HTML::Config::BODYTEXT = "";
  @Texi2HTML::Config::CSS_REFS      = (
      {FILENAME => "lilypond-website.css", TITLE => "Default style"}
      );
  @Texi2HTML::Config::ALT_CSS_REFS      = (
      );
}

$Texi2HTML::Config::USE_ACCESSKEY = 1;
$Texi2HTML::Config::USE_LINKS     = 1;
$Texi2HTML::Config::USE_REL_REV   = 1;
$Texi2HTML::Config::SPLIT_INDEX   = 0;
$Texi2HTML::Config::SEPARATED_FOOTNOTES = 0; # Print footnotes on same page, not separated

$DO_CONTENTS = 1;

# The default has changed to 'class="no-bullet"' in texi2html 5.0.
$NO_BULLET_LIST_CLASS = 'toc';

my $bigpage = 0;
my $have_index_entries = 0;
if ($Texi2HTML::Config::SPLIT eq 'section' or
    $Texi2HTML::Config::SPLIT eq 'node') {
  $Texi2HTML::Config::element_file_name    = \&lilypond_element_file_name;
  $bigpage = 0;
} else {
  $bigpage = 1;
}

$Texi2HTML::Config::anchor  = \&lilypond_anchor;
$Texi2HTML::Config::element_target_name  = \&lilypond_element_target_name;
$default_print_page_head = $Texi2HTML::Config::print_page_head;
$Texi2HTML::Config::print_page_head      = \&lilypond_print_page_head;
$Texi2HTML::Config::print_page_foot      = \&lilypond_print_page_foot;
$Texi2HTML::Config::print_navigation     = \&lilypond_print_navigation;
$Texi2HTML::Config::print_title          = \&lilypond_print_title;
$Texi2HTML::Config::about_body           = sub { return ''; };
$default_internal_ref = $Texi2HTML::Config::internal_ref;
$Texi2HTML::Config::internal_ref         = \&lilypond_internal_ref;
$Texi2HTML::Config::external_ref         = \&lilypond_external_ref;
$default_external_href = $Texi2HTML::Config::external_href;
$Texi2HTML::Config::external_href        = \&lilypond_external_href;
$Texi2HTML::Config::css_lines            = \&lilypond_css_lines;
$default_unknown = $Texi2HTML::Config::unknown;
$Texi2HTML::Config::unknown              = \&lilypond_unknown;
# $Texi2HTML::Config::foot_line_and_ref    = \&lilypond_foot_line_and_ref;
$Texi2HTML::Config::foot_line_and_ref  = \&makeinfo_like_foot_line_and_ref;
$Texi2HTML::Config::foot_lines         = \&makeinfo_like_foot_lines;
$Texi2HTML::Config::paragraph          = \&makeinfo_like_paragraph;



# Examples should be formatted similar to quotes:
$Texi2HTML::Config::complex_format_map->{'example'} = {
  'begin' => q{"<blockquote>"},
  'end' => q{"</blockquote>\n"},
  'style' => 'code',
 };

%Texi2HTML::config::misc_pages_targets = (
   'Overview' => 'Overview',
   'Contents' => 'Contents',
   'About' => 'About'
);


my @section_to_filename;




#############################################################################
###  DEBUGGING
#############################################################################

use Data::Dumper;
$Data::Dumper::Maxdepth = 2;

sub print_element_info($)
{
  my $element = shift;
  print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
  print "Element: $element\n";
  print Dumper($element);
}





#############################################################################
###  HELPER FUNCTIONS
#############################################################################

# only lc() the last portion of an href
sub lc_last($)
{
  my $href = shift;
  my @hrefsplit = split('/', $href);
  # change the last portion (the filename), if it exists;
  # if it is a plain filename with no path, change the string as a whole
  if ($#hrefsplit > 0) {
    @hrefsplit[$#hrefsplit] = lc( @hrefsplit[$#hrefsplit] );
    $href = join("/", @hrefsplit);
  } else {
    $href = lc($href);
  }
  return $href;
}

# Convert a given node name to its proper file name (normalization as explained
# in the texinfo manual:
# http://www.gnu.org/software/texinfo/manual/texinfo/html_node/HTML-Xref-Node-Name-Expansion.html
sub texinfo_file_name($)
{
  my $text = shift;
  my $result = '';
  # File name normalization by texinfo:
  # 1/2: letters and numbers are left unchanged
  # 3/4: multiple, leading and trailing whitespace is removed
  $text = main::normalise_space($text);
  # 5/6: all remaining spaces are converted to '-', all other 7- or 8-bit
  #      chars are replaced by _xxxx (xxxx=ascii character code)
  while ($text ne '') {
    if ($text =~ s/^([A-Za-z0-9]+)//o) { # number or letter stay unchanged
      $result .= $1;
    } elsif ($text =~ s/^ //o) { # space -> '-'
      $result .= '-';
    } elsif ($text =~ s/^(.)//o) { # Otherwise use _xxxx (ascii char code)
      my $ccode = ord($1);
      if ( $ccode <= 0xFFFF ) {
        $result .= sprintf("_%04x", $ccode);
      } else {
        $result .= sprintf("__%06x", $ccode);
      }
    }
  }
  # 7: if name does not begin with a letter, prepend 't_g' (so it starts with a letter)
  if ($result !~ /^[a-zA-Z]/) {
    $result = 't_g' . $result;
  }
  # DONE
  return lc_last($result)
}

# Load a file containing a nodename<=>filename map (tab-sepatared, i.e.
# NODENAME\tFILENAME\tANCHOR
# Returns a ref to a hash "Node title" => ["FilenameWithoutExt", "Anchor"]
sub load_map_file ($)
{
  my $mapfile = shift;
  my $node_map = ();

  # For some unknown reason, Perl on my system (5.10.0 on Fedora 12)
  # refuses to open map files of translated documents with
  # '<:encoding(utf8)', but decoding from UTF-8 line by line works. -jm
  if (open(XREFFILE,'<', $mapfile)) {
    my $line;
    # print STDERR "*** PRINTING MAP FILE LINES ***\n";
    while ( $line = decode ('UTF-8', <XREFFILE>) ) {
      # parse the tab-separated entries and insert them into the map:
      chomp($line);
      my @entries = split(/\t/, $line);
      if (scalar (@entries) == 3) {
	$node_map->{$entries[0]} = [$entries[1], $entries[2]];
	$, = " ";
	# print STDERR @entries;
	# print STDERR "\n";
      } else {
	print STDERR "Invalid entry in the node file $mapfile: $line\n";
      }
    }
    close (XREFFILE);
  } else {
    print STDERR "WARNING: Unable to load the map file $mapfile\n";
  }
  return $node_map;
}


# Split the given path into dir and basename (with .texi removed). Used mainly
# to get the path/basename of the original texi input file
sub split_texi_filename ($)
{
  my $docu = shift;
  my ($docu_dir, $docu_name);
  if ($docu =~ /(.*\/)/) {
    chop($docu_dir = $1);
    $docu_name = $docu;
    $docu_name =~ s/.*\///;
  } else {
     $docu_dir = '.';
     $docu_name = $docu;
  }
  $docu_name =~ s/\.te?x(i|info)?$//;
  return ($docu_dir, $docu_name);
}





#############################################################################
###  CSS HANDLING
#############################################################################

# Include our standard CSS file, not hard-coded CSS code directly in the HTML!
# For IE, add a second conditionally included CSS file.
sub lilypond_css_lines ($$)
{
  my $import_lines = shift;
  my $rule_lines = shift;
  return if (defined($Texi2HTML::THISDOC{'CSS_LINES'}));
  if (@$rule_lines or @$import_lines)
  {
    $Texi2HTML::THISDOC{'CSS_LINES'} = "<style type=\"text/css\">\n<!--\n";
    $Texi2HTML::THISDOC{'CSS_LINES'} .= join('',@$import_lines) . "\n" if (@$import_lines);
    $Texi2HTML::THISDOC{'CSS_LINES'} .= join('',@$rule_lines) . "\n" if (@$rule_lines);
    $Texi2HTML::THISDOC{'CSS_LINES'} .= "-->\n</style>\n";
  }
  foreach my $ref (@CSS_REFS)
  {
    $Texi2HTML::THISDOC{'CSS_LINES'} .=
	"<link rel=\"stylesheet\" type=\"text/css\" title=\"$ref->{TITLE}\" href=\"css/$ref->{FILENAME}\">\n";
  }
  foreach my $ref (@Texi2HTML::Config::ALT_CSS_REFS)
  {
    $Texi2HTML::THISDOC{'CSS_LINES'} .=
	"<link rel=\"alternate stylesheet\" type=\"text/css\" href=\"css/$ref->{FILENAME}\" title=\"$ref->{TITLE}\">\n";
  }
}





#############################################################################
###  SPLITTING BASED ON NUMBERED SECTIONS
#############################################################################

my $lastfilename;
my $docnr = 0;
my $node_to_filename_map = ();
$source_to_translationof_map = ();
our $changes_manual;


# This function makes sure that files are only generated for numbered sections,
# but not for unnumbered ones. It is called after texi2html has done its own
# splitting and simply returns the filename for the node given as first argument
# Nodes with the same filename will be printed out to the same filename, so
# this really all we need. Also, make sure that the file names for sections
# are derived from the section title. We also might want to name the anchors
# according to node titles, which works by simply overriding the id element of
# the $element hash.
# If an external nodename<=>filename/anchor map file is found (loaded in
# the command handler, use the externally created values, otherwise use the
# same logic here.
sub lilypond_element_file_name($$$)
{
  my $element = shift;
  my $type = shift;
  my $docu_name = shift;
  my $docu_ext = $Texi2HTML::Config::EXTENSION;

  my $node_name = main::remove_texi($element->{'node_ref'}->{'texi'});
  # the snippets page does not use nodes for the snippets, so in this case
  # we'll have to use the section name!
  if ($node_name eq '') {
    $node_name = main::remove_texi($element->{'texi'});
  }

  # If we have an entry in the section<=>filename map, use that one, otherwise
  # generate the filename/anchor here. In the latter case, external manuals
  # will not be able to retrieve the file name for xrefs!!! Still, I already
  # had that code, so I'll leave it in in case something goes wrong with the
  # extract_texi_filenames.py script in the lilypond build process!
  if (exists ($node_to_filename_map->{$node_name})) {
    (my $filename, my $anchor) = @{$node_to_filename_map->{$node_name}};
    $filename .= ".$docu_ext" if (defined($docu_ext));
    # don't do lc_last here, otherwise the colors are messed up!
    $filename = lc($filename);

    # unnumbered sections (except those at top-level!) always go to the same
    # file as the previous numbered section
    if (not ($web_manual) and not ($element->{number})
	and not ($lastfilename eq '') and ($element->{level} > 1 or $changes_manual)) {
      $filename = $lastfilename;
    }
    if (($filename eq $lastfilename)) {
      $$element{doc_nr} = $docnr;
    } else {
      $docnr += 1;
      $$element{doc_nr} = $docnr;
      $lastfilename = $filename;
    }
    #print STDERR "Output file name: $filename\n";
    $filename = lc_last($filename);
    return $filename;

  } elsif ($type eq "top" or $type eq "toc" or $type eq "doc" or
	   $type eq "stoc" or $type eq "foot" or $type eq "about") {
    return;
  } else {
    print STDERR "WARNING: Node '$node_name' was NOT found in the map\n"
        unless ($node_name eq '') or ($element->{'tag'} eq 'unnumberedsec')
               or ($node_name =~ /NOT REALLY USED/);

    # Numbered sections will get a filename Node_title, unnumbered sections will use
    # the file name of the previous numbered section:
    if (($element->{number}) or ($lastfilename eq '') or ($element->{level} == 1)) {
      # normalize to the same file name as texinfo
      if ($element->{translationof}) {
        $node_name = main::remove_texi($element->{translationof});
      }
      my $filename = texinfo_file_name($node_name);
      $filename .= ".$docu_ext" if (defined($docu_ext));
      $filename = lc_last($filename);
      $docnr += 1;
      $$element{doc_nr} = $docnr;
      $lastfilename = $filename;
      print STDERR "File name: $filename\n";
      return $filename;
    } else {
      $$element{doc_nr} = $docnr;
      $filename = lc_last($lastfilename);
      print STDERR "File name: $filename\n";
      return $filename;
    }
  }

  return;
}

sub lilypond_normalise_node($)
{
    my $text = shift;
    my $norm = main::t2h_default_normalise_node($text);
    if (exists ($source_to_translationof_map->{$text})) {
	my $original = $source_to_translationof_map->{$text};
	$norm = main::t2h_default_normalise_node($original);
    }

    return $norm;
}

# This function produces an anchor.
#
# arguments:
# $name           :   anchor name
# $href           :   anchor href
# text            :   text displayed
# extra_attribs   :   added to anchor attributes list
sub lilypond_anchor($;$$$)
{
    my $name = shift;
    my $href = shift;
    my $text = shift;
    my $attributes = shift;
    $href = remove_unneeded_anchor($href);
    if (!defined($attributes) or ($attributes !~ /\S/))
    {
        $attributes = '';
    }
    else
    {
        $attributes = ' ' . $attributes;
    }
    $name = '' if (!defined($name) or ($name !~ /\S/));
    $href = '' if (!defined($href) or ($href !~ /\S/));
    $text = '' if (!defined($text));
    return $text if (($name eq '') and ($href eq ''));
    $name = "name=\"$name\"" if ($name ne '');
    $href = "href=\"$href\"" if ($href ne '');
    $href = ' ' . $href if (($name ne '') and ($href ne ''));
    return "<a ${name}${href}${attributes}>$text</a>";
}


sub lilypond_element_target_name($$$)
{
  my $element = shift;
  my $target = shift;
  my $id = shift;
  # Target is based on node name (or sec name for secs without node attached)
  my $node_name = main::remove_texi($element->{'node_ref'}->{'texi'});
  if ($node_name eq '') {
    $node_name = main::remove_texi($element->{'texi'});
  }

  # If we have an entry in the section<=>filename map, use that one, otherwise
  # generate the anchor here.
  if (exists ($node_to_filename_map->{$node_name})) {
    (my $filename, $target) = @{$node_to_filename_map->{$node_name}};
  } else {
    my $anchor = $node_name;
    if ($element->{translationof}) {
      $anchor = main::remove_texi($element->{translationof});
    }
    # normalize to the same file name as texinfo
    $target = texinfo_file_name($anchor);
  }
  # TODO: Once texi2html correctly prints out the target and not the id for
  #       the sections, change this back to ($id, $target)
  # I don't understand this comment, so I'm reluctant to delete it -gp
  $target = lc_last($target);
  $id = lc($target);
# $id =~ s/-1$//i; # remove any trailing "-1"
  return ($target, $id);
}

sub ly_map_filename ($)
{
    my $map_name = shift;
    my $map_filename = main::locate_include_file ($map_name . '.xref-map');
    return $map_filename;
}

## Load the map file for the corrently processed texi file. We do this
#  using a command init handler, since texi2html does not have any
#  other hooks that are called after THISDOC is filled but before phase 2
#  of the texi2html conversion.
sub lilypond_init_map ()
{
    my ($docu_dir, $docu_name) = split_texi_filename ($Texi2HTML::THISDOC{'input_file_name'});
    my $map_filename = ly_map_filename ($docu_name);
    #print STDERR "Map filename is: $map_filename\nDocu name is $docu_name\n";
    if ($docu_name eq 'web') {
	$web_manual = 1;
	web_settings();
    } elsif ($docu_name eq 'changes') {
        $changes_manual = 1;
    }
    $node_to_filename_map = load_map_file ($map_filename);
}
push @Texi2HTML::Config::command_handler_init, \&lilypond_init_map;

sub lilypond_bodytext ()
{
  ## This section makes the manual name visible to CSS through the body tag
  ## so that styles can be applied per manual. It will add the manual
  ## directory name (e.g., 'notation' or 'learning') as a CSS class.

  # Parse the input file name to determine the manual we're dealing with.
  my ($docu_dir, $docu_name) = split_texi_filename ($Texi2HTML::THISDOC{'input_file_name'});

  # Create the extra information for the <body> tag.
  # For example, the development Notation reference in English
  # will output in HTML as <body lang='en' class='notation'>
  my $bodytext = 'lang="' . ly_get_language () . '" class="' . $docu_name . '"';

  $Texi2HTML::THISDOC{'BODYTEXT'} = $bodytext;
  # Set the global config variable for texi2html-1.82 which sets the previous
  # variable at the beginning of init_out.
  $Texi2HTML::Config::BODYTEXT = $bodytext;
}
push @Texi2HTML::Config::command_handler_process, \&lilypond_bodytext;


#############################################################################
###  CLEANER LINK TITLE FOR INTERNAL REFS
#############################################################################

# Never use 'section ' as a prefix to the link text.
#
# Ideally, we would like to simply use command line option `--short-ref`
# instead of providing a customized handler.  Unfortunately, this option
# drops formatting stuff like `<code>` in link texts, so we take a different
# route by setting `$is_section` to false, which has the desired effect.

sub lilypond_internal_ref($$$$$$$)
{
    my $type = shift;
    my $href = shift;
    my $short_name = shift;
    my $name = shift;
    my $is_section = shift;

    $is_section = 0;

    my $args_texi = shift;
    my $formatted_args = shift;

    return &$default_internal_ref ($type, $href, $short_name, $name,
                                   $is_section, $args_texi, $formatted_args);
}


#############################################################################
###  CLEANER LINK TITLE FOR EXTERNAL REFS
#############################################################################

# The default formatting of external refs returns e.g.
# "(lilypond-internals)Timing_translator", so we remove all (...) from the
# file_and_node argument. Also, we want only a very simple format, so we don't
# even call the default handler!
sub lilypond_external_ref($$$$$$)
{
  my $type = shift;
  my $section = shift;
  my $book = shift;
  my $file_node = shift;
  my $href = shift;

  $href = lc_last($href);

  my $cross_ref = shift;
  my $args_texi = shift;
  my $formatted_args = shift;
  my $node = shift;

  # In texi2html-1.82, the node was passed as the section in case that was not
  # available. Since version 5.0, the node is passed as an additional argument.
  if ($section eq '' and defined $node) {
    $section = $node;
  }

  my $displaytext = '';

  # 1) if we have a cross ref name, that's the text to be displayed:
  # 2) For the top node, use the (printable) name of the manual, unless we
  #    have an explicit cross ref name
  # 3) In all other cases use the section name
  if ($cross_ref ne '') {
    $displaytext = $cross_ref;
  } elsif (($section eq '') or ($section eq 'Top')) {
    $displaytext = $book;
  } else {
    $displaytext = $section;
  }

  $displaytext = &$anchor('', $href, $displaytext) if ($displaytext ne '');
  return $displaytext;
}





#############################################################################
###  HANDLING TRANSLATED SECTIONS: handle @translationof, secname<->filename
###                  map stored on disk, xrefs in other manuals load that map
#############################################################################


# Try to make use of @translationof to generate files according to the original
# English section title...
sub lilypond_unknown($$$$$)
{
    my $macro = shift;
    my $line = shift;
    my $pass = shift;
    my $stack = shift;
    my $state = shift;

    # the @translationof macro provides the original English section title,
    # which should be used for file/anchor naming, while the title will be
    # translated to each language
    # It is already used by extract_texi_filenames.py, so this should not be
    # necessary here at all. Still, I'll leave the code in just in case the
    # python script messed up ;-)
    if ($pass == 1 and $macro eq "translationof") {
      if (ref($state->{'element'}) eq 'HASH') {
	  $state->{'element'}->{'translationof'} = main::normalise_space($line);
	  my $source = main::normalise_space ($line);
	  if (ref($state->{'node_ref'}) eq 'HASH') {
	      my $translationof = $state->{'node_ref'}->{'texi'};
	      our %source_to_translationof_map;
	      $source_to_translationof_map->{$source} = $translationof;
	  }
      }
      return ('', 1, undef, undef);
    } else {
      return &$default_unknown($macro, $line, $pass, $stack, $state);
    }
}


my %translated_books = ();
# Construct a href to an external source of information.
# node is the node with texinfo @-commands
# node_id is the node transliterated and transformed as explained in the
#         texinfo manual
# node_xhtml_id is the node transformed such that it is unique and can
#     be used to make an html cross ref as explained in the texinfo manual
# file is the file in '(file)node'
sub lilypond_external_href($$$)
{
  my $node = shift;
  my $node_id = shift;
  my $node_xhtml_id = shift;
  my $file = shift;

  # 1) Keep a hash of book->section_map
  # 2) if not file in keys hash => try to load the map (assign empty map if
  #    non-existent => will load only once!)
  # 3) if node in the section=>(file, anchor) map, replace node_id and
  #    node_xhtml_id by the map's values
  # 4) call the default_external_href with these values (or the old ones if not found)

  if (($node_id ne '') and defined($file) and ($node_id ne 'Top')) {
    my $map_name = $file;
    $map_name =~ s/-big-page//;

    # Load the map if we haven't done so already
    if (!exists($translated_books{$map_name})) {
      $map_filename = ly_map_filename ($map_name);
      $translated_books{$map_name} = load_map_file ($map_filename);
    }

    # look up translation. use these values instead of the old filename/anchor
    my $section_name_map = $translated_books{$map_name};
    my $node_text = main::remove_texi($node);
    if (defined($section_name_map->{$node_text})) {
      ($node_id, $node_xhtml_id) = @{$section_name_map->{$node_text}};
    } else {
      print STDERR "WARNING: Unable to find node '$node_text' in book $map_name.\n";
    }
  }

  if (defined $file) {
    $href = &$default_external_href($node, $node_id, $node_xhtml_id, lc_last($file));
    $href = remove_unneeded_anchor($href);

    if ($web_manual) {
      my $only_web_version = $ENV{ONLY_WEB_VERSION};
      if ($only_web_version) {
        $href = "../../doc/".$only_web_version."/Documentation/web/".$href;
      }
    }

    return $href;
  } else {
    $href = &$default_external_href($node, $node_id, $node_xhtml_id);
    $href = remove_unneeded_anchor($href);
    return $href;
  }
}

sub lilypond_print_title ()
{
  return "";
}

sub remove_unneeded_anchor($)
{
  my $href = shift;
  my @hrefsplit = split("/", $href);
  for ($i = 0; $i < @hrefsplit; $i++) {
    $item = @hrefsplit[$i];
    if ($item =~ /#/) {
      @split = split(".html#", $item);
      if (@split[0] eq @split[1]) {
        @hrefsplit[$i] = @split[0] . ".html";
      }
    }
  }
  $href = join("/", @hrefsplit);
  return $href
}



#############################################################################
###  CUSTOM TOC FOR EACH PAGE (in a frame on the left)
#############################################################################

sub lilypond_print_toc_div ($)
{
    my $fh = shift;

    print $fh "\n\n<div id=\"tocframe\">\n";

    # Remove the leading "GNU LilyPond --- " from the manual title
    my $topname = $Texi2HTML::NAME{'Top'};
    $topname =~ s/^GNU LilyPond(:| &[mn]dash;) //;

    # construct the top-level Docs index (relative path and including language!)
    my $lang = ly_get_language ();
    if ($lang and $lang ne "en") {
      $lang .= ".";
    } else {
      $lang = "";
    }
    my $reldir = $ENV{DEPTH};
    # add a / at the end if there isn't one.
    if (substr ($reldir, -1) ne '/') {
        $reldir .= '/';
    }
    my $uplink = $reldir."Documentation/web/manuals.${lang}html";

    if (not $web_manual) {
      print $fh "<p class=\"toc_uplink\"><a href=\"$uplink\"
         title=\"Documentation Index\">&lt;&lt; " .
	 &ly_get_string ('Back to Documentation Index') .
	 "</a></p>\n";

      print $fh '<h4 class="toc_header"> ' . &$anchor('',
                                    $Texi2HTML::HREF{'Top'},
                                    $topname . " <!-- Sidebar Version Tag  --> ",
                                    'title="Start of the manual"'
                                   ) . "</h4>\n";
    }

    # Find the path to the current element
    my $element = $Texi2HTML::THIS_ELEMENT;
    my %parentelements;
    while ($element and not $element->{'top'}) {
        # The Snippets documentation has @unnumbered at the top level
        # that we do want to have marked as "toc_current". The Changes
        # document consists of only one page.
        # The section on the web pages are special and have no numbering
        # at all, but should still be taken into account.
        if ($element->{'number'} or (not $changes_manual and $element->{'toc_level'} == 1) or $web_manual) {
            $parentelements{$element->{'tocid'}} = 1;
        }
        $element = $element->{'sectionup'};
    }

    foreach my $line (@{$Texi2HTML::TOC_LINES}) {
        if ($line =~ /<a name="(.*)" href/ and $parentelements{$1}) {
            # Copy the line to avoid modifying the original string. More recent
            # versions of Perl (5.14, released in 2011) support non-destructive
            # substitutions via option /r. To support Perl 5.10 in GUB, use the
            # old way of doing it.
            my $current_line = $line;
            $current_line =~ s/<li>/<li class="toc_current">/;
            print $fh $current_line;
        } else {
            print $fh $line;
        }
    }

    local $/=undef;
    my $name = "search-box";
    $lang = ly_get_language ();
    open FILE, "$ENV{TOP_SRC_DIR}/Documentation/$lang/$name.ihtml" or
        open FILE, "$ENV{TOP_SRC_DIR}/Documentation/en/$name.ihtml" or
        die "no such file: $name.ihtml: $!";
    my $search_string = decode ('UTF-8', <FILE>);
    # We depend on an external entity here, which we cannot control.  Suppose
    # we go from 2.15.x to 2.17.x and put the documentation under "v2.17".
    # For some time, Google won't have the new location in its index, so the
    # search would get nothing.  It is better to keep "v2.15" in the search for
    # a while.
    my $search_site = "lilypond.org/doc/v2.24";
    if ($web_manual) {
        $search_site = "lilypond.org";
    }
    $search_string =~ s/\{\{site\}\}/site:$search_site/g;
    print $fh $search_string;
    close FILE;

    print $fh "</div>\n\n";
}

sub lilypond_print_page_head($)
{
    my $fh = shift;
    &$default_print_page_head($fh);
    print $fh "<div id=\"main\">\n";
}

# Print out the TOC in a <div> at the end of th page, which will be formatted as a
# sidebar mimicking a TOC frame
sub lilypond_print_page_foot($)
{
  my $fh = shift;
  my $program_string = &$program_string();
#   print $fh "<p><font size='-1'>$program_string</font><br>$PRE_BODY_CLOSE</p>\n";
  print $fh "<!-- FOOTER -->\n\n";
  print $fh "<!-- end div#main here -->\n</div>\n\n";
  if ($web_manual) {
    # FIXME: This div and p#languages need to be in div#footer.
    #        Should we move this div to postprocess_html.py ?
    print $fh "<div id=\"verifier_texinfo\">\n";
    print $fh "<h3>Validation</h3>\n";
    # FIXME: inlined text substitution, move to ly_get_string as soon as another case is needed
    # this does the variable substitution ("quoting" in Perlish) after the localization
    $hosting_thanks =~ s/(\$\{\w+\})/$1/eeg;
    print $fh "<a href=\"https://validator.w3.org/check?uri=referer\">\n";
    print $fh "<img src=\"https://www.w3.org/Icons/valid-html401\"\n";
    print $fh "     alt=\"Valid HTML 4.01 Transitional\"\n";
    print $fh "     height=\"31\" width=\"88\"></a></p>\n";
    print $fh "</div>";
  }

  # Print the TOC frame after the contents (positioned correctly using CSS),
  # so that browsers with CSS turned off still show the contents first.
  lilypond_print_toc_div ($fh);

  # Close the page:
  print $fh "</body>\n</html>\n";
}





#############################################################################
###  NICER / MORE FLEXIBLE NAVIGATION PANELS
#############################################################################

sub get_navigation_button
{
    my $button = shift;

    my $text = $NAVIGATION_TEXT{$button};
    if (($button eq 'Back') or ($button eq 'FastBack')) {
        $text = $text . $Texi2HTML::NODE{$button} . ' ';
    } elsif (($button eq 'Forward') or ($button eq 'FastForward')) {
        $text = ' ' . $Texi2HTML::NODE{$button} . $text;
    } elsif ($button eq 'Up') {
        $text = $text . ': ' . $Texi2HTML::NODE{$button} . ' ';
    }

    my $attributes = '';
    if ($BUTTONS_GOTO{$button}) {
        $attributes .= 'title="' . $BUTTONS_GOTO{$button} . '"';
    }
    if (defined ($BUTTONS_ACCESSKEY{$button}) and
        ($BUTTONS_ACCESSKEY{$button} ne '')) {
        $attributes .= ' accesskey="' . $BUTTONS_ACCESSKEY{$button} . '"';
    }
    if (defined ($BUTTONS_REL{$button}) and ($BUTTONS_REL{$button} ne '')) {
        $attributes .= ' rel="' . $BUTTONS_REL{$button} . '"';
    }

    return '[' . &$anchor ('', $Texi2HTML::HREF{$button}, $text, $attributes) . ']';
}

sub lilypond_print_navigation
{
    # No navigation buttons for the Changes document and web pages.
    if ($changes_manual or $web_manual) {
        return "\n";
    }

    my $buttons = shift;
    # Compare the button reference with one of the expected values.
    my $chapter_buttons = $buttons == \@CHAPTER_BUTTONS;
    my $section_buttons = (
        ($buttons == \@SECTION_BUTTONS) or
        ($buttons == \@SECTION_FOOTER_BUTTONS) or
        ($buttons == \@NODE_FOOTER_BUTTONS));
    my $result = "<table class=\"nav_table\">\n";

    # First row:
    $result .= '<tr>';
    if ($chapter_buttons or $section_buttons) {
        $result .= '<td align="left">';
        $result .= get_navigation_button ('FastBack');
        $result .= '</td>';
    }
    $result .= '<td align="center">';
    $result .= get_navigation_button ('Top');
    $result .= get_navigation_button ('Contents');
    # Not all manuals have an index.
    if ($Texi2HTML::HREF{'Index'}) {
        $result .= get_navigation_button ('Index');
    }
    $result .= '</td>';
    if ($chapter_buttons or $section_buttons) {
        $result .= '<td align="right">';
        $result .= get_navigation_button ('FastForward');
        $result .= '</td>';
    }
    $result .= "</tr>\n";

    if ($chapter_buttons or $section_buttons) {
        # (Optional) second row:
        $result .= '<tr>';
        $result .= '<td align="left">';
        $result .= get_navigation_button ('Back');
        $result .= '</td>';
        $result .= '<td align="center">';
        $result .= get_navigation_button ('Up');
        $result .= '</td>';
        $result .= '<td align="right">';
        $result .= get_navigation_button ('Forward');
        $result .= '</td>';
        $result .= "</tr>\n";
    }
    $result .= "</table>\n";

    return $result;
}



#############################################################################
###  FOOTNOTE FORMATTING
#############################################################################

# Format footnotes in a nicer way: Instead of printing the number in a separate
# (nr) heading line, use the standard way of prepending <sup>nr</sup> immediately
# before the fn text.


# The following code is copied from texi2html's examples/makeinfo.init and
# should be updated when texi2html makes some changes there!

my $makekinfo_like_footnote_absolute_number = 0;

sub makeinfo_like_foot_line_and_ref($$$$$$$$)
{
    my $foot_num = shift;
    my $relative_num = shift;
    my $footid = shift;
    my $docid = shift;
    my $from_file = shift;
    my $footnote_file = shift;
    my $lines = shift;
    my $state = shift;

    $makekinfo_like_footnote_absolute_number++;

    # this is a bit obscure, this allows to add an anchor only if formatted
    # as part of the document.
    $docid = '' if ($state->{'outside_document'} or $state->{'multiple_pass'});

    if ($from_file eq $footnote_file)
    {
        $from_file = $footnote_file = '';
    }

    my $foot_anchor = "<sup>" .
	&$anchor($docid, "$footnote_file#$footid", $relative_num) . "</sup>";
    $foot_anchor = &$anchor($docid,
			    "$footnote_file#$footid",
			    "($relative_num)") if ($state->{'preformatted'});

#    unshift @$lines, "<li>";
#    push @$lines, "</li>\n";
    return ($lines, $foot_anchor);
}

sub makeinfo_like_foot_lines($)
{
    my $lines = shift;
    unshift @$lines, "<hr>\n<h4>$Texi2HTML::I18n::WORDS->{'Footnotes_Title'}</h4>\n";
#<ol type=\"1\">\n";
#    push @$lines, "</ol>";
    return $lines;
}

my %makekinfo_like_paragraph_in_footnote_nr;

sub makeinfo_like_paragraph ($$$$$$$$$$$$$)
{
    my $text = shift;
    my $align = shift;
    my $indent = shift;
    my $paragraph_command = shift;
    my $paragraph_command_formatted = shift;
    my $paragraph_number = shift;
    my $format = shift;
    my $item_nr = shift;
    my $enumerate_style = shift;
    my $number = shift;
    my $command_stack_at_end = shift;
    my $command_stack_at_begin = shift;
    my $state = shift;
#print STDERR "format: $format\n" if (defined($format));
#print STDERR "paragraph @$command_stack_at_end; @$command_stack_at_begin\n";
    $paragraph_command_formatted = '' if (!defined($paragraph_command_formatted) or
          exists($special_list_commands{$format}->{$paragraph_command}));
    return '' if ($text =~ /^\s*$/);
    foreach my $style(t2h_collect_styles($command_stack_at_begin))
    {
       $text = t2h_begin_style($style, $text);
    }
    foreach my $style(t2h_collect_styles($command_stack_at_end))
    {
       $text = t2h_end_style($style, $text);
    }
    if (defined($paragraph_number) and defined($$paragraph_number))
    {
         $$paragraph_number++;
         return $text  if (($format eq 'itemize' or $format eq 'enumerate') and
            ($$paragraph_number == 1));
    }
    # The cells of a table should not be wrapped in a <p> tag, so just return the text
    if (defined($command_stack_at_begin->[0]) and $command_stack_at_begin->[0] eq 'multitable')
    {
        return $text;
    }

    # Adjust all footnotes so that they look like good old makeinfo
    my $open = '<p';
    if ($align)
    {
        $open .= " align=\"$paragraph_style{$align}\"";
    }
    my $footnote_text = '';
    if (defined($command_stack_at_begin->[0]) and $command_stack_at_begin->[0] eq 'footnote')
    {
        my $state = $Texi2HTML::THISDOC{'state'};
        $makekinfo_like_paragraph_in_footnote_nr{$makekinfo_like_footnote_absolute_number}++;
        if ($makekinfo_like_paragraph_in_footnote_nr{$makekinfo_like_footnote_absolute_number} <= 1)
        {
           $open.=' class="footnote"';
           my $document_file = $state->{'footnote_document_file'};
           if ($document_file eq $state->{'footnote_footnote_file'})
           {
               $document_file = '';
           }
           my $docid = $state->{'footnote_place_id'};
           my $doc_state = $state->{'footnote_document_state'};
           $docid = '' if ($doc_state->{'outside_document'} or $doc_state->{'multiple_pass'});
           my $foot_label = &$anchor($state->{'footnote_footnote_id'},
                 $document_file . "#$state->{'footnote_place_id'}",
                 "$state->{'footnote_number_in_page'}");
           $footnote_text = "<small>[${foot_label}]</small> ";
        }
    }
    return $open.'>'.$footnote_text.$text.'</p>';
}


#############################################################################
###  OTHER SETTINGS
#############################################################################

# For split pages, use index.html as start page!
if ($Texi2HTML::Config::SPLIT eq 'section' or
    $Texi2HTML::Config::SPLIT eq 'node') {
  $Texi2HTML::Config::TOP_FILE = 'index.html';
}


return 1;
