# -*-perl-*-
######################################################################
# File: mediawiki.init
#
# Override values for various customizable procedures are set in this file
# in such a way as to create text suitable for pasting into a MediaWiki.
#
# Load the file with command-line 
# option -init-file mediawiki.init
#
# $Id: mediawiki.init,v 1.12 2008/11/03 12:33:16 pertusus Exp $

######################################################################
# The following variables can also be set by command-line options
#
#
# The default values are set in this file, texi2html.init and the content
# of this file is included at the beginning of the texi2html script file. 
# Those values may be overrided by values set in $sysconfdir/texi2htmlrc 
# and then by values set in $HOME/texi2htmlrc.
#
# command line switches may override these values, and values set in files
# specified by -init-file are also taken into account.
# values set in these files overwrite values set by the command-line
# options appearing before -init-file and might still be overwritten by
# command-line arguments following the -init-file option.

# -number | -nonumber
# if this is set the sections are numbered, and section names and numbers 
# are used in references and menus (instead of node names).
$NUMBER_SECTIONS = 0;

# -separated-footnotes
# if this is set footnotes are on a separated page. Otherwise they are at
# the end of each file (if the document is split).
$SEPARATED_FOOTNOTES = 1;

# extension
$EXTENSION = undef;

# extension for nodes files when NODE_FILES is true
$NODE_FILE_EXTENSION = "";	    

# Use "title: section" name as the file name.
$SECTION_AS_FILE_NAME = 1;

# if set and $SPLIT is set, then split index pages at the next letter
# after they have more than that many entries
undef $SPLIT_INDEX;

# Use preformatted menus.
$SIMPLE_MENU = 1;

push @command_handler_init, \&mediawiki_initialize_variables;

my %doc_nr_to_file; # File name cache based on file index.
sub mediawiki_initialize_variables()
{
    %doc_nr_to_file = (); # File name cache based on file index.
}

###################################################################
# Layout of standard header and footer
#

$print_page_head	      = \&mediawiki_print_page_head;
$print_page_foot	      = \&mediawiki_print_page_foot;
$program_string		      = \&mediawiki_program_string;

sub mediawiki_print_page_head($)
{
    my $fh = shift;
    print $fh "$AFTER_BODY_OPEN\n" if $AFTER_BODY_OPEN;
}

sub mediawiki_program_string()
{
    my $user = $Texi2HTML::THISDOC{'user'};
    my $date = $Texi2HTML::THISDOC{'today'};
    $user = '' if (!defined($user));
    $date = '' if (!defined($date));
    if (($user ne '') and ($date ne ''))
    {
        return  &$I('This document was generated by @emph{%{user}} on @emph{%{date}} using @uref{%{program_homepage}, @emph{%{program}}}.', {
           'user' => $user, 'date' => $date, 'program_homepage' => $Texi2HTML::THISDOC{'program_homepage'}, 'program' => $Texi2HTML::THISDOC{'program'} });
    }
    elsif ($user ne '')
    {
        return  &$I('This document was generated by @emph{%{user}} using @uref{%{program_homepage}, @emph{%{program}}}.', {
           'user' => $user, 'program_homepage' => $Texi2HTML::THISDOC{'program_homepage'}, 'program' => $Texi2HTML::THISDOC{'program'} });
    }
    elsif ($date ne '')
    {
        return  &$I('This document was generated on @i{%{date}} using @uref{%{program_homepage}, @i{%{program}}}.', {
           'date' => $date, 'program_homepage' => $Texi2HTML::THISDOC{'program_homepage'}, 'program' => $Texi2HTML::THISDOC{'program'} });
    }
    return &$I('This document was generated using @uref{%{program_homepage}, @emph{%{program}}}.', {
       'program_homepage' => $Texi2HTML::THISDOC{'program_homepage'}, 'program'
=> $Texi2HTML::THISDOC{'program'} });
}

sub mediawiki_print_page_foot($)
{
    my $fh = shift;
    my $program_string = &$program_string();
    print $fh $program_string, "\n";
    print $fh $PRE_BODY_CLOSE, "\n" if $PRE_BODY_CLOSE;
}



