4 # Self extracting help2man script.
6 # -q, --quiet Suppress extraction message
7 # -s, --stdout Extract to stdout
8 # -w, --with-gettext Add support for localized man pages
9 # -n, --name Print name only*
10 # -v, --version Print version only*
19 my ($program, $version) = ('help2man', '1.46.5');
22 die "Usage: $0 [--quiet] [--stdout] [--with-gettext] [--name] [--version]\n"
23 unless GetOptions \%opts, qw(quiet stdout with-gettext name version)
26 print "$program\n" if $opts{name};
27 print "$version\n" if $opts{version};
28 exit if $opts{name} or $opts{version};
40 $target =~ s/\.PL$// or die "$0: can't determine target name\n";
41 $tmp = "$target.tmp$$";
42 unlink $tmp or die "$0: can't unlink $tmp ($!)\n" if -e $tmp;
43 open OUT, ">$tmp" or die "$0: can't create $tmp ($!)\n";
46 print "Extracting $target (with variable substitutions)\n"
50 print OUT "$Config{startperl} -w\n";
52 # For systems without the crash-bang hack also add:
53 print OUT <<"!GROK!THIS!" if $Config{sharpbang} !~ /^#!/;
54 eval 'exec $Config{perlpath} -wS \$0 \${1+"\$@"}'
55 if \$running_under_some_shell;
57 \$running_under_some_shell = 0; # for -w
60 # No substitutions for this chunk:
61 print OUT <<'!NO!SUBS!';
63 # Generate a short man page from --help and --version output.
64 # Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2009,
65 # 2010, 2011, 2012, 2013, 2014, 2015 Free Software Foundation, Inc.
67 # This program is free software; you can redistribute it and/or modify
68 # it under the terms of the GNU General Public License as published by
69 # the Free Software Foundation; either version 3, or (at your option)
72 # This program is distributed in the hope that it will be useful,
73 # but WITHOUT ANY WARRANTY; without even the implied warranty of
74 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
75 # GNU General Public License for more details.
77 # You should have received a copy of the GNU General Public License
78 # along with this program; if not, see <http://www.gnu.org/licenses/>.
80 # Written by Brendan O'Dea <bod@debian.org>
81 # Available from ftp://ftp.gnu.org/gnu/help2man/
86 use Text::ParseWords qw(shellwords);
87 use Text::Tabs qw(expand);
88 use POSIX qw(strftime setlocale LC_ALL);
91 print OUT <<'!NO!SUBS!' if $opts{'with-gettext'};
92 use Locale::gettext qw(gettext);
93 use Encode qw(decode encode);
94 use I18N::Langinfo qw(langinfo CODESET);
97 # Interpolate program name and version:
98 print OUT <<"!GROK!THIS!";
100 my \$this_program = '$program';
101 my \$this_version = '$version';
104 # Conditionally include gettext support:
105 print OUT $opts{'with-gettext'} ? <<'!WITH!GETTEXT!' : <<'!NO!GETTEXT!';
109 my $gettext = Locale::gettext->domain($this_program);
110 sub _ { $gettext->get($_[0]) }
112 my ($user_locale) = grep defined && length,
113 (map $ENV{$_}, qw(LANGUAGE LC_ALL LC_MESSAGES LANG)), 'C';
115 my $user_encoding = langinfo CODESET;
117 # Set localisation of date and executable's output.
120 delete @ENV{qw(LANGUAGE LC_MESSAGES LANG)};
121 setlocale LC_ALL, $ENV{LC_ALL} = shift || 'C';
122 $encoding = langinfo CODESET;
125 sub dec { $encoding ? decode $encoding, $_[0] : $_[0] }
126 sub enc { $encoding ? encode $encoding, $_[0] : $_[0] }
127 sub enc_user { encode $user_encoding, $_[0] }
128 sub kark # die with message formatted in the invoking user's locale
130 setlocale LC_ALL, $user_locale;
131 my $fmt = $gettext->get(shift);
132 my $errmsg = enc_user sprintf $fmt, @_;
143 die "$this_program: no locale support (Locale::gettext required)\n"
144 unless $locale eq 'C';
149 sub enc_user { $_[0] }
150 sub kark { die +(sprintf shift, @_), "\n" }
153 # No substitutions for this chunk:
154 print OUT <<'!NO!SUBS!';
157 sub program_basename;
158 sub get_option_value;
160 sub fix_italic_spacing;
162 my $version_info = enc_user sprintf _(<<'EOT'), $this_program, $this_version;
165 Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2009, 2010,
166 2011, 2012, 2013, 2014, 2015 Free Software Foundation, Inc.
167 This is free software; see the source for copying conditions. There is NO
168 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
170 Written by Brendan O'Dea <bod@debian.org>
173 my $help_info = enc_user sprintf _(<<'EOT'), $this_program, $this_program;
174 `%s' generates a man page out of `--help' and `--version' output.
176 Usage: %s [OPTION]... EXECUTABLE
178 -n, --name=STRING description for the NAME paragraph
179 -s, --section=SECTION section number for manual page (1, 6, 8)
180 -m, --manual=TEXT name of manual (User Commands, ...)
181 -S, --source=TEXT source of program (FSF, Debian, ...)
182 -L, --locale=STRING select locale (default "C")
183 -i, --include=FILE include material from `FILE'
184 -I, --opt-include=FILE include material from `FILE' if it exists
185 -o, --output=FILE send output to `FILE'
186 -p, --info-page=TEXT name of Texinfo manual
187 -N, --no-info suppress pointer to Texinfo manual
188 -l, --libtool exclude the `lt-' from the program name
189 --help print this help, then exit
190 --version print version number, then exit
192 EXECUTABLE should accept `--help' and `--version' options and produce output on
193 stdout although alternatives may be specified using:
195 -h, --help-option=STRING help option string
196 -v, --version-option=STRING version option string
197 --version-string=STRING version string
198 --no-discard-stderr include stderr when parsing option output
200 Report bugs to <bug-help2man@gnu.org>.
206 my $help_option = '--help';
207 my $version_option = '--version';
208 my $discard_stderr = 1;
209 my ($opt_name, @opt_include, $opt_output, $opt_info, $opt_no_info, $opt_libtool,
213 'n|name=s' => \$opt_name,
214 's|section=s' => \$section,
215 'm|manual=s' => \$manual,
216 'S|source=s' => \$source,
217 'L|locale=s' => sub { configure_locale pop },
218 'i|include=s' => sub { push @opt_include, [ pop, 1 ] },
219 'I|opt-include=s' => sub { push @opt_include, [ pop, 0 ] },
220 'o|output=s' => \$opt_output,
221 'p|info-page=s' => \$opt_info,
222 'N|no-info' => \$opt_no_info,
223 'l|libtool' => \$opt_libtool,
224 'help' => sub { print $help_info; exit },
225 'version' => sub { print $version_info; exit },
226 'h|help-option=s' => \$help_option,
227 'v|version-option=s' => \$version_option,
228 'version-string=s' => \$version_text,
229 'discard-stderr!' => \$discard_stderr,
233 Getopt::Long::config('bundling');
234 die $help_info unless GetOptions %opt_def and @ARGV == 1;
238 print OUT <<'!NO!SUBS!' if $opts{'with-gettext'};
239 configure_locale unless $encoding;
243 # No substitutions for the remainder of the script:
244 print OUT <<'!NO!SUBS!';
248 my %append_match = ();
249 my @sections = (); # retain order of include file or in-line *section*s
251 # Process include file (if given). Format is:
253 # Optional initial text, ignored. May include lines starting with `-'
254 # which are processed as options.
257 # Verbatim text to be included in the named section. By default at
258 # the start, but in the case of `name' and `synopsis' the content
259 # will replace the autogenerated contents.
262 # Verbatim text to be inserted at the start of the named section.
265 # Verbatim text to replace the named section.
268 # Verbatim text to be appended to the end of the named section.
271 # Verbatim text for inclusion below a paragraph matching `pattern'.
276 my ($inc, $required) = @{shift @opt_include};
278 next unless -f $inc or $required;
279 kark N_("%s: can't open `%s' (%s)"), $this_program, $inc, $!
280 unless open INC, $inc;
287 # Convert input to internal Perl format, so that multibyte
288 # sequences are treated as single characters.
292 if (/^\[([^]]+)\]\s*$/)
298 # Handle explicit [<section], [=section] and [>section]
299 if ($key =~ s/^([<>=])\s*//)
301 if ($1 eq '>') { $hash = \%append; }
302 elsif ($1 eq '=') { $hash = \%replace; }
304 # NAME/SYNOPSIS replace by default
305 elsif ($key eq _('NAME') or $key eq _('SYNOPSIS'))
314 push @sections, $key;
319 if (m!^/(.*)/([ims]*)\s*$!)
321 my $pat = $2 ? "(?$2)$1" : $1;
324 eval { $key = qr($pat) };
327 $@ =~ s/ at .*? line \d.*//;
331 $hash = \%append_match;
335 # Check for options before the first section--anything else is
336 # silently ignored, allowing the first for comments and
343 local @ARGV = shellwords $_;
355 kark N_("%s: no valid information found in `%s'"), $this_program, $inc
359 # Compress trailing blank lines.
360 for my $hash (\(%include, %replace, %append, %append_match))
362 for (keys %$hash) { $hash->{$_} =~ s/\n+$/\n/ }
365 # Grab help and version info from executable.
366 my $help_text = get_option_value $ARGV[0], $help_option;
367 $version_text ||= get_option_value $ARGV[0], $version_option;
369 # Translators: the following message is a strftime(3) format string, which in
370 # the English version expands to the month as a word and the full year. It
371 # is used on the footer of the generated manual pages. If in doubt, you may
372 # just use %x as the value (which should be the full locale-specific date).
373 my $date = enc strftime _("%B %Y"), localtime;
374 my $program = program_basename $ARGV[0];
375 my $package = $program;
380 unlink $opt_output or kark N_("%s: can't unlink %s (%s)"),
381 $this_program, $opt_output, $! if -e $opt_output;
383 open STDOUT, ">$opt_output"
384 or kark N_("%s: can't create %s (%s)"), $this_program, $opt_output, $!;
387 # The first line of the --version information is assumed to be in one
388 # of the following formats:
391 # <program> <version>
392 # {GNU,Free} <program> <version>
393 # <program> ({GNU,Free} <package>) <version>
394 # <program> - {GNU,Free} <package> <version>
396 # and separated from any copyright/author details by a blank line.
398 ($_, $version_text) = ((split /\n+/, $version_text, 2), '');
400 if (/^(\S+) +\(((?:GNU|Free) +[^)]+)\) +(.*)/ or
401 /^(\S+) +- *((?:GNU|Free) +\S+) +(.*)/)
403 $program = program_basename $1;
407 elsif (/^((?:GNU|Free) +)?(\S+) +(.*)/)
409 $program = program_basename $2;
410 $package = $1 ? "$1$program" : $program;
418 # No info for `info' itself.
419 $opt_no_info = 1 if $program eq 'info';
423 # --name overrides --include contents.
424 $replace{_('NAME')} = "$program \\- $opt_name\n";
427 # Translators: "NAME", "SYNOPSIS" and other one or two word strings in all
428 # upper case are manual page section headings. The man(1) manual page in your
429 # language, if available should provide the conventional translations.
430 for ($replace{_('NAME')} || ($include{_('NAME')} ||= ''))
432 if ($_) # Use first name given as $program
434 $program = $1 if /^([^\s,]+)(?:,?\s*[^\s,\\-]+)*\s+\\?-/;
436 else # Set a default (useless) NAME paragraph.
438 $_ = sprintf _("%s \\- manual page for %s %s") . "\n", $program,
443 # Man pages traditionally have the page title in caps.
444 my $PROGRAM = uc $program;
446 # Set default page head/footers
447 $source ||= "$program $version";
452 if (/^(1[Mm]|8)/) { $manual = enc _('System Administration Utilities') }
453 elsif (/^6/) { $manual = enc _('Games') }
454 else { $manual = enc _('User Commands') }
458 # Extract usage clause(s) [if any] for SYNOPSIS.
459 # Translators: "Usage" and "or" here are patterns (regular expressions) which
460 # are used to match the usage synopsis in program output. An example from cp
461 # (GNU coreutils) which contains both strings:
462 # Usage: cp [OPTION]... [-T] SOURCE DEST
463 # or: cp [OPTION]... SOURCE... DIRECTORY
464 # or: cp [OPTION]... -t DIRECTORY SOURCE...
465 my $PAT_USAGE = _('Usage');
466 my $PAT_USAGE_CONT = _('or');
467 if ($help_text =~ s/^($PAT_USAGE):( +(\S+))(.*)((?:\n(?: {6}\1| *($PAT_USAGE_CONT): +\S).*)*)//om)
474 for (split /\n/) { s/^ *(($PAT_USAGE_CONT): +)?//o; push @syn, $_ }
480 $synopsis .= ".br\n" if $synopsis;
482 s/^lt-// if $opt_libtool;
484 $synopsis .= ".B $1\n";
486 s/(([][]|\.\.+)+)/\\fR$1\\fI/g;
487 s/^/\\fI/ unless s/^\\fR//;
495 $_ = fix_italic_spacing $_;
499 $include{_('SYNOPSIS')} .= $synopsis;
502 # Process text, initial section is DESCRIPTION.
503 my $sect = _('DESCRIPTION');
504 $_ = "$help_text\n\n$version_text";
506 # Normalise paragraph breaks.
511 # Join hyphenated lines.
512 s/([A-Za-z])-\n *([A-Za-z])/$1$2/g;
514 # Temporarily exchange leading dots, apostrophes and backslashes for
520 # Translators: patterns are used to match common program output. In the source
521 # these strings are all of the form of "my $PAT_something = _('...');" and are
522 # regular expressions. If there is more than one commonly used string, you
523 # may separate alternatives with "|". Spaces in these expressions are written
524 # as " +" to indicate that more than one space may be matched. The string
525 # "(?:[\\w-]+ +)?" in the bug reporting pattern is used to indicate an
526 # optional word, so that either "Report bugs" or "Report _program_ bugs" will
528 my $PAT_BUGS = _('Report +(?:[\w-]+ +)?bugs|Email +bug +reports +to');
529 my $PAT_AUTHOR = _('Written +by');
530 my $PAT_OPTIONS = _('Options');
531 my $PAT_ENVIRONMENT = _('Environment');
532 my $PAT_FILES = _('Files');
533 my $PAT_EXAMPLES = _('Examples');
534 my $PAT_FREE_SOFTWARE = _('This +is +free +software');
536 # Start a new paragraph (if required) for these.
537 s/([^\n])\n($PAT_BUGS|$PAT_AUTHOR) /$1\n\n$2 /og;
539 # Convert iso-8859-1 copyright symbol or (c) to nroff
541 s/^Copyright +(?:\xa9|\([Cc]\))/Copyright \\(co/mg;
545 # Convert some standard paragraph names.
546 if (s/^($PAT_OPTIONS): *\n+//o)
548 $sect = _('OPTIONS');
551 if (s/^($PAT_ENVIRONMENT): *\n+//o)
553 $sect = _('ENVIRONMENT');
556 if (s/^($PAT_FILES): *\n+//o)
561 elsif (s/^($PAT_EXAMPLES): *\n+//o)
563 $sect = _('EXAMPLES');
567 # Custom section indicated by a line containing "*Section Name*".
568 if (s/^\*(\w(.*\w)?)\* *\n+//)
571 $sect =~ tr/*/ /; # also accept *Section*Name*
572 push @sections, $sect;
579 $sect = _('COPYRIGHT');
582 # Bug reporting section.
583 elsif (/^($PAT_BUGS) /o)
585 $sect = _('REPORTING BUGS');
589 elsif (/^($PAT_AUTHOR)/o)
594 # Examples, indicated by an indented leading $, % or > are
595 # rendered in a constant width font.
596 if (/^( +)([\$\%>] )\S/)
601 while (s/^$indent\Q$prefix\E(\S.*)\n*//)
603 $include{$sect} .= "$break\n\\f(CW$prefix$1\\fR\n";
612 # Sub-sections have a trailing colon and the second line indented.
613 if (s/^(\S.*:) *\n / /)
615 $matched .= $& if %append_match;
616 $include{$sect} .= qq(.SS "$1"\n);
622 # Option with description.
623 if (s/^( {1,10}([+-]\S.*?))(?:( +(?!-))|\n( {20,}))(\S.*)\n//)
625 $matched .= $& if %append_match;
626 $indent = length ($4 || "$1$3");
627 $content = ".TP\n\x84$2\n\x84$5\n";
630 # Indent may be different on second line.
631 $indent = length $& if /^ {20,}/;
635 # Option without description.
636 elsif (s/^ {1,10}([+-]\S.*)\n//)
638 $matched .= $& if %append_match;
639 $content = ".HP\n\x84$1\n";
640 $indent = 80; # not continued
643 # Indented paragraph with tag.
644 elsif (s/^( +(\S.*?))(?:( +)|\n( {20,}))(\S.*)\n//)
646 $matched .= $& if %append_match;
647 $indent = length ($4 || "$1$3");
648 $content = ".TP\n\x84$2\n\x84$5\n";
651 # Indented paragraph.
652 elsif (s/^( +)(\S.*)\n//)
654 $matched .= $& if %append_match;
656 $content = ".IP\n\x84$2\n";
659 # Left justified paragraph.
663 $matched .= $& if %append_match;
664 $content = ".PP\n" if $include{$sect};
668 # Append continuations.
669 while ($indent ? s/^ {$indent}(\S.*)\n// : s/^(\S.*)\n//)
671 $matched .= $& if %append_match;
672 $content .= "\x84$1\n";
675 # Move to next paragraph.
680 # Leading dot and apostrophe protection.
685 # Examples should be verbatim.
686 unless ($sect eq _('EXAMPLES'))
689 s/(^|[ (])(-[][\w=-]+)/$1 . convert_option $2/mge;
691 # Italicise filenames: /a/b, $VAR/c/d, ~/e/f
693 (^|[ (]) # space/punctuation before
695 (?:\$\w+|~)? # leading variable, or tilde
696 (?:/\w(?:[\w.-]*\w)?)+ # path components
698 ($|[ ,;.)]) # space/punctuation after
701 $_ = fix_italic_spacing $_;
704 # Escape remaining hyphens.
707 if ($sect eq _('COPYRIGHT'))
709 # Insert line breaks before additional copyright messages
710 # and the disclaimer.
711 s/\n(Copyright |$PAT_FREE_SOFTWARE)/\n.br\n$1/og;
713 elsif ($sect eq _('REPORTING BUGS'))
715 # Handle multi-line bug reporting sections of the form:
717 # Report <program> bugs to <addr>
718 # GNU <package> home page: <url>
720 s/\n([[:upper:]])/\n.br\n$1/g;
724 # Check if matched paragraph contains /pat/.
727 for my $pat (keys %append_match)
729 if ($matched =~ $pat)
731 $content .= ".PP\n" unless $append_match{$pat} =~ /^\./;
732 $content .= $append_match{$pat};
737 $include{$sect} .= $content;
740 # Refer to the real documentation.
741 unless ($opt_no_info)
743 my $info_page = $opt_info || $program;
745 $sect = _('SEE ALSO');
746 $include{$sect} .= ".PP\n" if $include{$sect};
747 $include{$sect} .= sprintf _(<<'EOT'), $program, $program, $info_page;
748 The full documentation for
750 is maintained as a Texinfo manual. If the
754 programs are properly installed at your site, the command
758 should give you access to the complete manual.
762 # Append additional text.
763 while (my ($sect, $text) = each %append)
765 $include{$sect} .= $append{$sect};
769 while (my ($sect, $text) = each %replace)
771 $include{$sect} = $replace{$sect};
776 .\\" DO NOT MODIFY THIS FILE! It was generated by $this_program $this_version.
777 .TH $PROGRAM "$section" "$date" "$source" "$manual"
781 my @pre = (_('NAME'), _('SYNOPSIS'), _('DESCRIPTION'), _('OPTIONS'));
782 my @post = (_('ENVIRONMENT'), _('FILES'), _('EXAMPLES'), _('AUTHOR'),
783 _('REPORTING BUGS'), _('COPYRIGHT'), _('SEE ALSO'));
784 my %filter = map { $_ => 1 } @pre, @post;
788 for my $sect (@pre, (grep !$filter{$_}, @sections), @post)
790 next if $done{$sect}++; # ignore duplicates
791 next unless $include{$sect};
794 my $quote = $sect =~ /\W/ ? '"' : '';
795 print enc ".SH $quote$sect$quote\n";
797 for ($include{$sect})
799 # Replace leading dot, apostrophe, backslash and hyphen
806 # Convert some latin1 chars to troff equivalents
807 s/\xa0/\\ /g; # non-breaking space
814 close STDOUT or kark N_("%s: error writing to %s (%s)"), $this_program,
815 $opt_output || 'stdout', $!;
819 # Get program basename, and strip libtool "lt-" prefix if required.
824 s/^lt-// if $opt_libtool;
828 # Call program with given option and return results.
831 my ($prog, $opt) = @_;
832 my $stderr = $discard_stderr ? '/dev/null' : '&1';
834 map { s/ +$//; expand $_ }
836 `$prog $opt 2>$stderr`;
840 my $err = N_("%s: can't get `%s' info from %s%s");
841 my $extra = $discard_stderr
842 ? "\n" . N_("Try `--no-discard-stderr' if option outputs to stderr")
845 kark $err, $this_program, $opt, $prog, $extra;
851 # Convert option dashes to \- to stop nroff from hyphenating 'em, and
852 # embolden. Option arguments get italicised.
855 local $_ = '\fB' . shift;
858 unless (s/\[=(.*)\]$/\\fR[=\\fI$1\\fR]/)
868 # Insert spacing escape characters \, and \/ before and after italic text. See
869 # http://www.gnu.org/software/groff/manual/html_node/Ligatures-and-Kerning.html
870 sub fix_italic_spacing
873 s!\\fI(.*?)\\f([BRP])!\\fI\\,$1\\/\\f$2!g;
878 # Rename output and fix permissions
879 unless ($opts{stdout})
882 rename $tmp, $target or die "$0: can't rename $tmp to $target ($!)\n";
883 chmod 0555, $target or warn "$0: can't change mode of $target ($!)\n";