code:
#! /usr/bin/env perl

# texi2any: Texinfo converter.
#
# Copyright 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017
# Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License,
# or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Original author: Patrice Dumas <pertusus@free.fr>
# Parts (also from Patrice Dumas) come from texi2html.pl or texi2html.init.

# for POSIX::setlocale and File::Spec
require 5.00405;

use strict;

# for file names portability
use File::Spec;
# to determine the path separator and null file
use Config;
# for dirname and fileparse
use File::Basename;
#use Cwd;
use Getopt::Long qw(GetOptions);
# for carp
#use Carp;

Getopt::Long::Configure("gnu_getopt");

# This big BEGIN block deals with finding modules and
# some dependencies that we ship
# * in source or
# * installed or
# * installed relative to the script
BEGIN
{
  # emulate -w
  $^W = 1;
  my ($real_command_name, $command_directory, $command_suffix)
     = fileparse($0, '.pl');
  my $updir = File::Spec->updir();

  # These are substituted by the Makefile to create "texi2any".
  my $datadir = '@datadir@';
  my $package = '@PACKAGE@';
  my $packagedir = '@pkglibdir@';

  if ($datadir eq '@' .'datadir@' or $package eq '@' . 'PACKAGE@'
      or $packagedir eq '@' .'pkglibdir@'
      or defined($ENV{'TEXINFO_DEV_SOURCE'})
         and $ENV{'TEXINFO_DEV_SOURCE'} ne '0')
  {
    # Use uninstalled modules

    # To find Texinfo::ModulePath
    if (!defined($ENV{'top_builddir'})) {
      $ENV{'top_builddir'} = File::Spec->catdir($command_directory, $updir);
    }
    unshift @INC, File::Spec->catdir($ENV{'top_builddir'}, 'tp');

    if (defined($ENV{'top_srcdir'})) {
      my $lib_dir = File::Spec->catdir($ENV{'top_srcdir'}, 'tp');
      unshift @INC, $lib_dir;
    }

    require Texinfo::ModulePath;
    Texinfo::ModulePath::init();
  } else {
    # Look for modules in their installed locations.

    my $lib_dir = File::Spec->catdir($datadir, $package);

    # try to make package relocatable, will only work if
    # standard relative paths are used
    if (! -f File::Spec->catfile($lib_dir, 'Texinfo', 'Parser.pm')
        and -f File::Spec->catfile($command_directory, $updir, 'share',
                                   'texinfo', 'Texinfo', 'Parser.pm')) {
      $lib_dir = File::Spec->catdir($command_directory, $updir,
                                          'share', 'texinfo');
    }
    unshift @INC, $lib_dir;

    require Texinfo::ModulePath;
    Texinfo::ModulePath::init($lib_dir, $packagedir);
  }
} # end BEGIN

BEGIN {
  my $enable_xs = '@enable_xs@';
  if ($enable_xs eq 'no') {
    package Texinfo::XSLoader;
    our $disable_XS;
    $disable_XS = 1;
  }
}

use Locale::Messages;
use Texinfo::Common;
use Texinfo::Convert::Converter;

my ($real_command_name, $command_directory, $command_suffix)
   = fileparse($0, '.pl');

# this associates the command line options to the arrays set during
# command line parsing.
my @css_files = ();
my @css_refs = ();
my $cmdline_options = { 'CSS_FILES' => \@css_files,
                        'CSS_REFS' => \@css_refs };

# determine the path separators
my $path_separator = $Config{'path_sep'};
$path_separator = ':' if (!defined($path_separator));
my $quoted_path_separator = quotemeta($path_separator);

# Paths and file names
my $curdir = File::Spec->curdir();
my $updir = File::Spec->updir();

# set by configure, prefix for the sysconfdir and so on
# This could be used in the eval
my $prefix = '@prefix@';
my $datarootdir;
my $sysconfdir;
my $pkgdatadir;
my $datadir;

my $fallback_prefix = File::Spec->catdir(File::Spec->rootdir(), 'usr', 'local');

# We need to eval as $prefix has to be expanded. However when we haven't
# run configure @sysconfdir will be expanded as an array, thus we verify
# whether configure was run or not
if ('@sysconfdir@' ne '@' . 'sysconfdir@') {
  $sysconfdir = eval '"@sysconfdir@"';
} else {
  $sysconfdir = File::Spec->catdir($fallback_prefix, 'etc');
}

if ('@datarootdir@' ne '@' . 'datarootdir@') {
  $datarootdir = eval '"@datarootdir@"';
} else {
  $datarootdir = File::Spec->catdir($fallback_prefix, 'share');
}

if ('@datadir@' ne '@' . 'datadir@' and '@PACKAGE@' ne '@' . 'PACKAGE@') {
  $datadir = eval '"@datadir@"';
  my $package = '@PACKAGE@';
  $pkgdatadir = File::Spec->catdir($datadir, $package);
} else {
  $datadir = File::Spec->catdir($fallback_prefix, 'share');
  $pkgdatadir = File::Spec->catdir($datadir, 'texinfo');
}

# work-around in case libintl-perl do not do it itself
# see http://www.gnu.org/software/gettext/manual/html_node/The-LANGUAGE-variable.html#The-LANGUAGE-variable

if ((defined($ENV{"LC_ALL"}) and $ENV{"LC_ALL"} =~ /^(C|POSIX)$/)
     or (defined($ENV{"LANG"}) and $ENV{"LANG"} =~ /^(C|POSIX)$/)) {
  delete $ENV{"LANGUAGE"} if defined($ENV{"LANGUAGE"});
}

#my $messages_textdomain = 'texinfo';
my $messages_textdomain = '@PACKAGE@';
$messages_textdomain = 'texinfo' if ($messages_textdomain eq '@'.'PACKAGE@');
my $strings_textdomain = '@PACKAGE@' . '_document';
$strings_textdomain = 'texinfo_document'
   if ($strings_textdomain eq '@'.'PACKAGE@' . '_document');

sub __($) {
  my $msgid = shift;
  return Locale::Messages::dgettext($messages_textdomain, $msgid);
}

sub __p($$) {
  my $context = shift;
  my $msgid = shift;
  return Locale::Messages::dpgettext($messages_textdomain, $context, $msgid);
}

my $srcdir;
if (defined($ENV{'top_srcdir'})) {
  $srcdir = File::Spec->catdir($ENV{'top_srcdir'}, 'tp');
} else {
  $srcdir = $command_directory;
}

my $libsrcdir = File::Spec->catdir($srcdir, 'maintain');

# we want a reliable way to switch locale, so we don't use the system
# gettext.
Locale::Messages->select_package('gettext_pp');

#my @search_locale_dirs = ("$datadir/locale", (map $_ . '/LocaleData', @INC),
#  qw (/usr/share/locale /usr/local/share/locale));
my @search_locale_dirs = ();

if (($command_suffix eq '.pl' and !(defined($ENV{'TEXINFO_DEV_SOURCE'})
     and $ENV{'TEXINFO_DEV_SOURCE'} eq 0)) or $ENV{'TEXINFO_DEV_SOURCE'}) {
  # in case of build from the source directory, out of source build,
  # this helps to locate the locales.
  my $locales_dir_found = 0;
  @search_locale_dirs = (
    File::Spec->catdir($libsrcdir, $updir, 'LocaleData'),
    File::Spec->catdir($curdir, 'LocaleData'),
    File::Spec->catdir($updir, $updir, $updir, 'tp', 'LocaleData'),
    File::Spec->catdir($updir, $updir, 'tp', 'LocaleData'));
  foreach my $locales_dir (@search_locale_dirs) {
    if (-d $locales_dir) {
      Locale::Messages::bindtextdomain ($strings_textdomain, $locales_dir);
      # the messages in this domain are not regenerated automatically,
      # only when calling ./maintain/regenerate_perl_module_files.sh
      Locale::Messages::bindtextdomain ($messages_textdomain, $locales_dir);
      $locales_dir_found = 1;
      last;
    }
  }
  if (!$locales_dir_found) {
    warn "Locales dir for document strings not found (@search_locale_dirs)\n";
  }
} else {
  Locale::Messages::bindtextdomain ($strings_textdomain,
                                    File::Spec->catdir($datadir, 'locale'));
  Locale::Messages::bindtextdomain ($messages_textdomain,
                                    File::Spec->catdir($datadir, 'locale'));
}

#Locale::Messages::bindtextdomain ($messages_textdomain,
#                                  File::Spec->catdir($datadir, 'locale'));

# Version setting is complicated, because we cope with
# * script with configure values substituted or not
# * script shipped as part of texinfo or as a standalone perl module

# When shipped as a perl modules, $hardcoded_version is set to undef here
# by a sed one liner.  The consequence is that configure.ac is not used
# to retrieve the version number.
# Otherwise this is only used as a safety value, and should never be used
# in practice as a regexp extracts the version from configure.ac.
my $hardcoded_version = "0.00-hardcoded";
# Version set in configure.ac
my $configured_version = '@PACKAGE_VERSION@';
if ($configured_version eq '@' . 'PACKAGE_VERSION@') {
  # if not configured, and $hardcoded_version is set search for the version
  # in configure.ac
  if (defined($hardcoded_version)) {
    if (open (CONFIGURE,
              "< ".File::Spec->catfile($srcdir, $updir, 'configure.ac'))) {
      while (<CONFIGURE>) {
        if (/^AC_INIT\(\[[^\]]+\]\s*,\s*\[([^\]]+)\]\s*,/) {
          $configured_version = "$1+dev"; # +dev to distinguish from installed
          last;
        }
      }
      close (CONFIGURE);
    }
    # This should never be used, but is a safety value
    $configured_version = $hardcoded_version if (!defined($configured_version));
  } else {
    # used in the standalone perl module, as $hardcoded_version is undef
    # and it should never be configured in that setup
    require Texinfo::Parser;
    $configured_version = $Texinfo::Parser::VERSION;
  }
}

# Compare the version of this file with the version of the modules
# it is using.  If they are different, don't go any further.  This
# can happen if multiple versions of texi2any are installed under a
# different names, e.g. with the --program-suffix option to 'configure'.
# The version in Common.pm is checked because that file has been present
# since Texinfo 5.0 (the first release with texi2any in Perl).
if ($configured_version ne $Texinfo::Common::VERSION
    and $configured_version ne $Texinfo::Common::VERSION."+dev") {
  warn "This is texi2any $configured_version but modules ".
       "for texi2any $Texinfo::Common::VERSION found!\n";
  die "Your installation of Texinfo is broken; aborting.\n";
}

my $configured_package = '@PACKAGE@';
$configured_package = 'Texinfo' if ($configured_package eq '@' . 'PACKAGE@');
my $configured_name = '@PACKAGE_NAME@';
$configured_name = $configured_package
  if ($configured_name eq '@' .'PACKAGE_NAME@');
my $configured_name_version = "$configured_name $configured_version";
my $configured_url = '@PACKAGE_URL@';
$configured_url = 'http://www.gnu.org/software/texinfo/'
  if ($configured_url eq '@' .'PACKAGE_URL@');

my $texinfo_dtd_version = '@TEXINFO_DTD_VERSION@';
# $hardcoded_version is undef for a standalone perl module
if ($texinfo_dtd_version eq '@' . 'TEXINFO_DTD_VERSION@') {
  $texinfo_dtd_version = undef;
  if (defined($hardcoded_version)) {
    if (open (CONFIGURE,
            "< ".File::Spec->catfile($srcdir, $updir, 'configure.ac'))) {
      while (<CONFIGURE>) {
        if (/^TEXINFO_DTD_VERSION=([0-9]\S*)/) {
          $texinfo_dtd_version = "$1";
          last;
        }
      }
      close (CONFIGURE);
    }
  }
}
# Used in case it is not hardcoded in configure and for standalone perl module
$texinfo_dtd_version = $configured_version
  if (!defined($texinfo_dtd_version));