# This function produces an anchor 
#
# arguments:
# $name           :   anchor name
# $href           :   anchor href
# $text           :   text displayed
# extra_attribs   :   added to anchor attributes list

$anchor = \&mediawiki_anchor;

sub mediawiki_anchor($;$$$)
{
    my $name = shift;
    my $href = shift;
    my $text = shift;
    my $attributes = shift; # ignored
    $href = '' if !defined $href or $href !~ /\S/;
    $text = '' if !defined $text or $text !~ /\S/;
    return $text if $name eq '' and $href eq '';
    $name = "<div id=\"$name\"></div>" if $name ne '';
    if ($href)
    {
	if ($href =~ /^\w+:/
	    # If the i18n will replace this later, assume it's a full URL.
	    || $href =~ /^%/)
	{
	    $text = " $text" if $text;
    	    $href = "[$href$text]";
	}
	else
	{
	    $text = "|$text" if $text;
    	    $href = "[[$href$text]]";
	}
    }
    else
    {
    	$href = $text;
    }
#print STDERR "!!!$name!$href!$text!$attributes!\n";
    return "$name$href";
}



# When the value begins with & the function with that name is used to do the
#
# Otherwithe the value is the html element used to enclose the text, and if
# there is a " the resulting text is also enclosed within `'

# default is {'args' => ['normal'], 'attribute' => ''},   
$style_map{'titlefont'} = {'function' => \&mediawiki_titlefont};
#$style_map{'option'} = {'args' => ['code'],
#			 'attribute' => 'code',
#			 'quote' => '"'};
#$style_map{'samp'} = {'args' => ['code'],
#		       'attribute' => 'code',
#		       'quote' => '"'};



$print_Top		   = \&mediawiki_print_Top;
$print_misc		   = \&mediawiki_print_misc;
$titlepage                 = \&mediawiki_titlepage;

sub mediawiki_print_Top
{
    my $fh = shift;
    my $has_top_heading = shift;

    # for redefining navigation buttons use:
    # my $buttons = [...];
    # as it is, 'Top', 'Contents', 'Index', 'About' are printed
    my $buttons = \@MISC_BUTTONS;
#    &$print_head_navigation($fh, $buttons);
    my $nw;
    if ($Texi2HTML::THIS_SECTION)
    {
        # if top-level node has content, then print it with extra header
        #print $fh "<h1>$Texi2HTML::NAME{Top}</h1>\n"
        #print $fh "<h1 class=\"settitle\">$Texi2HTML::NAME{Top}</h1>\n"
#        chomp $Texi2HTML::NAME{Top};
#        print $fh "== $Texi2HTML::NAME{Top} ==\n"
#            unless ($has_top_heading);
        $nw = main::print_lines($fh, $Texi2HTML::THIS_SECTION);
    }
    else
    {
        # top-level node is fully enclosed in @ifnothtml
        # print fulltitle, subtitle, author, Overview
        # redo the titlepage with the actual state
        my ($titlepage_text, $titlepage_no_texi, $titlepage_simple_text) = main::do_special_region_lines('titlepage',$Texi2HTML::THISDOC{'state'});
        &$titlepage([],$titlepage_text, $titlepage_no_texi, $titlepage_simple_text); 
        print $fh $Texi2HTML::TITLEPAGE;
        if (@{$Texi2HTML::OVERVIEW})
        {
             print $fh '=== ' . &$I('Overview:') . " ===\n" . "<blockquote>\n";
             my $nw = main::print_lines($fh, $Texi2HTML::OVERVIEW);
             print $fh "</blockquote>\n";
        }
    }
}

sub mediawiki_print_misc
{
    my $fh = shift;
    my $new_file = shift;
    my $misc_page = shift;

    my $buttons = \@MISC_BUTTONS;
    &$print_misc_header($fh, $buttons, $new_file, $misc_page);
    print $fh "== $Texi2HTML::NAME{This} ==\n";
    main::print_lines($fh);
    &$print_misc_footer($fh, $buttons, $new_file);
}

sub mediawiki_titlepage($$$$)
{
    my $titlepage_lines = shift;
    my $titlepage_text = shift;
    my $titlepage_no_texi = shift;
    my $titlepage_simple_text = shift;

    my $result = '';
    if (@{$Texi2HTML::THISDOC{'titles'}} 
        or @{$Texi2HTML::THISDOC{'subtitles'}} 
        or @{$Texi2HTML::THISDOC{'authors'}})
    {     
        foreach my $title (@{$Texi2HTML::THISDOC{'titles'}})
        {
            $result .= '== ' . $title . " ==\n";
        }    
        foreach my $subtitle (@{$Texi2HTML::THISDOC{'subtitles'}})
        {
            $result .= '=== ' . $subtitle . " ===\n";
        }
        foreach my $author (@{$Texi2HTML::THISDOC{'authors'}})
        {
            $result .= '<strong> ' . $author . " </strong><br>\n";
        }
        $result .= "$DEFAULT_RULE\n" if $DEFAULT_RULE;
    }

    $Texi2HTML::TITLEPAGE = $result . $titlepage_text;
}

sub mediawiki_titlefont($$$)
{
    shift;
    my $args = shift;
    return "\n== $args->[0] ==\n" if $args->[0] =~ /\S/;
    return '';
}



# This function formats a footnote reference and the footnote text associated
# with a given footnote.
# The footnote reference is the text appearing in the main document pointing
# to the footnote text.
#
# arguments:
# absolute number of the footnote (in the document)
# relative number of the footnote (in the page)
# identifier for the footnote
# identifier for the footnote reference in the main document
# main document file
# footnote text file
# array with the footnote text lines 
# the state. See menu entry.
#
# returns:
# reference on an array containing the footnote text lines which should
#     have been updated
# the text for the reference pointing on the footnote text

$foot_line_and_ref = \&mediawiki_foot_line_and_ref;
$foot_section      = \&mediawiki_default_foot_section;

sub medaiwiki_foot_line_and_ref($$$$$$$)
{
    my $number_in_doc = shift;
    my $number_in_page = shift;
    my $footnote_id = shift;
    my $place_id = shift;
    my $document_file = shift;
    my $footnote_file = shift;
    my $lines = shift;
    my $state = shift;
    
    unshift (@$lines,
          &$anchor($footnote_id, $document_file . "#$place_id",
                   "($number_in_doc)")
          . "\n");
    return ($lines, &$anchor($place_id,  $footnote_file . "#$footnote_id", 
           "($number_in_doc)"));
}

# formats a group of footnotes.
#
# argument:
# array reference on the footnotes texts lines 
#
# returns an array reference on the group of footnotes lines
sub mediawiki_foot_section($)
{
    my $lines = shift;
    unshift @$lines, "$DEFAULT_RULE\n" if $DEFAULT_RULE;
    unshift @$lines, "==== " . &$I('Footnotes') . " ====\n";
    return $lines; 
}



# This function formats a heading for an element
#
# argument:
# an element. It is a hash reference for a node or a sectionning command.
# The interesting keys are:
# 'text': the heading text
# 'name': the heading text without section number
# 'node': true if it is a node
# 'level': level of the element. 0 for @top, 1 for chapter, heading, 
#      appendix..., 2 for section and so on...
# 'tag_level': the sectionning element name, raisesections and lowersections
#      taken into account
#
# relevant configuration variable:
# $NUMBER_SECTIONS

$heading           = \&mediawiki_heading;

sub mediawiki_heading($$$$$;$$)
{
    my $element = shift;
    my $command = shift;
    my $texi_line = shift;
    my $line = shift;
    my $in_preformatted = shift;
    my $one_section = shift;
    my $element_heading = shift;

    #return '' if (defined($command) and $command eq 'node' and !$element_heading);
    my $level = 3;
    if (!$element->{'node'})
    {
        $level = $element->{'level'};
    }
    $level = 1 if ($level == 0);
    my $text = $element->{'text'};
    if (!$element->{'node'} and (!$NUMBER_SECTIONS))
    {
        $text = $element->{'name'};
    }
    if ($element->{'top'})
    {
        return '' if ($element->{'titlefont'});
        $level = 1;
        $text = $Texi2HTML::NAME{'Top'};
        chomp $text;
    }
    return '' if ($text !~ /\S/);
    my $class = $element->{'tag_level'};
    $class = 'unnumbered' if ($class eq 'top');
    if (defined($element->{'tocid'}) and $TOC_LINKS)
    {
         $text = &$anchor ('', "$Texi2HTML::THISDOC{'toc_file'}#$element->{'tocid'}", $text);
    }
    return (("=" x $level) . "= $text =" . ("=" x $level) . "\n");
}