# defaults for options relevant in the main program, not undef, and also
# defaults for all the converters.
# Other relevant options (undef) are NO_WARN FORCE OUTFILE
# Others are set in the converters (SHOW_MENU).
my $converter_default_options = {
    'ERROR_LIMIT' => 100,
    'TEXI2DVI' => 'texi2dvi',
    'PACKAGE_VERSION' => $configured_version,
    'PACKAGE' => $configured_package,
    'PACKAGE_NAME' => $configured_name,
    'PACKAGE_AND_VERSION' => $configured_name_version,
    'PACKAGE_URL' => $configured_url,
    'PROGRAM' => $real_command_name,
    'TEXINFO_DTD_VERSION' => $texinfo_dtd_version,
};

# determine configuration directories.

my $conf_file_name = 'Config' ;
my $texinfo_htmlxref = 'htmlxref.cnf';

# directories for texinfo configuration files
my @language_config_dirs = File::Spec->catdir($curdir, '.texinfo');
push @language_config_dirs, File::Spec->catdir($ENV{'HOME'}, '.texinfo')
                                if (defined($ENV{'HOME'}));
push @language_config_dirs, File::Spec->catdir($sysconfdir, 'texinfo')
                               if (defined($sysconfdir));
push @language_config_dirs, File::Spec->catdir($datadir, 'texinfo')
                               if (defined($datadir));
my @texinfo_config_dirs = ($curdir, @language_config_dirs);

my @program_config_dirs;
my @program_init_dirs;

my $program_name = 'texi2any';
@program_config_dirs = ($curdir, File::Spec->catdir($curdir, ".$program_name"));
push @program_config_dirs, File::Spec->catdir($ENV{'HOME'}, ".$program_name")
       if (defined($ENV{'HOME'}));
push @program_config_dirs, File::Spec->catdir($sysconfdir, $program_name)
       if (defined($sysconfdir));
push @program_config_dirs, File::Spec->catdir($datadir, $program_name)
  if (defined($datadir));

@program_init_dirs = @program_config_dirs;
foreach my $texinfo_config_dir (@language_config_dirs) {
  push @program_init_dirs, File::Spec->catdir($texinfo_config_dir, 'init');
}

# Namespace for configuration
{
package Texinfo::Config;

#use Carp;

# passed from main program
my $cmdline_options;
my $default_options;
# used in main program
our $options = {};

sub _load_config($$) {
  $default_options = shift;
  $cmdline_options = shift;
  #print STDERR "cmdline_options: ".join('|',keys(%$cmdline_options))."\n";
}

sub _load_init_file($) {
  my $file = shift;
  require Texinfo::Convert::HTML;
  eval { require($file) ;};
  my $e = $@;
  if ($e ne '') {
    main::document_warn(sprintf(main::__("error loading %s: %s\n"),
                                 $file, $e));
  }
}

# FIXME: maybe use an opaque return status that can be used to retrieve
# an error message?
sub set_from_init_file($$) {
  my $var = shift;
  my $value = shift;
  if (!Texinfo::Common::valid_option($var)) {
    # carp may be better, but infortunately, it points to the routine that
    # loads the file, and not to the init file.
    main::document_warn(sprintf(main::__("%s: unknown variable %s"),
                                'set_from_init_file', $var));
    return 0;
  } elsif (Texinfo::Common::obsolete_option($var)) {
    main::document_warn(sprintf(main::__("%s: obsolete variable %s\n"),
                                  'set_from_init_file', $var));
  }
  return 0 if (defined($cmdline_options->{$var}));
  delete $default_options->{$var};
  $options->{$var} = $value;
  return 1;
}

sub set_from_cmdline($$) {
  my $var = shift;
  my $value = shift;
  delete $options->{$var};
  delete $default_options->{$var};
  if (!Texinfo::Common::valid_option($var)) {
    main::document_warn(sprintf(main::__("%s: unknown variable %s\n"),
                                'set_from_cmdline', $var));
    return 0;
  } elsif (Texinfo::Common::obsolete_option($var)) {
    main::document_warn(sprintf(main::__("obsolete variable %s\n"),
                                'set_from_cmdline', $var));
  }
  $cmdline_options->{$var} = $value;
  return 1;
}

# This also could get and set some @-command results.
# FIXME But it does not take into account what happens during conversion,
# for that something like $converter->get_conf(...) has to be used.
sub get_conf($) {
  my $var = shift;
  if (exists($cmdline_options->{$var})) {
    return $cmdline_options->{$var};
  } elsif (exists($options->{$var})) {
    return $options->{$var};
  } elsif (exists($default_options->{$var})) {
    return $default_options->{$var};
  } else {
    return undef;
  }
}

}
# back in main program namespace

# file:        file name to locate. It can be a file path.
# directories: a reference on a array containing a list of directories to
#              search the file in.
# all_files:   if true collect all the files with that name, otherwise stop
#              at first match.
sub locate_init_file($$$)
{
  my $file = shift;
  my $directories = shift;
  my $all_files = shift;

  if (File::Spec->file_name_is_absolute($file)) {
    return $file if (-e $file and -r $file);
  } else {
    my @files;
    foreach my $dir (@$directories) {
      next unless (-d $dir);
      my $possible_file = File::Spec->catfile($dir, $file);
      if ($all_files) {
        push (@files, $possible_file)
          if (-e $possible_file and -r $possible_file);
      } else {
        return $possible_file if (-e $possible_file and -r $possible_file);
      }
    }
    return @files if ($all_files);
  }
  return undef;
}

sub locate_and_load_init_file($$)
{
  my $filename = shift;
  my $directories = shift;

  my $file = locate_init_file($filename, $directories, 0);
  if (defined($file)) {
    Texinfo::Config::_load_init_file($file);
  } else {
    document_warn(sprintf(__("could not read init file %s"), $filename));
  }
}

# read initialization files
foreach my $file (locate_init_file($conf_file_name,
                  [ reverse(@program_config_dirs) ], 1)) {
  Texinfo::Config::_load_init_file($file);
}

sub set_from_cmdline($$) {
  return &Texinfo::Config::set_from_cmdline(@_);
}

sub set_from_init_file($$) {
  return &Texinfo::Config::set_from_init_file(@_);
}

sub get_conf($) {
  return &Texinfo::Config::get_conf(@_);
}

my @input_file_suffixes = ('.txi','.texinfo','.texi','.txinfo','');

my @texi2dvi_args = ();

my $format = 'info';
# this is the format associated with the output format, which is replaced
# when the output format changes.  It may also be removed if there is the
# corresponding --no-ifformat.
my $default_expanded_format = [ $format ];
my @conf_dirs = ();
my @include_dirs = ();
my @prepend_dirs = ();

# options for all the files
my $parser_default_options = {'expanded_formats' => [],
                              'values' => {'txicommandconditionals' => 1},
                              'gettext' => \&__,
                              'pgettext' => \&__p,};

Texinfo::Config::_load_config($converter_default_options, $cmdline_options);

sub set_expansion($$) {
  my $region = shift;
  my $set = shift;
  $set = 1 if (!defined($set));
  if ($set) {
    push @{$parser_default_options->{'expanded_formats'}}, $region
      unless (grep {$_ eq $region} @{$parser_default_options->{'expanded_formats'}});
  } else {
    @{$parser_default_options->{'expanded_formats'}} =
      grep {$_ ne $region} @{$parser_default_options->{'expanded_formats'}};
    @{$default_expanded_format}
       = grep {$_ ne $region} @{$default_expanded_format};
  }
}

my $format_from_command_line = 0;

my %format_command_line_names = (
  'xml' => 'texinfoxml',
);

my %formats_table = (
 'info' => {
             'nodes_tree' => 1,
             'floats' => 1,
             'module' => 'Texinfo::Convert::Info'
           },
  'plaintext' => {
             'nodes_tree' => 1,
             'floats' => 1,
             'split' => 1,
             'module' => 'Texinfo::Convert::Plaintext'
           },
  'html' => {
             'nodes_tree' => 1,
             'floats' => 1,
             'split' => 1,
             'internal_links' => 1,
             'simple_menu' => 1,
             'move_index_entries_after_items' => 1,
             'no_warn_non_empty_parts' => 1,
             'module' => 'Texinfo::Convert::HTML'
           },
  'texinfoxml' => {
             'nodes_tree' => 1,
             'module' => 'Texinfo::Convert::TexinfoXML',
             'floats' => 1,
           },
  'texinfosxml' => {
             'nodes_tree' => 1,
             'module' => 'Texinfo::Convert::TexinfoSXML',
             'floats' => 1,
           },
  'ixinsxml' => {
             'nodes_tree' => 1,
             'module' => 'Texinfo::Convert::IXINSXML'
           },
  'docbook' => {
             'move_index_entries_after_items' => 1,
             'no_warn_non_empty_parts' => 1,
             'module' => 'Texinfo::Convert::DocBook'
           },
  'pdf' => {
             'texi2dvi_format' => 1,
           },
  'ps' =>  {
             'texi2dvi_format' => 1,
           },
  'dvi' => {
             'texi2dvi_format' => 1,
           },
  'dvipdf' => {
             'texi2dvi_format' => 1,
           },
  'debugcount' => {
             'nodes_tree' => 1,
             'floats' => 1,
             'module' => 'DebugTexinfo::DebugCount'
           },
  'debugtree' => {
          'split' => 1,
          'module' => 'DebugTexinfo::DebugTree'
         },
  'textcontent' => {
            'converter' => sub{Texinfo::Convert::TextContent->converter(@_)},
           },
  'rawtext' => {
            'converter' => sub{Texinfo::Convert::Text->converter(@_)},
           },
  'plaintexinfo' => {
            'converter' => sub{Texinfo::Convert::PlainTexinfo->converter(@_)},
           },
  'parse' => {
           },
  'structure' => {
             'nodes_tree' => 1,
             'floats' => 1,
             'split' => 1,
           },
);

my $call_texi2dvi = 0;

# previous_format should be in argument if there is a possibility of error.
# as a fallback, the $format global variable is used.
sub set_format($;$$)
{
  my $set_format = shift;
  my $previous_format = shift;
  $previous_format = $format if (!defined($previous_format));
  my $do_not_override_command_line = shift;

  my $new_format;
  if ($format_command_line_names{$set_format}) {
    $new_format = $format_command_line_names{$set_format};
  } else {
    $new_format = $set_format;
  }
  my $expanded_format = $set_format;
  if (!$formats_table{$new_format}) {
    document_warn(sprintf(__("ignoring unrecognized TEXINFO_OUTPUT_FORMAT value `%s'\n"),
                 $new_format));
    $new_format = $previous_format;
  } else {
    if ($format_from_command_line and $do_not_override_command_line) {
      $new_format = $previous_format;
    } else {
      if ($formats_table{$new_format}->{'texi2dvi_format'}) {
        $call_texi2dvi = 1;
        push @texi2dvi_args, '--'.$new_format;
        $expanded_format = 'tex';
      }
      if ($Texinfo::Common::texinfo_output_formats{$expanded_format}) {
        if ($expanded_format eq 'plaintext') {
          $default_expanded_format = [$expanded_format, 'info']
        } else {
          $default_expanded_format = [$expanded_format]
        }
      }
      $format_from_command_line = 1
        unless ($do_not_override_command_line);
    }
  }
  return $new_format;
}

sub set_global_format($)
{
  my $set_format = shift;
  $format = set_format($set_format);
}

sub document_warn($) {
  return if (get_conf('NO_WARN'));
  my $text = shift;
  chomp ($text);
  warn(sprintf(__p("program name: warning: warning_message",
                   "%s: warning: %s\n"), $real_command_name,  $text));
}

sub _exit($$)
{
  my $error_count = shift;
  my $opened_files = shift;

  if ($error_count and $opened_files and !get_conf('FORCE')) {
    while (@$opened_files) {
      my $opened_file = shift (@$opened_files);
      unlink ($opened_file);
    }
  }
  exit (1) if ($error_count and (!get_conf('FORCE')
     or $error_count > get_conf('ERROR_LIMIT')));
}

sub handle_errors($$$)
{
  my $self = shift;
  my $error_count = shift;
  my $opened_files = shift;
  my ($errors, $new_error_count) = $self->errors();
  $error_count += $new_error_count if ($new_error_count);
  foreach my $error_message (@$errors) {
    warn $error_message->{'error_line'} if ($error_message->{'type'} eq 'error'
                                           or !get_conf('NO_WARN'));
  }

  _exit($error_count, $opened_files);
  return $error_count;
}