$print_navigation	      = \&mediawiki_print_navigation;
sub mediawiki_print_navigation
{
    my $buttons = shift;
    my $vertical = shift;
    my $spacing = 1;

    my $result = '<table cellpadding="1" cellspacing="1" border="0">'."\n";

    $result .= "<tr>" unless $vertical;
    for my $button (@$buttons)
    {
        $result .= qq{<tr valign="top" align="left">\n} if $vertical;
        $result .= qq{<td valign="middle" align="left">};

        if (ref($button) eq 'CODE')
        {
            $result .= &$button($vertical);
        }
        elsif (ref($button) eq 'SCALAR')
        {
            $result .= "$$button" if defined($$button);
        }
        elsif (ref($button) eq 'ARRAY')
        {
            my $text = $button->[1];
            my $button_href = $button->[0];
            if (defined($button_href) and !ref($button_href) 
               and defined($text) and (ref($text) eq 'SCALAR') and defined($$text))
            {             # use given text
                if ($Texi2HTML::HREF{$button_href})
                {
                  $result .= "" .
                        &$anchor('',
                                    $Texi2HTML::HREF{$button_href},
                                    $$text
                                   ) 
                                    ;
                }
                else
                {
                  $result .= $$text;
                }
            }
        }
        elsif ($button eq ' ')
        {                       # handle space button
            $result .=
                $ICONS && $ACTIVE_ICONS{' '} ?
                    &$button_icon_img($button, $ACTIVE_ICONS{' '}) :
                        $NAVIGATION_TEXT{' '};
            #next;
        }
        elsif ($Texi2HTML::HREF{$button})
        {                       # button is active
            my $btitle = $BUTTONS_GOTO{$button} ?
                'title="' . ucfirst($BUTTONS_GOTO{$button}) . '"' : '';
            if ($ICONS && $ACTIVE_ICONS{$button})
            {                   # use icon
                $result .= '' .
                    &$anchor('',
                        $Texi2HTML::HREF{$button},
                        &$button_icon_img($button,
                                   $ACTIVE_ICONS{$button},
                                   #$Texi2HTML::NAME{$button}),
                                   $Texi2HTML::NO_TEXI{$button}),
                        $btitle
                      );
            }
            else
            {                   # use text
                $result .= '|' .
                        &$anchor('',
                                    $Texi2HTML::HREF{$button},
                                    $NAVIGATION_TEXT{$button},
                                    $btitle
                                   ) .
                                       '|';
            }
        }
        else
        {                       # button is passive
            $result .=
                $ICONS && $PASSIVE_ICONS{$button} ?
                    &$button_icon_img($button,
                                          $PASSIVE_ICONS{$button},
                                          #$Texi2HTML::NAME{$button}) :
                                          $Texi2HTML::NO_TEXI{$button}) :

                                              "[" . $NAVIGATION_TEXT{$button} . "]";
        }
        $result .= "</td>\n";
        $result .= "</tr>\n" if $vertical;
    }
    $result .= "</tr>" unless $vertical;
    $result .= "</table>\n";
    return $result;
}



$element_file_name = \&mediawiki_element_file_name;

sub mediawiki_element_file_name
{
    my $element = shift;
    my $type = shift;
    my $docu_name = shift;
    my $file;
#print STDERR "!$element!$type!$docu_name!\n";

    if (!$element)
    {
	if ($type =~ /^toc$/)
	{
	    $file = $docu_name . ": Table of Contents";
	}
	elsif ($type =~ /^stoc$/)
	{
	    $file = $docu_name . ": Short Table of Contents";
	}
	elsif ($type =~ /^foot$/)
	{
	    $file = $docu_name . ": Footnotes";
	}
	elsif ($type =~ /^about$/)
	{
	    $file = $docu_name . ": About this Manual";
	}
	elsif ($type =~ /^doc$/)
	{
	    $file = $docu_name;
	}
    }
    elsif (exists $doc_nr_to_file{$element->{'doc_nr'}})
    {
	$file = $doc_nr_to_file{$element->{'doc_nr'}};
	$doc_nr_to_file{$element->{'doc_nr'}} = $file;
    }
    else
    {
	$file = "$docu_name" . ($type ? "" : ": " . $element->{'texi'});
	$doc_nr_to_file{$element->{'doc_nr'}} = $file;
    }
    return $file;
}

# a preformatted region
# arguments:
# $text of the preformatted region
# $pre_style css style
# $class identifier for the preformatted region (example, menu-comment)
# The following is usefull if the preformatted is in an itemize.
# $leading_command is the leading formatting command (like @minus)
# $leading_command_formatted is the leading formatting command formatted
# $preformatted_number is a reference on the number of preformatteds appearing
#    in the format. The value should be increased if a preformatted is done
$preformatted      = \&mediawiki_preformatted;
sub mediawiki_preformatted($$$$$$$$$$)
{
    my $text = shift;
    my $pre_style = shift;
    my $class = shift;
    my $leading_command = shift;
    my $leading_command_formatted = shift;
    my $preformatted_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;

    return '' if ($text eq '');
    $leading_command_formatted = '' if (!defined($leading_command_formatted) or 
          exists($special_list_commands{$format}->{$leading_command}));
    if (defined($preformatted_number) and defined($$preformatted_number))
    {
        $$preformatted_number++;
    }

    my $top_stack = '';
    $top_stack = $command_stack_at_begin->[-1] if (scalar (@$command_stack_at_begin));
    if ($top_stack eq 'multitable')
    {
       $text =~ s/^\s*//;
       $text =~ s/\s*$//;
    }

    return "<pre class=\"$class\"><nowiki>$text</nowiki></pre>";
}



# format an index summary. This is a list of letters linking to the letter
# entries.
#
# arguments:
# array reference containing the formatted alphabetical letters
# array reference containing the formatted non lphabetical letters
$index_summary     = \&mediawiki_index_summary;
sub mediawiki_index_summary($$)
{
    my $alpha = shift;
    my $nonalpha = shift;
    my $join = '';
    my $nonalpha_text = '';
    my $alpha_text = '';
    return "" if !@$nonalpha and !@$alpha;
    $nonalpha_text = join ("", map {"<td>$_</td>"} @$nonalpha) . "\n"
	if @$nonalpha;
    $alpha_text = join ("", @$alpha) . "\n &nbsp; \n"
	if @$alpha;
    return '<table cellpadding="1" cellspacing="1" border="0">'
	   . "<tr><th valign=\"top\">" . &$I('Jump to') .":</th>\n"
    	   . join ("", map {"<td>$_</td>\n"} @$nonalpha, @$alpha),
	   . "</tr></table>\n";
}


## a simple menu entry ref in case we aren't in a standard menu context
#$simple_menu_link  = \&mediawiki_simple_menu_link;

# a menu link. We are always in preformatted because of SIMPLE_MENU.
$menu_link  = \&mediawiki_simple_menu_link;

sub mediawiki_simple_menu_link($$$$$$$)
{
    my $entry = shift;
#    my $preformatted = shift; # We assume this is true.
    my $state = shift;
    my $href = shift;
    my $node = shift;
    my $title = shift;
    my $ending = shift;
    my $has_title = shift;
    my $command_stack = shift;
    my $preformatted = shift;

    $title = '' unless ($has_title);
    $ending = '' unless defined $ending;
    $entry = "</nowiki>";
    $entry .= "$MENU_SYMBOL";
    if ($href)
    {
	$entry .= &$anchor ('', $href, $node);
    }
    else
    {
	$title .= ":" if ($title ne '');
	$entry .= "$title$node";
    }
    $entry .= $ending;
    $entry .= "<nowiki>";
    return $entry;
}