sub _get_converter_default($)
{
  my $option = shift;
  return $Texinfo::Convert::Converter::all_converters_defaults{$option}
   if (defined($Texinfo::Convert::Converter::all_converters_defaults{$option}));
  return undef;
}

sub makeinfo_help()
{
  my $makeinfo_help =
    sprintf(__("Usage: %s [OPTION]... TEXINFO-FILE...\n"),
    $real_command_name . $command_suffix)
."\n".
__("Translate Texinfo source documentation to various other formats, by default
Info files suitable for reading online with Emacs or standalone GNU Info.

This program is commonly installed as both `makeinfo' and `texi2any';
the behavior is identical, and does not depend on the installed name.\n")
."\n";
  $makeinfo_help .= sprintf(__("General options:
      --document-language=STR locale to use in translating Texinfo keywords
                                for the output document (default C).
      --error-limit=NUM       quit after NUM errors (default %d).
      --force                 preserve output even if errors.
      --help                  display this help and exit.
      --no-validate           suppress node cross-reference validation.
      --no-warn               suppress warnings (but not errors).
      --conf-dir=DIR          search also for initialization files in DIR.
      --init-file=FILE        load FILE to modify the default behavior.
  -c, --set-customization-variable VAR=VAL  set customization variable VAR
                                to value VAL.
  -v, --verbose               explain what is being done.
      --version               display version information and exit.\n"),
    get_conf('ERROR_LIMIT'))
."\n";
  $makeinfo_help .= __("Output format selection (default is to produce Info):
      --docbook               output Docbook XML rather than Info.
      --html                  output HTML rather than Info.
      --plaintext             output plain text rather than Info.
      --xml                   output Texinfo XML rather than Info.
      --dvi, --dvipdf, --ps, --pdf  call texi2dvi to generate given output,
                                after checking validity of TEXINFO-FILE.\n")
."\n";
  $makeinfo_help .= __("General output options:
  -E, --macro-expand=FILE     output macro-expanded source to FILE,
                                ignoring any \@setfilename.
      --no-headers            suppress node separators, Node: lines, and menus
                                from Info output (thus producing plain text)
                                or from HTML (thus producing shorter output).
                                Also, if producing Info, write to
                                standard output by default.
      --no-split              suppress any splitting of the output;
                                generate only one output file.
      --[no-]number-sections  output chapter and sectioning numbers;
                                default is on.
  -o, --output=DEST           output to DEST.
                                With split output, create DEST as a directory
                                 and put the output files there.
                                With non-split output, if DEST is already
                                 a directory or ends with a /,
                                 put the output file there.
                                Otherwise, DEST names the output file.\n")
."\n";
  $makeinfo_help .= sprintf(__("Options for Info and plain text:
      --disable-encoding      do not output accented and special characters
                                in Info output based on \@documentencoding.
      --enable-encoding       override --disable-encoding (default).
      --fill-column=NUM       break Info lines at NUM characters (default %d).
      --footnote-style=STYLE  output footnotes in Info according to STYLE:
                                `separate' to put them in their own node;
                                `end' to put them at the end of the node, in
                                which they are defined (this is the default).
      --paragraph-indent=VAL  indent Info paragraphs by VAL spaces (default %d).
                                If VAL is `none', do not indent; if VAL is
                                `asis', preserve existing indentation.
      --split-size=NUM        split Info files at size NUM (default %d).\n"),
    _get_converter_default('fillcolumn'),
    _get_converter_default('paragraphindent'),
    _get_converter_default('SPLIT_SIZE'))
."\n";
  $makeinfo_help .= __("Options for HTML:
      --css-include=FILE      include FILE in HTML <style> output;
                                read stdin if FILE is -.
      --css-ref=URL           generate CSS reference to URL.
      --internal-links=FILE   produce list of internal links in FILE.
      --split=SPLIT           split at SPLIT, where SPLIT may be `chapter',
                                `section' or `node'.
      --transliterate-file-names  use file names in ASCII transliteration.
      --node-files            produce redirection files for nodes and
                                anchors; default is set only if split.\n")
."\n";
  $makeinfo_help .= __("Options for XML and Docbook:
      --output-indent=VAL     does nothing, retained for compatibility.\n")
."\n";
  $makeinfo_help .= __("Options for DVI/PS/PDF:
      --Xopt=OPT              pass OPT to texi2dvi; can be repeated.\n")
."\n";
  $makeinfo_help .= __("Input file options:
      --commands-in-node-names  does nothing, retained for compatibility.
  -D VAR                        define the variable VAR, as with \@set.
  -D 'VAR VAL'                  define VAR to VAL (one shell argument).
  -I DIR                        append DIR to the \@include search path.
  -P DIR                        prepend DIR to the \@include search path.
  -U VAR                        undefine the variable VAR, as with \@clear.\n")
."\n";
  $makeinfo_help .= __("Conditional processing in input:
  --ifdocbook       process \@ifdocbook and \@docbook even if
                      not generating Docbook.
  --ifhtml          process \@ifhtml and \@html even if not generating HTML.
  --ifinfo          process \@ifinfo even if not generating Info.
  --ifplaintext     process \@ifplaintext even if not generating plain text.
  --iftex           process \@iftex and \@tex.
  --ifxml           process \@ifxml and \@xml.
  --no-ifdocbook    do not process \@ifdocbook and \@docbook text.
  --no-ifhtml       do not process \@ifhtml and \@html text.
  --no-ifinfo       do not process \@ifinfo text.
  --no-ifplaintext  do not process \@ifplaintext text.
  --no-iftex        do not process \@iftex and \@tex text.
  --no-ifxml        do not process \@ifxml and \@xml text.

  Also, for the --no-ifFORMAT options, do process \@ifnotFORMAT text.\n")
."\n";
  $makeinfo_help .= __("  The defaults for the \@if... conditionals depend on the output format:
  if generating Docbook, --ifdocbook is on and the others are off;
  if generating HTML, --ifhtml is on and the others are off;
  if generating Info, --ifinfo is on and the others are off;
  if generating plain text, --ifplaintext is on and the others are off;
  if generating XML, --ifxml is on and the others are off.\n")
."\n";
  $makeinfo_help .= __("Examples:
  makeinfo foo.texi                      write Info to foo's \@setfilename
  makeinfo --html foo.texi               write HTML to \@setfilename
  makeinfo --xml foo.texi                write Texinfo XML to \@setfilename
  makeinfo --docbook foo.texi            write Docbook XML to \@setfilename
  makeinfo --plaintext foo.texi          write plain text to standard output
  makeinfo --pdf foo.texi                write PDF using texi2dvi

  makeinfo --html --no-headers foo.texi  write html without node lines, menus
  makeinfo --number-sections foo.texi    write Info with numbered sections
  makeinfo --no-split foo.texi           write one Info file however big\n")
."\n";
  $makeinfo_help .= __("Email bug reports to bug-texinfo\@gnu.org,
general questions and discussion to help-texinfo\@gnu.org.
Texinfo home page: http://www.gnu.org/software/texinfo/") ."\n";
  return $makeinfo_help;
}

my $Xopt_arg_nr = 0;
my $latex2html_file = 'latex2html.pm';

my $result_options = Getopt::Long::GetOptions (
 'help|h' => sub { print makeinfo_help(); exit 0; },
 'version|V' => sub {print "$program_name (GNU texinfo) $configured_version\n\n";
    printf __("Copyright (C) %s Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.\n"), "2017";
      exit 0;},
 'macro-expand|E=s' => sub { set_from_cmdline('MACRO_EXPAND', $_[1]); },
 'ifhtml!' => sub { set_expansion('html', $_[1]); },
 'ifinfo!' => sub { set_expansion('info', $_[1]); },
 'ifxml!' => sub { set_expansion('xml', $_[1]); },
 'ifdocbook!' => sub { set_expansion('docbook', $_[1]); },
 'iftex!' => sub { set_expansion('tex', $_[1]); },
 'ifplaintext!' => sub { set_expansion('plaintext', $_[1]); },
 'I=s' => sub { push @texi2dvi_args, ('-'.$_[0], $_[1]);
                push @include_dirs, split(/$quoted_path_separator/, $_[1]); },
 'conf-dir=s' => sub { push @conf_dirs, split(/$quoted_path_separator/, $_[1]); },
 'P=s' => sub { unshift @prepend_dirs, split(/$quoted_path_separator/, $_[1]); },
 'number-sections!' => sub { set_from_cmdline('NUMBER_SECTIONS', $_[1]); },
 'number-footnotes!' => sub { set_from_cmdline('NUMBER_FOOTNOTES', $_[1]); },
 'node-files!' => sub { set_from_cmdline('NODE_FILES', $_[1]); },
 'footnote-style=s' => sub {
    if ($_[1] eq 'end' or $_[1] eq 'separate') {
       set_from_cmdline('footnotestyle', $_[1]);
    } else {
      die sprintf(__("%s: --footnote-style arg must be `separate' or `end', not `%s'.\n"), $real_command_name, $_[1]);
    }
  },
 'split=s' => sub {  my $split = $_[1];
                     my @messages
                       = Texinfo::Common::warn_unknown_split($_[1], \&__);
                     if (@messages) {
                       foreach my $message (@messages) {
                         document_warn($message);
                       }
                       $split = 'node';
                     }
                     set_from_cmdline('SPLIT', $split); },
 'no-split' => sub { set_from_cmdline('SPLIT', '');
                     set_from_cmdline('SPLIT_SIZE', undef);},
 'headers!' => sub { set_from_cmdline('HEADERS', $_[1]);
                     set_from_cmdline('SHOW_MENU', $_[1]);
                     $format = 'plaintext' if (!$_[1] and $format eq 'info'); },
 'output|out|o=s' => sub {
    my $var = 'OUTFILE';
    if ($_[1] =~ m:/$: or -d $_[1]) {
      set_from_cmdline($var, undef);
      $var = 'SUBDIR';
    }
    set_from_cmdline($var, $_[1]);
    set_from_cmdline('OUT', $_[1]);
    push @texi2dvi_args, '-o', $_[1];
  },
 'no-validate|no-pointer-validate' => sub {
      set_from_cmdline('novalidate',$_[1]);
      $parser_default_options->{'info'}->{'novalidate'} = $_[1];
    },
 'no-warn' => sub { set_from_cmdline('NO_WARN', $_[1]); },
 'verbose|v!' => sub {set_from_cmdline('VERBOSE', $_[1]);
                     push @texi2dvi_args, '--verbose'; },
 'document-language=s' => sub {
                      set_from_cmdline('documentlanguage', $_[1]);
                      $parser_default_options->{'documentlanguage'} = $_[1];
                      my @messages
                       = Texinfo::Common::warn_unknown_language($_[1], \&__);
                      foreach my $message (@messages) {
                        document_warn($message);
                      }
                    },
 'D=s' => sub {
    my $var = $_[1];
    my @field = split (/\s+/, $var, 2);
    if (@field == 1) {
      $parser_default_options->{'values'}->{$var} = 1;
    } else {
      $parser_default_options->{'values'}->{$field[0]} = $field[1];
    }
 },
 'U=s' => sub {delete $parser_default_options->{'values'}->{$_[1]};},
 'init-file=s' => sub {
    locate_and_load_init_file($_[1], [ @conf_dirs, @program_init_dirs ]);
 },
 'set-customization-variable|c=s' => sub {
   my $var_val = $_[1];
   if ($var_val =~ s/^(\w+)\s*=?\s*//) {
     my $var = $1;
     my $value = $var_val;
     if ($value =~ /^undef$/i) {
       $value = undef;
     }
     # special format
     if ($var eq 'TEXINFO_OUTPUT_FORMAT') {
       $format = set_format($value, $format, 1);
     } elsif ($var eq 'TEXI2HTML') {
       $format = set_format('html');
       $parser_default_options->{'values'}->{'texi2html'} = 1;
     }
     set_from_cmdline($var, $value);
     # FIXME do that here or when all command line options are processed?
     if ($var eq 'L2H' and get_conf('L2H')) {
       locate_and_load_init_file($latex2html_file,
                             [ @conf_dirs, @program_init_dirs ]);
     }
   }
 },
 'css-include=s' => \@css_files,
 'css-ref=s' => \@css_refs,
 'transliterate-file-names!' =>
     sub {set_from_cmdline('TRANSLITERATE_FILE_NAMES', $_[1]);},
 'error-limit|e=i' => sub { set_from_cmdline('ERROR_LIMIT', $_[1]); },
 'split-size=s' => sub {set_from_cmdline('SPLIT_SIZE', $_[1])},
 'paragraph-indent|p=s' => sub {
    my $value = $_[1];
    if ($value =~ /^([0-9]+)$/ or $value eq 'none' or $value eq 'asis') {
      set_from_cmdline('paragraphindent', $_[1]);
    } else {
      die sprintf(__("%s: --paragraph-indent arg must be numeric/`none'/`asis', not `%s'.\n"),
                  $real_command_name, $value);
    }
 },
 'fill-column|f=i' => sub {set_from_cmdline('FILLCOLUMN',$_[1]);},
 'enable-encoding' => sub {set_from_cmdline('ENABLE_ENCODING',$_[1]);
                     $parser_default_options->{'ENABLE_ENCODING'} = $_[1];},
 'disable-encoding' => sub {set_from_cmdline('ENABLE_ENCODING', 0);
                     $parser_default_options->{'ENABLE_ENCODING'} = 0;},
 'internal-links=s' => sub {set_from_cmdline('INTERNAL_LINKS', $_[1]);},
 'force|F' => sub {set_from_cmdline('FORCE', $_[1]);},
 'commands-in-node-names' => sub { ;},
 'output-indent=i' => sub { ;},
 'reference-limit=i' => sub { ;},
 'Xopt=s' => sub {push @texi2dvi_args, $_[1]; $Xopt_arg_nr++},
 'silent|quiet' => sub {set_from_cmdline('SILENT', $_[1]);
                         push @texi2dvi_args, '--'.$_[0];},

 'plaintext' => sub {$format = set_format($_[0].'');},
 'html' => sub {$format = set_format($_[0].'');},
 'info' => sub {$format = set_format($_[0].'');},
 'docbook' => sub {$format = set_format($_[0].'');},
 'xml' => sub {$format = set_format($_[0].'');},
 'dvi' => sub {$format = set_format($_[0].'');},
 'dvipdf' => sub {$format = set_format($_[0].'');},
 'ps' => sub {$format = set_format($_[0].'');},
 'pdf' => sub {$format = set_format($_[0].'');},
 'debug=i' => sub {set_from_cmdline('DEBUG', $_[1]);
                   $parser_default_options->{'DEBUG'} = $_[1];
                   push @texi2dvi_args, '--'.$_[0]; },
);

exit 1 if (!$result_options);

# For tests, set some strings to values not changing with releases
my %test_conf = (
    'PACKAGE_VERSION' => '',
    'PACKAGE' => 'texinfo',
    'PACKAGE_NAME' => 'texinfo',
    'PACKAGE_AND_VERSION' => 'texinfo',
    'PACKAGE_URL' => 'http://www.gnu.org/software/texinfo/',
# maybe don't set this?
    'PROGRAM' => 'texi2any',
);
if (get_conf('TEST')) {
  foreach my $conf (keys (%test_conf)) {
    $converter_default_options->{$conf} = $test_conf{$conf};
  }
}

my %format_names = (
 'info' => 'Info',
 'html' => 'HTML',
 'docbook' => 'DocBook',
 'texinfoxml' => 'Texinfo XML',
 'plaintext' => 'Plain Text',
);

sub format_name($)
{
  my $format = shift;
  if ($format_names{$format}) {
    return $format_names{$format};
  } else {
    return $format;
  }
}

if (defined($ENV{'TEXINFO_OUTPUT_FORMAT'})
    and $ENV{'TEXINFO_OUTPUT_FORMAT'} ne '') {
  $format = set_format($ENV{'TEXINFO_OUTPUT_FORMAT'}, $format, 1);
}

if ($call_texi2dvi) {
  if (defined(get_conf('OUT')) and @ARGV > 1) {
    die sprintf(__('%s: when generating %s, only one input FILE may be specified with -o'."\n"),
                $real_command_name, format_name($format));
  }
} elsif($Xopt_arg_nr) {
  document_warn(__('--Xopt option without printed output'));
}

require Texinfo::Parser;
require Texinfo::Structuring;
require Texinfo::Transformations;
# Avoid loading these modules until down here to speed up the case
# when they are not needed.

my %tree_transformations;
if (get_conf('TREE_TRANSFORMATIONS')) {
  my @transformations = split /,/, get_conf('TREE_TRANSFORMATIONS');
  foreach my $transformation (@transformations) {
    if (Texinfo::Common::valid_tree_transformation($transformation)) {
      $tree_transformations{$transformation} = 1;
    } else {
      document_warn(sprintf(__('unknown tree transformation %s'),
                     $transformation));
    }
  }
}

if (get_conf('SPLIT') and !$formats_table{$format}->{'split'}) {
  document_warn(sprintf(__('ignoring splitting for format %s'),
                        format_name($format)));
  set_from_cmdline('SPLIT', '');
}

foreach my $expanded_format (@{$default_expanded_format}) {
  push @{$parser_default_options->{'expanded_formats'}}, $expanded_format
    unless (grep {$_ eq $expanded_format} @{$parser_default_options->{'expanded_formats'}});
}

my $converter_class;
my %converter_defaults;

if (defined($formats_table{$format}->{'module'})) {
  # Speed up initialization by only loading the module we need.
  eval "require $formats_table{$format}->{'module'};"
      or die "$@";
  eval '$formats_table{$format}->{\'converter\'} = sub{'.
                $formats_table{$format}->{'module'}
        .'->converter(@_)};';
}

# This gets the class right, even though there is a sub...
if (defined($formats_table{$format}->{'converter'})) {
  $converter_class = ref(&{$formats_table{$format}->{'converter'}});
  %converter_defaults = $converter_class->converter_defaults();
}

# FIXME should this be set when the --set is set too?  The corresponding
# code is ready above, but commented out.
# using no warnings is wrong, but a way to avoid a spurious warning.
no warnings 'once';
foreach my $parser_settable_option (
                keys(%Texinfo::Parser::default_customization_values)) {
  if (defined(get_conf($parser_settable_option))) {
    $parser_default_options->{$parser_settable_option}
       = get_conf($parser_settable_option);
  } elsif (defined($converter_class)
           and defined($converter_defaults{$parser_settable_option})) {
    $parser_default_options->{$parser_settable_option}
       = $converter_defaults{$parser_settable_option};
  }
}

## using no warnings is wrong, but a way to avoid a spurious warning.
#no warnings 'once';
# The configuration options are upper-cased when considered as
# customization variables, and lower-cased when passed to the Parser
foreach my $parser_option (map {uc($_)}
                  (keys (%Texinfo::Common::default_parser_state_configuration))) {
  $parser_default_options->{lc($parser_option)} = get_conf($parser_option)
    if (defined(get_conf($parser_option)));
}

# Main processing, process all the files given on the command line

my @input_files = @ARGV;
# use STDIN if not a tty, like makeinfo does
@input_files = ('-') if (!scalar(@input_files) and !-t STDIN);
die sprintf(__("%s: missing file argument.\n"), $real_command_name)
   .sprintf(__("Try `%s --help' for more information.\n"), $real_command_name)
     unless (scalar(@input_files) >= 1);

my $file_number = -1;
my @opened_files = ();
my %unclosed_files;
my $error_count = 0;
# main processing
while(@input_files) {
  $file_number++;
  my $input_file_arg = shift(@input_files);
  my $input_file_name;
  # try to concatenate with different suffixes. The last suffix is ''
  # such that the plain file name is checked.
  foreach my $suffix (@input_file_suffixes) {
    if (-e $input_file_arg.$suffix) {
      $input_file_name = $input_file_arg.$suffix;
      last;
    }
  }
  # in case no file was found, still set the file name
  $input_file_name = $input_file_arg if (!defined($input_file_name));

  my ($input_filename, $input_directory, $suffix) = fileparse($input_file_name);
  if (!defined($input_directory) or $input_directory eq '') {
    $input_directory = $curdir;
  }

  my $input_file_base = $input_file_name;
  $input_file_base =~ s/\.te?x(i|info)?$//;

  my @htmlxref_dirs;
  if (get_conf('TEST')) {
    # to have reproducible tests, do not use system or user
    # directories if TEST is set.
    @htmlxref_dirs = File::Spec->catdir($curdir, '.texinfo');
  } else {
    @htmlxref_dirs = @language_config_dirs;
  }
  if ($input_directory ne '.' and $input_directory ne '') {
    unshift @htmlxref_dirs, $input_directory;
  }
  unshift @htmlxref_dirs, '.';

  my @texinfo_htmlxref_files;
  my $init_file_from_conf = get_conf('HTMLXREF');
  if ($init_file_from_conf) {
    @texinfo_htmlxref_files = ( $init_file_from_conf );
  } else {
    @texinfo_htmlxref_files
      = locate_init_file ($texinfo_htmlxref, \@htmlxref_dirs, 1);
  }

  my $parser_options = { %$parser_default_options };

  $parser_options->{'include_directories'} = [@include_dirs];
  my @prependended_include_directories = ('.');
  push @prependended_include_directories, $input_directory
      if ($input_directory ne '.');
  unshift @{$parser_options->{'include_directories'}},
     @prependended_include_directories;
  unshift @{$parser_options->{'include_directories'}}, @prepend_dirs;

  my $parser = Texinfo::Parser::parser($parser_options);
  my $tree = $parser->parse_texi_file($input_file_name);

  #my $global_commands = $parser->global_commands_information();
  #print STDERR join('|', keys(%$global_commands))."\n";

  if (!defined($tree) or $format eq 'parse') {
    handle_errors($parser, $error_count, \@opened_files);
    next;
  }

  if (defined(get_conf('DUMP_TREE'))
      or (get_conf('DEBUG') and get_conf('DEBUG') >= 10)) {
    # this is very wrong, but a way to avoid a spurious warning.
    no warnings 'once';
    local $Data::Dumper::Purity = 1;
    no warnings 'once';
    local $Data::Dumper::Indent = 1;
    print STDERR Data::Dumper->Dump([$tree]);
  }

  if ($tree_transformations{'fill_gaps_in_sectioning'}) {
    my ($filled_contents, $added_sections)
      = Texinfo::Transformations::fill_gaps_in_sectioning($tree);
    if (!defined($filled_contents)) {
      document_warn(__("fill_gaps_in_sectioning transformation return no result. No section?"));
    } else {
      $tree->{'contents'} = $filled_contents;
    }
  }
  if ((get_conf('SIMPLE_MENU')
       and $formats_table{$format}->{'simple_menu'})
      or $tree_transformations{'simple_menus'}) {
    $parser->Texinfo::Transformations::set_menus_to_simple_menu();
  }

  if (defined(get_conf('MACRO_EXPAND')) and $file_number == 0) {
    require Texinfo::Convert::Texinfo;
    my $texinfo_text = Texinfo::Convert::Texinfo::convert($tree, 1);
    #print STDERR "$texinfo_text\n";
    my $macro_expand_file = get_conf('MACRO_EXPAND');
    my $macro_expand_fh = Texinfo::Common::open_out($parser,
                        $macro_expand_file, $parser->{'INPUT_PERL_ENCODING'});

    my $error_macro_expand_file;
    if (defined($macro_expand_fh)) {
      print $macro_expand_fh $texinfo_text;
      if (!close($macro_expand_fh)) {
        document_warn(sprintf(__("error on closing macro expand file %s: %s\n"),
                              $macro_expand_file, $!));
        $error_macro_expand_file = 1;
      }
      $parser->Texinfo::Convert::Converter::register_close_file($macro_expand_file);
    } else {
      document_warn(sprintf(__("could not open %s for writing: %s\n"),
                            $macro_expand_file, $!));
      $error_macro_expand_file = 1;
    }

    if ($error_macro_expand_file) {
      $error_count++;
      _exit($error_count, \@opened_files);
    }
  }
  if (get_conf('DUMP_TEXI') or $formats_table{$format}->{'texi2dvi_format'}) {
    handle_errors($parser, $error_count, \@opened_files);
    next;
  }

  if ($formats_table{$format}->{'move_index_entries_after_items'}
      or $tree_transformations{'move_index_entries_after_items'}) {
    Texinfo::Common::move_index_entries_after_items_in_tree($tree);
  }

  if ($tree_transformations{'insert_nodes_for_sectioning_commands'}) {
    my ($modified_contents, $added_nodes)
     = Texinfo::Transformations::insert_nodes_for_sectioning_commands($parser, $tree);
    if (!defined($modified_contents)) {
      document_warn(__(
       "insert_nodes_for_sectioning_commands transformation return no result. No section?"));
    } else {
      $tree->{'contents'} = $modified_contents;
    }
  }

  Texinfo::Structuring::associate_internal_references($parser);
  # every format needs the sectioning structure
  # FIXME this adjusts the level of sectioning commands.  Maybe should be
  # done before dumping the tree?
  my $structure = Texinfo::Structuring::sectioning_structure($parser, $tree);

  if ($structure
      and !$formats_table{$format}->{'no_warn_non_empty_parts'}) {
    Texinfo::Structuring::warn_non_empty_parts($parser);
  }

  if ($tree_transformations{'complete_tree_nodes_menus'}) {
    Texinfo::Transformations::complete_tree_nodes_menus($parser, $tree);
  }

  if ($tree_transformations{'regenerate_master_menu'}) {
    Texinfo::Transformations::regenerate_master_menu($parser);
  }

  # this can be done for every format, since information is already gathered
  my $floats = $parser->floats_information();

  my $top_node;
  if ($formats_table{$format}->{'nodes_tree'}) {
    $top_node = Texinfo::Structuring::nodes_tree($parser);
  }
  if ($formats_table{$format}->{'floats'}) {
    Texinfo::Structuring::number_floats($floats);
  }

  $error_count = handle_errors($parser, $error_count, \@opened_files);

  if ($format eq 'structure') {
    next;
  }

  if ($file_number != 0) {
    delete $cmdline_options->{'OUTFILE'} if exists($cmdline_options->{'OUTFILE'});
    delete $cmdline_options->{'OUT'} if exists($cmdline_options->{'OUT'});
    delete $cmdline_options->{'PREFIX'} if exists($cmdline_options->{'PREFIX'});
    delete $cmdline_options->{'SUBDIR'}
      if (exists($cmdline_options->{'SUBDIR'}) and get_conf('SPLIT'));
  }
  my $converter_options = { %$converter_default_options,
                            %$cmdline_options,
                            %$Texinfo::Config::options };

  $converter_options->{'parser'} = $parser;
  $converter_options->{'output_format'} = $format;
  $converter_options->{'htmlxref_files'} = \@texinfo_htmlxref_files;
  my $converter = &{$formats_table{$format}->{'converter'}}($converter_options);
  $converter->output($tree);
  push @opened_files, $converter->converter_opened_files();
  handle_errors($converter, $error_count, \@opened_files);
  my $converter_unclosed_files = $converter->converter_unclosed_files();
  if ($converter_unclosed_files) {
    foreach my $unclosed_file (keys(%$converter_unclosed_files)) {
      if ($unclosed_file eq '-') {
        $unclosed_files{$unclosed_file}
          = $converter_unclosed_files->{$unclosed_file};
      } else {
        if (!close($converter_unclosed_files->{$unclosed_file})) {
          warn(sprintf(__("%s: error on closing %s: %s\n"),
                           $real_command_name, $unclosed_file, $!));
          $error_count++;
          _exit($error_count, \@opened_files);
        }
      }
    }
  }

  if (defined(get_conf('INTERNAL_LINKS')) and $file_number == 0
      and $formats_table{$format}->{'internal_links'}) {
    my $internal_links_text
      = $converter->output_internal_links();
    # always create a file, even if empty.
    $internal_links_text = '' if (!defined($internal_links_text));
    my $internal_links_file = get_conf('INTERNAL_LINKS');
    my $internal_links_fh = Texinfo::Common::open_out($converter,
                                             $internal_links_file);
    my $error_internal_links_file;
    if (defined ($internal_links_fh)) {
      print $internal_links_fh $internal_links_text;

      if (!close ($internal_links_fh)) {
        warn(sprintf(__("%s: error on closing internal links file %s: %s\n"),
                      $real_command_name, $internal_links_file, $!));
        $error_internal_links_file = 1;
      }
      $converter->register_close_file($internal_links_file);
    } else {
      warn(sprintf(__("%s: could not open %s for writing: %s\n"),
                      $real_command_name, $internal_links_file, $!));
      $error_internal_links_file = 1;
    }
    if ($error_internal_links_file) {
      $error_count++;
      _exit($error_count, \@opened_files);
    }
  }
  if (defined(get_conf('SORT_ELEMENT_COUNT')) and $file_number == 0) {
    my $converter_element_count_file
      = Texinfo::Convert::TextContent->converter($converter_options);
    my $use_sections = (! $formats_table{$format}->{'nodes_tree'}
                        or (defined($converter->get_conf('USE_NODES'))
                            and !$converter->get_conf('USE_NODES')));
    my ($sorted_name_counts_array, $sort_element_count_text)
        = Texinfo::Convert::Converter::sort_element_counts(
               $converter_element_count_file, $tree, $use_sections,
                             get_conf('SORT_ELEMENT_COUNT_WORDS'));

    my $sort_element_count_file = get_conf('SORT_ELEMENT_COUNT');
    my $sort_element_count_fh = Texinfo::Common::open_out($converter,
                                             $sort_element_count_file);
    my $error_sort_element_count_file;
    if (defined ($sort_element_count_fh)) {
      print $sort_element_count_fh $sort_element_count_text;

      if (!close ($sort_element_count_fh)) {
        warn(sprintf(__("%s: error on closing internal links file %s: %s\n"),
                      $real_command_name, $sort_element_count_file, $!));
        $error_sort_element_count_file = 1;
      }
      $converter->register_close_file($sort_element_count_file);
    } else {
      warn(sprintf(__("%s: could not open %s for writing: %s\n"),
                    $real_command_name, $sort_element_count_file, $!));
      $error_sort_element_count_file = 1;
    }
    if ($error_sort_element_count_file) {
      $error_count++;
      _exit($error_count, \@opened_files);
    }
  }
}

foreach my $unclosed_file (keys(%unclosed_files)) {
  if (!close($unclosed_files{$unclosed_file})) {
    warn(sprintf(__("%s: error on closing %s: %s\n"),
                     $real_command_name, $unclosed_file, $!));
    $error_count++;
    _exit($error_count, \@opened_files);
  }
}

if ($call_texi2dvi) {
  if (get_conf('DEBUG') or get_conf('VERBOSE')) {
    print STDERR "EXEC ".join('|', (get_conf('TEXI2DVI'), @texi2dvi_args, @ARGV))
       ."\n";
  }
  exec { get_conf('TEXI2DVI') } (get_conf('TEXI2DVI'), @texi2dvi_args, @ARGV);
}

1;


code:
define redo
file texindex
end

set env MALLOC_CHECK_ 2
set env ttests ../../@tests

set args $ttests/bug-texinfo-4.3/gforth.ds

repo_name: mthl/texinfo

license: mit


code:
# $Id$
# Makefile.am for texinfo/util.
# Run automake in .. to produce Makefile.in from this.
#
# Copyright 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015
# Free Software Foundation, Inc.
#
# This file is free software; as a special exception the author gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

bin_SCRIPTS = texi2dvi texi2pdf pdftexi2dvi
nodist_noinst_SCRIPTS = txixml2texi

w32_bat = makeinfo.bat pod2texi.bat texi2any.bat texindex.bat
if HOST_IS_WINDOWS
 bin_SCRIPTS += $(w32_bat)
endif

# for auctex.
pdftexi2dvi: texi2pdf
	cp -f $(srcdir)/texi2pdf $@

txixml2texi: txixml2texi.pl Makefile
	sed -e 's,[@]datadir[@],$(datadir),g' \
	-e 's,[@]PACKAGE[@],$(PACKAGE),g' \
	-e 's,[@]USE_EXTERNAL_LIBINTL[@],$(USE_EXTERNAL_LIBINTL),g' \
	-e 's,[@]USE_EXTERNAL_EASTASIANWIDTH[@],$(USE_EXTERNAL_EASTASIANWIDTH),g' \
	-e 's,[@]USE_EXTERNAL_UNIDECODE[@],$(USE_EXTERNAL_UNIDECODE),g' \
	-e '1 s,/usr/bin/env perl,$(PERL),g' \
	   $(srcdir)/txixml2texi.pl >$@
	chmod a+x $@

localedir = $(datadir)/locale
AM_CPPFLAGS = 					\
  -I$(top_srcdir)				\
  -I$(top_srcdir)/gnulib/lib			\
  -I$(top_builddir)/gnulib/lib			\
  -DLOCALEDIR=\"$(localedir)\"
LDADD = $(top_builddir)/gnulib/lib/libgnu.a $(LIBINTL)

dist_pkgdata_DATA = htmlxref.cnf texinfo.dtd #texinfo.cat

# This fails distcheck:
#texinfo.cat: texinfo-cat.in Makefile
#	sed 's/__VERSION__/$(TEXINFO_DTD_VERSION)/g' $(srcdir)/texinfo-cat.in >$@
# used to be:
#texinfo.cat: texinfo-cat.in $(top_srcdir)/doc/version.texi
#	sed 's/__VERSION__/@VERSION@/g' $(srcdir)/texinfo-cat.in >$@
# Let's try just getting rid of it; not aware of its being used.

# Most of these are for fun.  The only official/installed ones are the
# *texi2* scripts.
#
EXTRA_DIST = README detexinfo dir-example \
  pdftexi2dvi \
  texi2dvi texi2pdf \
  $(dist_pkgdata_DATA) texinfo-cat.in texi-elements-by-size \
  texi2html txixml2texi.pl $(w32_bat) $(TESTS)

DISTCLEANFILES = txixml2texi

# Use 'texinfo.tex' from "$(top_srcdir)/doc"
AM_TESTS_ENVIRONMENT = \
  TEXINPUTS="$(top_srcdir)/doc$(PATH_SEPARATOR)$$TEXINPUTS"; \
  export TEXINPUTS;

TESTS = tests/texi2dvi_helpversion.sh


code:
$Id$
texinfo/util/README

  Copyright 2002, 2008, 2011, 2012, 2013, 2014, 2015 Free Software
  Foundation, Inc.

  Copying and distribution of this file, with or without modification,
  are permitted in any medium without royalty provided the copyright
  notice and this notice are preserved.

All the files here are maintained as part of the Texinfo distribution
(in contrast to the contrib/ directory).

These scripts actually get installed:
  texi2dvi texi2pdf pdftexi2dvi
  (along with *.bat on Windows)
  Also the XML stuff: texinfo.dtd texinfo.cat.

These are examples of wrapping makeinfo invocation to achieve their
various jobs:
  detexinfo texi2html texi-elements-by-size
  txicmdlist txicustomvars txixml2texi

The srclist.txt file specifies common source files to keep in sync; see
the srclist-update script in gnulib.

Finally, the gendocs script and templates (which are not installed) are
about creating all the usual output formats to be put on web pages.
For more, see the GNU Maintainers Information:
http://www.gnu.org/prep/maintain/html_node/Invoking-gendocs_002esh.html

path: util/README


code:
#! /bin/sh
# $Id$
# Copyright 2011, 2012 Free Software Foundation, Inc.
#
# This file is free software; as a special exception the author gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# Original author: Patrice Dumas.

# Script to strip Texinfo commands.  It is so trivial we don't install
# it, but it's in the distribution as an example.
#
exec texi2any --set-customization-variable TEXINFO_OUTPUT_FORMAT=textcontent "$@"

path: util/detexinfo


code:
This is the directory file `dir' a.k.a. `DIR', which contains the
  topmost node of the Info hierarchy.
This particular dir file is merely made available for your hacking
  pleasure, not official or standard in any way.  If it doesn't make sense
  to you, or you don't like it, ignore it.
rms suggested that we follow the categories of the Free Software
  Directory (http://www.gnu.org/directory/) where possible, including
  `minimal' capitalization, that is, just the first word and proper nouns.
If you have dir entries for Texinfo manuals you'd like to be added here,
  please send them to karl@gnu.org.

$Id$

File: dir,	Node: Top,	This is the top of the INFO tree.

This is the Info main menu (aka directory node).
A few useful Info commands:

  `q' quits;
  `H' lists all Info commands;
  `h' starts the Info tutorial;
  `mTexinfo RET' visits the Texinfo manual, etc.

Not all of the topics shown below may be available on this system.

* Menu:

Basics
* BC: (bc).                     Arbitrary precision calculator language.
* Bash: (bash).                 The GNU Bourne-Again SHell.
* Common options: (coreutils)Common options.
* Coreutils: (coreutils).       Core GNU (file, text, shell) utilities.
* DC: (dc).                     Postfix desk calculator.
* Date input formats: (coreutils)Date input formats.
* Ed: (ed).                     The GNU line editor
* File permissions: (coreutils)File permissions.  Access modes.
* Finding files: (find).        Operating on files matching certain criteria.
* Gcal: (gcal).                 GNU calendar program.
* Hello: (hello).               Hello, GNU world.
* Time: (time).                 Measuring program resource usage.

Text creation and manipulation
* Diffutils: (diffutils).       Comparing and merging files.
* Gawk: (gawk).                 A text scanning and processing language.
* M4: (m4).                     A powerful macro processor.
* Perl: (perldoc-all).          Practical Extraction and Report Language.
* Word differences: (wdiff).    GNU wdiff and diff related tools.
* grep: (grep).                 Print lines matching a pattern.
* sed: (sed).                   Stream EDitor.

Texinfo documentation system
* Info: (info).                 How to use the documentation browsing system.
* Texi2HTML: (texi2html).       Texinfo to HTML Converter.
* Texinfo: (texinfo).           The GNU documentation format.
* info standalone: (info-stnd).                 Standalone Info reader.
* install-info: (texinfo)Invoking install-info. Updating info/dir entries.
* makeinfo: (texinfo)Creating an Info File.     Translate Texinfo source.
* texi2dvi: (texinfo)Format with texi2dvi.      Printing Texinfo documentation.
* texindex: (texinfo)Format with tex/texindex.  Sorting Texinfo index files.

Archiving
* Cpio: (cpio).                 Copy-in-copy-out archiver to tape or disk.
* Shar utilities: (sharutils).  Shell archiver, uuencode/uudecode.
* Tar: (tar).                   Making tape (or disk) archives.
* Xorrecord: (xorrecord).       Emulates CD/DVD/BD program cdrecord
* Xorriso: (xorriso).           Burns ISO 9660 on CD, DVD, BD.
* Xorrisofs: (xorrisofs).       Emulates ISO 9660 program mkisofs

Compression
* Gzip: (gzip).                 General (de)compression of files (lzw).
* bzip2: (bzip2).               General (de)compression of files (blocksort).

Editors
* JED: (jed).                   JED editor documentation.
* Screen: (screen).             Terminal multiplexer.

Email
* Anubis: (anubis).             The GNU outgoing mail processor.
* Mailutils: (mailutils).       Utilities & library for mailboxes, protocols.

Graphics
* Netpbm: (netpbm).             Images/graphics manipulation programs.

Network applications
* Gawkinet: (gawkinet).         TCP/IP Internetworking With `gawk'.
* Inetutils: (inetutils).       GNU networking utilities.
* Wget: (wget).                 Non-interactive network downloader.

Printing
* PreScript: (a2ps) PreScript.     Input language for a2ps
* a2ps: (a2ps).                    PostScript Generating Utility
* card: (a2ps) card.               Print Reference Cards
* enscript (enscript).             Text to PostScript.
* fixnt: (a2ps) fixnt.             Fixing Microsoft NT PostScript Files
* fixps: (a2ps) fixps.             Fixing Some Ill Designed PostScript Files
* ogonkify: (ogonkify).            Ogonkify
* pdiff: (a2ps) pdiff.             Produce Pretty Comparison of Files
* psmandup: (a2ps) psmandup.       Printing Duplex on Simplex Printers
* psset: (a2ps) psset.             Inserting calls to setpagedevice

Version control
* CVS: (cvs).                   Concurrent Versions System
* RCS: (rcs).                   GNU Revision Control System.

Software development
* Annotate: (annotate).         The obsolete annotation interface.
* As: (as).                     Assembler.
* Autoconf: (autoconf).         Create source code configuration scripts.
* Automake: (automake).         Making GNU standards-compliant Makefiles.
* Bfd: (bfd).                   The Binary File Descriptor library.
* Binutils: (binutils).         The GNU binary utilities.
* C: (gnu-c-manual).            GNU C reference manual.
* Complexity: (complexity).     Measure complexity of C source.
* Cpp: (cpp).                   The GNU C preprocessor.
* Cpplib: (cppinternals).       Cpplib internals.
* DejaGnu: (dejagnu).           Testing framework.
* Dmalloc: (dmalloc).		Malloc debug library.
* Gdb: (gdb).                   The GNU debugger.
* Gdb-Internals: (gdbint).      The GNU debugger's internals.
* Stabs: (stabs).               The "stabs" debugging information format.
* bison: (bison).               GNU parser generator (Yacc replacement).
* egcs: (egcs).                 Experimental GNU C compiler.
* Flex: (flex).                 A fast scanner generator.
* g++: (gcc).                   The GNU C++ compiler.
* g77: (g77).                   GNU Fortran 77 compiler.
* Gasp: (gasp).                 GNU Assembler preprocessor.
* Gnats: (gnats).               Cygnus bug tracking system.
* Gnulib: (gnulib).             Source files to share among distributions.
* Gperf: (gperf).               Perfect hash function generator.
* Gprof: (gprof).               Profiler.
* Guile Reference: (guile).     The Guile reference manual.
* Guile Tutorial: (guile-tut).	The Guile Tutorial.
* ID database: (id-utils).      Identifier database utilities.
* Indent: (indent).             Prettyprinter for programs.
* Ld: (ld).                     Linker.
* Libtool: (libtool).           Generic library support script.
* Make: (make).                 Remake files automatically.
* PRCS: (prcs).                 Project revision control system.
* Remsync: (remsync).           Remote synchronization of directory trees.
* Send PR: (send-pr).           Cygnus bug reporting for Gnats.
* Source config: (cfg-paper).   Some theory on configuring source packages.
* gcc: (gcc).                   The GNU Compiler Collection.
* gccinstall: (gccinstall).     Installing the GNU Compiler Collection.
* gccint: (gccint).             Internals of the GNU Compiler Collection.
* gdbserver: (gdb) Server.      The GNU debugging server.
* help2man: (help2man).         Automatic manual page generation.
* vc-dwim: (vc-dwim).           VCS-agnostic commit, diff, and change logs.

Emacs
* Emacs: (emacs).               The extensible self-documenting text editor.
* Emacs FAQ: (efaq).            Frequently Asked Questions about Emacs.

Emacs Lisp
* Elisp: (elisp).               The Emacs Lisp Reference Manual.
* Emacs Lisp Intro: (eintr).    Introduction to Emacs Lisp programming.

Emacs editing modes
* Ada mode: (ada-mode).         Emacs mode for editing and compiling Ada code.
* CC Mode: (ccmode).            Emacs mode for editing C, C++, Objective-C,
                                  Java, Pike, AWK, and CORBA IDL code.
* IDLWAVE: (idlwave).           Major mode and shell for IDL files.
* Octave mode: (octave-mode).   Emacs mode for editing GNU Octave files.
* Org Mode: (org).              Outline-based notes management and organizer
* nXML Mode: (nxml-mode).       XML editing mode with RELAX NG support.

Emacs Lisp libraries
* Auth-source: (auth).          The Emacs auth-source library.
* CL: (cl).                     Partial Common Lisp support for Emacs Lisp.
* D-Bus: (dbus).                Using D-Bus in Emacs.
* Emacs MIME: (emacs-mime).     Emacs MIME de/composition library.
* SMTP: (smtpmail).             Emacs library for sending mail via SMTP.
* URL: (url).                   URL loading package.
* Widget: (widget).             The "widget" package used by Customization.

Emacs misc features
* Autotype: (autotype).         Convenient features for text that you enter
                                  frequently in Emacs.
* Bovine: (bovine).             Semantic bovine parser development.
* Calc: (calc).                 Advanced desk calculator and mathematical tool.
* Dired-X: (dired-x).           Dired Extra Features.
* EDE: (ede).                   The Emacs Development Environment.
* EDT: (edt).                   An Emacs emulation of the EDT editor.
* EIEIO: (eieio).               An objects system for Emacs Lisp.
* ERT: (ert).                   Emacs Lisp regression testing tool.
* EWW: (eww).                   Emacs Web Wowser
* EasyPG Assistant: (epa).      An Emacs user interface to GNU Privacy Guard.
* Ebrowse: (ebrowse).           A C++ class browser for Emacs.
* Ediff: (ediff).               A visual interface for comparing and merging
                                  programs.
* Eshell: (eshell).             A command shell implemented in Emacs Lisp.
* Flymake: (flymake).           A universal on-the-fly syntax checker.
* Forms: (forms).               Emacs package for editing data bases by
                                  filling in forms.
* Htmlfontify: (htmlfontify).   Convert source code to html.
* Ido: (ido).                   Interactively do things with buffers and files.
* PCL-CVS: (pcl-cvs).           Emacs front-end to CVS.
* RefTeX: (reftex).             Emacs support for LaTeX cross-references and
                                  citations.
* Remember: (remember).         Simple information manager for Emacs.
* SES: (ses).                   Simple Emacs Spreadsheet.
* SRecode: (srecode).           Semantic template code generator.
* Semantic: (semantic).         Source code parser library and utilities.
* Speedbar: (speedbar).         File/Tag summarizing utility.
* Todo Mode: (todo-mode).       Make and maintain todo lists.
* VIP: (vip).                   An obsolete VI-emulation for Emacs.
* VIPER: (viper).               A VI-emulation mode for Emacs.
* Wisent: (wisent).             Semantic Wisent parser development.
* WoMan: (woman).               Browse UN*X Manual Pages "W.O. (without) Man".

Emacs network features
* ERC: (erc).                   Powerful and extensible IRC client for Emacs.
* EUDC: (eudc).                 Emacs client for directory servers (LDAP, PH).
* Emacs GnuTLS: (emacs-gnutls). The Emacs GnuTLS integration.
* Gnus: (gnus).                 The newsreader Gnus.
* MH-E: (mh-e).                 Emacs interface to the MH mail system.
* Mairix: (mairix-el).          Emacs interface to the Mairix mail indexer.
* Message: (message).           Mail and news composition mode that goes with
                                  Gnus.
* Newsticker: (newsticker).     A Newsticker for Emacs.
* PGG: (pgg).                   Emacs interface to various PGP implementations.
* Rcirc: (rcirc).               Internet Relay Chat (IRC) client.
* SASL: (sasl).                 The Emacs SASL library.
* SC: (sc).                     Supercite lets you cite parts of messages
                                  you’re replying to, in flexible ways.
* Sieve: (sieve).               Managing Sieve scripts in Emacs.
* TRAMP: (tramp).               Transparent Remote Access, Multiple Protocol
                                  Emacs remote file access via ssh and scp.

GNU Gettext Utilities
* ISO3166: (gettext)Country Codes.             ISO 3166 country codes.
* ISO639: (gettext)Language Codes.             ISO 639 language codes.
* autopoint: (gettext)autopoint Invocation.    Copy gettext infrastructure.
* envsubst: (gettext)envsubst Invocation.      Expand environment variables.
* gettext: (gettext).                          GNU gettext utilities.
* gettextize: (gettext)gettextize Invocation.  Prepare a package for gettext.
* msgattrib: (gettext)msgattrib Invocation.    Select part of a PO file.
* msgcat: (gettext)msgcat Invocation.          Combine several PO files.
* msgcmp: (gettext)msgcmp Invocation.          Compare a PO file and template.
* msgcomm: (gettext)msgcomm Invocation.        Match two PO files.
* msgconv: (gettext)msgconv Invocation.        Convert PO file to encoding.
* msgen: (gettext)msgen Invocation.            Create an English PO file.
* msgexec: (gettext)msgexec Invocation.        Process a PO file.
* msgfilter: (gettext)msgfilter Invocation.    Pipe a PO file through a filter.
* msgfmt: (gettext)msgfmt Invocation.          Make MO files out of PO files.
* msggrep: (gettext)msggrep Invocation.        Select part of a PO file.
* msginit: (gettext)msginit Invocation.        Create a fresh PO file.
* msgmerge: (gettext)msgmerge Invocation.      Update a PO file from template.
* msgunfmt: (gettext)msgunfmt Invocation.      Uncompile MO file into PO file.
* msguniq: (gettext)msguniq Invocation.        Unify duplicates for PO file.
* ngettext: (gettext)ngettext Invocation.      Translate a message with plural.
* xgettext: (gettext)xgettext Invocation.      Extract strings into a PO file.

Software libraries
* Annotate: (annotate).         High-level GDB to GUI's.
* Bfd: (bfd).                   The Binary File Descriptor library.
* Gdb-Internals: (gdbint).      The GNU debugger's internals.
* GDB library: (libgdb).        Application programming interface to GDB.
* GDBM: (gdbm).                 Hashed databases.
* GDK: (gdk).                   General drawing kit.
* GTK: (gtk).                   GIMP toolkit.
* History: (history).           Recall previous lines of input.
* Ld internals: (ldint).        GNU linker internals.
* Libc: (libc).                 C library.
* Libextractor: (extractor).    Metadata extraction library.
* libgomp: (libgomp).           GNU OpenMP runtime library
* libitm: (libitm).             GNU Transactional Memory Library
* libquadmath: (libquadmath).   GCC Quad-Precision Math Library
* Mmalloc: (mmalloc).           The GNU mapped-malloc package.
* Stabs: (stabs).               The "stabs" debugging information format.
* Readline: (readline).         General command-line interface.
* Termcap: (termcap).           All about /etc/termcap.

C++ libraries
* Iostream: (iostream).         C++ input/output.
* autosprintf: (autosprintf).   Support for printf format strings in C++.

GNU LilyPond--the music typesetter
* LilyPond Learning Manual: (lilypond-learning).  Start here.
* Music Glossary: (music-glossary).               For non-English users.
* LilyPond: (lilypond-notation).                  LilyPond Notation Reference.
* LilyPond Snippets: (lilypond-snippets).         Short tricks, tips, and examples.
* LilyPond Internals Reference: (lilypond-internals).  Definitions for tweaking.
* LilyPond Application Usage: (lilypond-usage). Installing and running applications.
* LilyPond Website: (lilypond-web).             Preview of new website.
* lilypond: (lilypond-usage)Running lilypond.   Invoking the LilyPond program.
* abc2ly: (lilypond-usage)Invoking abc2ly.      Importing ABC.
* convert-ly: (lilypond-usage)Updating files with convert-ly. Older LilyPond versions.
* etf2ly: (lilypond-usage)Invoking etf2ly.      Importing Finale.
* lilypond-book: (lilypond-usage)lilypond-book. Integrating text and music.
* midi2ly: (lilypond-usage)Invoking midi2ly.          Importing MIDI.
* musicxml2ly: (lilypond-usage)Invoking musicxml2ly.  Importing MusicXML.

Science
* Asymptote: (asymptote).       Vector graphics language.
* Asymptote FAQ: (asy-faq).     FAQ for Asymptote.
* Octave: (octave).             A language for numerical computation.
* R FAQ: (R-FAQ).               The R statistical language FAQ.

System administration
* GSRC: (gsrc).                 Building the GNU Source Release Collection.

TeX
* Dvipng: (dvipng).             DVI to Portable Network Graphics (PNG).
* Dvips: (dvips).               Translating TeX DVI files to PostScript.
* Eplain: (eplain).             Expanding on plain TeX.
* EpsPDF: (epspdf).             Portable GUI&cmdline EPS-to-PDF conversion.
* Kpathsea: (kpathsea).         File lookup along search paths.
* LaTeX2e: (latex2e).           LaTeX2e unofficial reference manual.
* LaTeX2e-es: (latex2e-es).     Spanish translation of latex2e.
* LaTeX2e-fr: (latex2e-fr).     French translation of latex2e.
* Mf2pt1: (mf2pt1).             Make PostScript Type 1 fonts from Metafont.
* Naming TeX fonts: (fontname). Filenames for TeX fonts.
* TDS: (tds).                   Standard TeX directory structure.
* TeXDraw: (texdraw).           Drawing PostScript diagrams within TeX.
* TLbuild: (tlbuild).           TeX Live configuration and development.
* Web2C: (web2c).               TeX, Metafont, and companion programs.

Typesetting
* Font utilities: (fontu).      Programs for font manipulation.
* GV: (gv).                     The GNU PostScript and PDF viewer.
* Groff: (groff).               The GNU troff document formatting system.

Database
* rec-mode: (rec-mode).         Emacs mode for editing recfiles.
* recutils: (recutils).         The GNU Recutils manual.

DOS
* GNUish: (gnuish).             GNU utilities for DOS.
* Mtools: (mtools).             Access DOS disks from Unix.

GNU organization
* Maintain: (maintain).         GNU maintainer guidelines.
* Maintaining Findutils: (find-maint). Maintaining GNU findutils.
* Quality code: (qualitycode).  GNU code quality recommendations.
* Standards: (standards).       GNU coding standards.

Individual utilities
* aclocal-invocation: (automake)aclocal Invocation. Generating aclocal.m4.
* afm2tfm: (dvips)Invoking afm2tfm.             Adobe to TeX font metrics.
* addr2line: (binutils)addr2line.    Convert addresses to file and line.
* ar: (binutils)ar.                  Create, modify, and extract from archives.
* arch: (coreutils)arch invocation.             Print machine hardware name.
* at-pr: (gnats)at-pr.                          Bug report timely reminders.
* autoconf: (autoconf)autoconf Invocation. How to create configuration scripts.
* autoconf-invocation: (autoconf)autoconf Invocation. Creating configure.
* autoheader: (autoconf)autoheader Invocation. Creating configure templates.
* autom4te: (autoconf)autom4te Invocation.     Autoconf executables backbone.
* automake-invocation: (automake)automake Invocation. Generating Makefile.in.
* autoreconf: (autoconf)autoreconf Invocation. Remake multiple `configure's.
* autoscan: (autoconf)autoscan Invocation.     Semi-automated `configure.ac'.
* autoupdate: (autoconf)autoupdate Invocation.  Automatic configure.ac update.
* awk: (gawk)Invoking gawk.                     Text scanning and processing.
* base32: (coreutils)base32 invocation.         Base32 encode/decode data.
* base64: (coreutils)base64 invocation.         Base64 encode/decode data.
* basename: (coreutils)basename invocation.     Strip directory and suffix.
* bibtex: (web2c)BibTeX invocation.             Maintaining bibliographies.
* c++filt: (binutils)c++filt.	Filter to demangle encoded C++ symbols.
* cat: (coreutils)cat invocation.               Concatenate and write files.
* chcon: (coreutils)chcon invocation.           Change SELinux CTX of files.
* chgrp: (coreutils)chgrp invocation.           Change file groups.
* chmod: (coreutils)chmod invocation.           Change access permissions.
* chown: (coreutils)chown invocation.           Change file owners and groups.
* chroot: (coreutils)chroot invocation.         Specify the root directory.
* cksum: (coreutils)cksum invocation.           Print POSIX CRC checksum.
* cmp: (diffutils)Invoking cmp.                 Compare 2 files byte by byte.
* comm: (coreutils)comm invocation.             Compare sorted files by line.
* comsatd: (mailutils)comsatd.                  Comsat daemon.
* config.status: (autoconf)config.status Invocation. Recreating configurations.
* configure: (autoconf)configure Invocation.    Configuring a package.
* coreutils: (coreutils)coreutils invocation.   Multi-call program.
* cp: (coreutils)cp invocation.                 Copy files.
* csplit: (coreutils)csplit invocation.         Split by context.
* csv2rec: (recutils)Invoking csv2rec.          CSV to recfiles.
* cut: (coreutils)cut invocation.               Print selected parts of lines.
* cvs: (cvs)CVS commands.       Concurrent Versions System
* cvsclient: (cvsclient).      The CVS client/server protocol.
* cxxfilt: (binutils)c++filt.   MS-DOS name for c++filt.
* date: (coreutils)date invocation.             Print/set system date and time.
* dd: (coreutils)dd invocation.                 Copy and convert a file.
* df: (coreutils)df invocation.                 Report file system disk usage.
* diff: (diffutils)Invoking diff.               Compare 2 files line by line.
* diff3: (diffutils)Invoking diff3.             Compare 3 files line by line.
* dir: (coreutils)dir invocation.               List directories briefly.
* dircolors: (coreutils)dircolors invocation.   Color setup for ls.
* dirname: (coreutils)dirname invocation.       Strip last file name component.
* dlltool: (binutils)dlltool.	Create files needed to build and use DLLs.
* dmp: (web2c)Dmp invocation.                   Troff->MPX (MetaPost pictures).
* du: (coreutils)du invocation.                 Report on disk usage.
* dvicopy: (web2c)DVIcopy invocation.           Virtual font expansion
* dvitomp: (web2c)DVItoMP invocation.           DVI to MPX (MetaPost pictures).
* dvitype: (web2c)DVItype invocation.           DVI to human-readable text.
* echo: (coreutils)echo invocation.             Print a line of text.
* edit-pr: (gnats)Invoking edit-pr.             Changing bugs.
* egrep: (grep)Invoking.                        grep -E.
* env: (coreutils)env invocation.               Modify the environment.
* expand: (coreutils)expand invocation.         Convert tabs to spaces.
* expr: (coreutils)expr invocation.             Evaluate expressions.
* factor: (coreutils)factor invocation.         Print prime factors
* false: (coreutils)false invocation.           Do nothing, unsuccessfully.
* fgrep: (fgrep)Invoking.                       grep -F.
* fid: (id-utils)fid invocation.        	Listing a file's tokens.
* file-pr: (gnats)file-pr.                      Processing incoming traffic.
* find: (find)Invoking find.                    Finding and acting on files.
* fmt: (coreutils)fmt invocation.               Reformat paragraph text.
* fnid: (id-utils)fnid invocation.      	Looking up file names.
* fold: (coreutils)fold invocation.             Wrap long input lines.
* frm: (mailutils)frm.                          List headers from a mailbox.
* ftp: (inetutils)ftp invocation.               FTP client.
* ftpd: (inetutils)ftpd invocation.             FTP Daemon.
* gcal2txt: (gcal)Invoking gcal2txt.            Calendar resource to text file.
* gftodvi: (web2c)GFtoDVI invocation.           Generic font proofsheets.
* gftopk: (web2c)GFtoPK invocation.             Generic to packed fonts.
* gftype: (web2c)GFtype invocation.             GF to human-readable text.
* groups: (coreutils)groups invocation.         Print group names a user is in.
* guimb: (mailutils)guimb.                      Mailbox processing language.
* gunzip: (gzip)Overview.                       Decompression.
* gzexe: (gzip)Overview.                        Compress executables.
* head: (coreutils)head invocation.             Output the first part of files.
* hostid: (coreutils)hostid invocation.         Print numeric host identifier.
* hostname: (coreutils)hostname invocation.     Print or set system name.
* id: (coreutils)id invocation.                 Print user identity.
* ifnames: (autoconf)ifnames Invocation.        Listing conditionals in source.
* imap4d: (mailutils)imap4d.                    IMAP4 daemon.
* inetd: (inetutils)inetd invocation.           Interner super-server.
* inimf: (web2c)inimf invocation.               Initial Metafont.
* inimp: (web2c)inimp invocation.               Initial MetaPost.
* initex: (web2c)initex invocation.             Initial TeX.
* install: (coreutils)install invocation.       Copy files and set attributes.
* join: (coreutils)join invocation.             Join lines on a common field.
* kill: (coreutils)kill invocation.             Send a signal to processes.
* kpsewhich: (kpathsea)Invoking kpsewhich.      TeX file searching.
* libtool-invocation: (libtool)Invoking libtool. Running the `libtool' script.
* libtoolize: (libtool)Invoking libtoolize.     Adding libtool support.
* lid: (id-utils)lid invocation.        	Matching words and patterns.
* link: (coreutils)link invocation.             Make hard links between files.
* ln: (coreutils)ln invocation.                 Make links between files.
* locate: (find)Invoking locate.                Finding files in a database.
* logger: (inetutils)logger invocation.         Send messages to system log.
* logname: (coreutils)logname invocation.       Print current login name.
* ls: (coreutils)ls invocation.                 List directory contents.
* mail-files: (sharutils)mail-files invocation. Send files to remote site.
* mail.local: (mailutils)mail.local.            Deliver mail to local mailbox.
* mail: (mailutils)mail.                        Send and receive mail.
* mailshar: (sharutils)mailshar invocation.     Make and send a shell archive.
* makempx: (web2c)MakeMPX invocation.           MetaPost label typesetting.
* maketexmf: (kpathsea)MakeTeX scripts.         MF source generation.
* maketexpk: (kpathsea)MakeTeX scripts.         PK bitmap generation.
* maketextex: (kpathsea)MakeTeX scripts.        TeX source generation.
* maketextfm: (kpathsea)MakeTeX scripts.        TeX font metric generation.
* md5sum: (coreutils)md5sum invocation.         Print or check MD5 digests.
* mdb2rec: (recutils)Invoking mdb2rec.          MDB to recfiles.
* mdiff: (wdiff)mdiff invocation.               Line cluster finder.
* messages: (mailutils)messages.                Count messages in mailbox.
* mf: (web2c)mf invocation.                     Creating typeface families.
* mft: (web2c)MFT invocation.                   Prettyprinting Metafont source.
* mgetty: (mgetty).                             Faxes, voicemail and more.
* mkdir: (coreutils)mkdir invocation.           Create directories.
* mkfifo: (coreutils)mkfifo invocation.         Create FIFOs (named pipes).
* mkid: (id-utils)mkid invocation.      	Creating an ID database.
* mknod: (coreutils)mknod invocation.           Create special files.
* mktemp: (coreutils)mktemp invocation.         Create temporary files.
* mp: (web2c)mp invocation.                     Creating technical diagrams.
* mpto: (web2c)MPto invocation.                 MetaPost label extraction.
* mv: (coreutils)mv invocation.                 Rename files.
* newer: (web2c)Newer invocation.               Compare modification times.
* nice: (coreutils)nice invocation.             Modify niceness.
* nl: (coreutils)nl invocation.                 Number lines and write files.
* nlmconv: (binutils)nlmconv.   Converts object code into an NLM.
* nm: (binutils)nm.             List symbols from object files.
* nohup: (coreutils)nohup invocation.           Immunize to hangups.
* nproc: (coreutils)nproc invocation.           Print the number of processors.
* numfmt: (coreutils)numfmt invocation.         Reformat numbers.
* objcopy: (binutils)objcopy.	Copy and translate object files.
* objdump: (binutils)objdump.   Display information from object files.
* od: (coreutils)od invocation.                 Dump files in octal, etc.
* paste: (coreutils)paste invocation.           Merge lines of files.
* patch: (diffutils)Invoking patch.             Apply a patch to a file.
* patgen: (web2c)Patgen invocation.             Creating hyphenation patterns.
* pathchk: (coreutils)pathchk invocation.       Check file name portability.
* ping: (inetutils)ping invocation.             Packets to network hosts.
* pktogf: (web2c)PKtoGF invocation.             Packed to generic fonts.
* pktype: (web2c)PKtype invocation.             PK to human-readable text.
* pltotf: (web2c)PLtoTF invocation.             Property list to TFM.
* pooltype: (web2c)Pooltype invocation.         Display WEB pool files.
* pop3d: (mailutils)pop3d.                      POP3 daemon.
* pr: (coreutils)pr invocation.                 Paginate or columnate files.
* pr-addr: (gnats)pr-addr.                      Bug report address retrieval.
* pr-edit: (gnats)pr-edit.                      The edit-pr driver.
* printenv: (coreutils)printenv invocation.     Print environment variables.
* printf: (coreutils)printf invocation.         Format and print data.
* ptx: (coreutils)ptx invocation.               Produce permuted indexes.
* pwd: (coreutils)pwd invocation.               Print working directory.
* query-pr: (gnats)Invoking query-pr.           Bug searching/reporting.
* queue-pr: (gnats)queue-pr.                    Handling incoming traffic.
* ranlib: (binutils)ranlib.                     Index archive contents.
* rcp: (inetutils)rcp invocation.               Remote copy.
* readelf: (binutils)readelf.	                Display contents of ELF file.
* readlink: (coreutils)readlink invocation.     Print referent of a symlink.
* readmsg: (mailutils)readmsg.                  Extract messages from a folder.
* realpath: (coreutils)realpath invocation.     Print resolved file names.
* rec2csv: (recutils)Invoking rec2csv.          Recfiles to CSV.
* recdel: (recutils)Invoking recdel.            Delete records.
* recfix: (recutils)Invoking recfix.            Fix recfiles.
* recinf: (recutils)Invoking recinf.            Get info about recfiles.
* recins: (recutils)Invoking recins.            Insert records.
* recsel: (recutils)Invoking recsel.            Read records.
* recset: (recutils)Invoking recset.            Manage fields.
* rexec: (inetutils)rexec invocation.           Remote execution client.
* rexecd: (inetutils)rexecd invocation.         Remote execution server.
* rlogin: (inetutils)rlogin invocation.         Remote login.
* rlogind: (inetutils)rlogind invocation.       Remote login server.
* rm: (coreutils)rm invocation.                 Remove files.
* rmdir: (coreutils)rmdir invocation.           Remove empty directories.
* rsh: (inetutils)rsh invocation.               Remote shell.
* rshd: (inetutils)rshd invocation.             Remote shell server.
* runcon: (coreutils)runcon invocation.         Run in specified SELinux CTX.
* sdiff: (diffutils)Invoking sdiff.             Merge 2 files side-by-side.
* send-pr: (gnats)Invoking send-pr.             Submitting bugs.
* seq: (coreutils)seq invocation.               Print numeric sequences
* sha1sum: (coreutils)sha1sum invocation.       Print or check SHA-1 digests.
* sha2: (coreutils)sha2 utilities.              Print or check SHA-2 digests.
* shar: (sharutils)shar Invocation.             Make a shell archive.
* shred: (coreutils)shred invocation.           Remove files more securely.
* shuf: (coreutils)shuf invocation.             Shuffling text files.
* sieve: (mailutils)sieve.                      Mail filtering utility.
* size: (binutils)size.         List section sizes and total size.
* sleep: (coreutils)sleep invocation.           Delay for a specified time.
* sort: (coreutils)sort invocation.             Sort text files.
* split: (coreutils)split invocation.           Split into pieces.
* stat: (coreutils)stat invocation.             Report file(system) status.
* stdbuf: (coreutils)stdbuf invocation.         Modify stdio buffering.
* strings: (binutils)strings.   List printable strings from files.
* strip: (binutils)strip.       Discard symbols.
* stty: (coreutils)stty invocation.             Print/change terminal settings.
* su: (coreutils)su invocation.                 Modify user and group ID.
* sum: (coreutils)sum invocation.               Print traditional checksum.
* sync: (coreutils)sync invocation.             Synchronize memory to disk.
* syslogd: (inetutils)syslogd invocation.       Syslog server.
* tabs: (tput)Invoking tabs.                    Tab settings.
* tac: (coreutils)tac invocation.               Reverse files.
* tail: (coreutils)tail invocation.             Output the last part of files.
* talk: (inetutils)talk invocation.             Talk client.
* talkd: (inetutils)talkd invocation.           Talk server.
* tangle: (web2c)Tangle invocation.             WEB to Pascal.
* tar: (tar)tar invocation.                     Invoking GNU `tar'.
* tcal: (gcal)Invoking tcal.                    Run Gcal with tomorrow's date.
* tee: (coreutils)tee invocation.               Redirect to multiple files.
* telnet: (inetutils)telnet invocation.         User interface to TELNET.
* telnetd: (inetutils)telnetd invocation.       Telnet server.
* test: (coreutils)test invocation.             File/string tests.
* testsuite: (autoconf)testsuite Invocation.    Running an Autotest test suite.
* tex: (web2c)tex invocation.                   Typesetting.
* tftopl: (web2c)TFtoPL invocation.             TFM -> property list.
* tftp: (inetutils)tftp invocation.             TFTP client.
* tftpd: (inetutils)tftpd invocation.           TFTP server.
* timeout: (coreutils)timeout invocation.       Run with time limit.
* touch: (coreutils)touch invocation.           Change file timestamps.
* tput: (tput)Invoking tput.                    Termcap in shell scripts.
* tr: (coreutils)tr invocation.                 Translate characters.
* traceroute: (inetutils)traceroute invocation. Trace the route to a host.
* true: (coreutils)true invocation.             Do nothing, successfully.
* truncate: (coreutils)truncate invocation.     Shrink/extend size of a file.
* tsort: (coreutils)tsort invocation.           Topological sort.
* tty: (coreutils)tty invocation.               Print terminal name.
* txt2gcal: (gcal)Invoking txt2gcal.            Calendar text to resource file.
* uname: (coreutils)uname invocation.           Print system information.
* unexpand: (coreutils)unexpand invocation.     Convert spaces to tabs.
* unify: (wdiff)unify invocation.               Diff format converter.
* uniq: (coreutils)uniq invocation.             Uniquify files.
* unlink: (coreutils)unlink invocation.         Removal via unlink(2).
* unshar: (sharutils)unshar Invocation.         Explode a shell archive.
* updatedb: (find)Invoking updatedb.            Building the locate database.
* uptime: (coreutils)uptime invocation.         Print uptime and load.
* users: (coreutils)users invocation.           Print current user names.
* uucpd: (inetutils)uucpd invocation.           Unix to Unix Copy.
* uudecode: (sharutils)uudecode Invocation.     Restore file from 7-bits.
* uuencode: (sharutils)uuencode Invocation.     Force binary file to 7-bits.
* vc-chlog: (vc-dwim)vc-chlog Invocation.       Changelog writing helper tool.
* vc-dwim: (vc-dwim)vc-dwim Invocation.         Version-control-agnostic tool.
* vdir: (coreutils)vdir invocation.             List directories verbosely.
* vftovp: (web2c)VFtoVP invocation.             Virtual font -> virtual pl.
* view-pr: (gnats)Invoking view-pr.             Showing bug reports.
* virmf: (web2c)virmf invocation.               Virgin Metafont.
* virmp: (web2c)virmp invocation.               Virgin MetaPost.
* virtex: (web2c)virtex invocation.             Virgin TeX.
* vptovf: (web2c)VPtoVF invocation.             Virtual pl -> virtual font.
* wc: (coreutils)wc invocation.                 Line, word, and byte counts.
* wdiff: (wdiff)wdiff invocation.               Word difference finder.
* weave: (web2c)Weave invocation.               WEB to TeX.
* who: (coreutils)who invocation.               Print who is logged in.
* whoami: (coreutils)whoami invocation.         Print effective user ID.
* whois: (inetutils)whois invocation.           Whois user interface.
* windmc: (binutils)windmc.	Generator for Windows message resources.
* windres: (binutils)windres.	Manipulate Windows resources.
* xargs: (find)Invoking xargs.                  Operating on many files.
* xtokid: (id-utils)xtokid invocation.  	Testing mkid scanners.
* yes: (coreutils)yes invocation.               Print a string indefinitely.
* zcat: (gzip)Overview.                         Decompression to stdout.
* zdiff: (gzip)Overview.                        Compare compressed files.
* zforce: (gzip)Overview.                       Force .gz extension on files.
* zgrep: (gzip)Overview.                        Search compressed files.
* zmore: (gzip)Overview.                        Decompression output by pages.
* zsh: (zsh).                                   An enhanced Bourne shell.

path: util/dir-example