maint: Update INSTALL
[automake.git] / doc / help2man
blob9268874fa58c29e110576d6e3dc6949637ddcbef
1 #!/usr/bin/perl -w
3 # Generate a short man page from --help and --version output.
4 # Copyright (C) 1997-2018 Free Software Foundation, Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3, or (at your option)
9 # any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, see <https://www.gnu.org/licenses/>.
19 # Written by Brendan O'Dea <bod@debian.org>
20 # Available from https://ftp.gnu.org/gnu/help2man/
22 use 5.008;
23 use strict;
24 use Getopt::Long;
25 use Text::ParseWords qw(shellwords);
26 use Text::Tabs qw(expand);
27 use POSIX qw(strftime setlocale LC_ALL);
29 my $this_program = 'help2man';
30 my $this_version = '1.47.4';
32 sub _ { $_[0] }
33 sub configure_locale
35 my $locale = shift;
36 die "$this_program: no locale support (Locale::gettext required)\n"
37 unless $locale eq 'C';
40 sub dec { $_[0] }
41 sub enc { $_[0] }
42 sub enc_user { $_[0] }
43 sub kark { die +(sprintf shift, @_), "\n" }
44 sub N_ { $_[0] }
46 sub program_basename;
47 sub get_option_value;
48 sub convert_option;
49 sub fix_italic_spacing;
51 my $version_info = enc_user sprintf _(<<'EOT'), $this_program, $this_version;
52 GNU %s %s
54 Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2009, 2010,
55 2011, 2012, 2013, 2014, 2015 Free Software Foundation, Inc.
56 This is free software; see the source for copying conditions. There is NO
57 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
59 Written by Brendan O'Dea <bod@debian.org>
60 EOT
62 my $help_info = enc_user sprintf _(<<'EOT'), $this_program, $this_program;
63 `%s' generates a man page out of `--help' and `--version' output.
65 Usage: %s [OPTION]... EXECUTABLE
67 -n, --name=STRING description for the NAME paragraph
68 -s, --section=SECTION section number for manual page (1, 6, 8)
69 -m, --manual=TEXT name of manual (User Commands, ...)
70 -S, --source=TEXT source of program (FSF, Debian, ...)
71 -L, --locale=STRING select locale (default "C")
72 -i, --include=FILE include material from `FILE'
73 -I, --opt-include=FILE include material from `FILE' if it exists
74 -o, --output=FILE send output to `FILE'
75 -p, --info-page=TEXT name of Texinfo manual
76 -N, --no-info suppress pointer to Texinfo manual
77 -l, --libtool exclude the `lt-' from the program name
78 --help print this help, then exit
79 --version print version number, then exit
81 EXECUTABLE should accept `--help' and `--version' options and produce output on
82 stdout although alternatives may be specified using:
84 -h, --help-option=STRING help option string
85 -v, --version-option=STRING version option string
86 --version-string=STRING version string
87 --no-discard-stderr include stderr when parsing option output
89 Report bugs to <bug-help2man@gnu.org>.
90 EOT
92 my $section = 1;
93 my $manual = '';
94 my $source = '';
95 my $help_option = '--help';
96 my $version_option = '--version';
97 my $discard_stderr = 1;
98 my ($opt_name, @opt_include, $opt_output, $opt_info, $opt_no_info, $opt_libtool,
99 $version_text);
101 my %opt_def = (
102 'n|name=s' => \$opt_name,
103 's|section=s' => \$section,
104 'm|manual=s' => \$manual,
105 'S|source=s' => \$source,
106 'L|locale=s' => sub { configure_locale pop },
107 'i|include=s' => sub { push @opt_include, [ pop, 1 ] },
108 'I|opt-include=s' => sub { push @opt_include, [ pop, 0 ] },
109 'o|output=s' => \$opt_output,
110 'p|info-page=s' => \$opt_info,
111 'N|no-info' => \$opt_no_info,
112 'l|libtool' => \$opt_libtool,
113 'help' => sub { print $help_info; exit },
114 'version' => sub { print $version_info; exit },
115 'h|help-option=s' => \$help_option,
116 'v|version-option=s' => \$version_option,
117 'version-string=s' => \$version_text,
118 'discard-stderr!' => \$discard_stderr,
121 # Parse options.
122 Getopt::Long::config('bundling');
123 die $help_info unless GetOptions %opt_def and @ARGV == 1;
125 my %include = ();
126 my %replace = ();
127 my %append = ();
128 my %append_match = ();
129 my @sections = (); # retain order of include file or in-line *section*s
131 # Process include file (if given). Format is:
133 # Optional initial text, ignored. May include lines starting with `-'
134 # which are processed as options.
136 # [section]
137 # Verbatim text to be included in the named section. By default at
138 # the start, but in the case of `name' and `synopsis' the content
139 # will replace the autogenerated contents.
141 # [<section]
142 # Verbatim text to be inserted at the start of the named section.
144 # [=section]
145 # Verbatim text to replace the named section.
147 # [>section]
148 # Verbatim text to be appended to the end of the named section.
150 # /pattern/
151 # Verbatim text for inclusion below a paragraph matching `pattern'.
154 while (@opt_include)
156 my ($inc, $required) = @{shift @opt_include};
158 next unless -f $inc or $required;
159 kark N_("%s: can't open `%s' (%s)"), $this_program, $inc, $!
160 unless open INC, $inc;
162 my $key;
163 my $hash;
165 while (<INC>)
167 # Convert input to internal Perl format, so that multibyte
168 # sequences are treated as single characters.
169 $_ = dec $_;
171 # [section]
172 if (/^\[([^]]+)\]\s*$/)
174 $key = uc $1;
175 $key =~ s/^\s+//;
176 $key =~ s/\s+$//;
177 $hash = \%include;
178 # Handle explicit [<section], [=section] and [>section]
179 if ($key =~ s/^([<>=])\s*//)
181 if ($1 eq '>') { $hash = \%append; }
182 elsif ($1 eq '=') { $hash = \%replace; }
184 # NAME/SYNOPSIS replace by default
185 elsif ($key eq _('NAME') or $key eq _('SYNOPSIS'))
187 $hash = \%replace;
189 else
191 $hash = \%include;
194 push @sections, $key;
195 next;
198 # /pattern/
199 if (m!^/(.*)/([ims]*)\s*$!)
201 my $pat = $2 ? "(?$2)$1" : $1;
203 # Check pattern.
204 eval { $key = qr($pat) };
205 if ($@)
207 $@ =~ s/ at .*? line \d.*//;
208 die "$inc:$.:$@";
211 $hash = \%append_match;
212 next;
215 # Check for options before the first section--anything else is
216 # silently ignored, allowing the first for comments and
217 # revision info.
218 unless ($key)
220 # handle options
221 if (/^-/)
223 local @ARGV = shellwords $_;
224 GetOptions %opt_def;
227 next;
230 $hash->{$key} .= $_;
233 close INC;
235 kark N_("%s: no valid information found in `%s'"), $this_program, $inc
236 unless $key;
239 # Compress trailing blank lines.
240 for my $hash (\(%include, %replace, %append, %append_match))
242 for (keys %$hash) { $hash->{$_} =~ s/\n+$/\n/ }
245 # Grab help and version info from executable.
246 my $help_text = get_option_value $ARGV[0], $help_option;
247 $version_text ||= get_option_value $ARGV[0], $version_option;
249 # By default the generated manual pages will include the current date. This may
250 # however be overriden by setting the environment variable $SOURCE_DATE_EPOCH
251 # to an integer value of the seconds since the UNIX epoch. This is primarily
252 # intended to support reproducible builds (wiki.debian.org/ReproducibleBuilds)
253 # and will additionally ensure that the output date string is UTC.
254 my $epoch_secs = time;
255 if (exists $ENV{SOURCE_DATE_EPOCH} and $ENV{SOURCE_DATE_EPOCH} =~ /^(\d+)$/)
257 $epoch_secs = $1;
258 $ENV{TZ} = 'UTC';
261 # Translators: the following message is a strftime(3) format string, which in
262 # the English version expands to the month as a word and the full year. It
263 # is used on the footer of the generated manual pages. If in doubt, you may
264 # just use %x as the value (which should be the full locale-specific date).
265 my $date = enc strftime _("%B %Y"), localtime $epoch_secs;
266 my $program = program_basename $ARGV[0];
267 my $package = $program;
268 my $version;
270 if ($opt_output)
272 unlink $opt_output or kark N_("%s: can't unlink %s (%s)"),
273 $this_program, $opt_output, $! if -e $opt_output;
275 open STDOUT, ">$opt_output"
276 or kark N_("%s: can't create %s (%s)"), $this_program, $opt_output, $!;
279 # The first line of the --version information is assumed to be in one
280 # of the following formats:
282 # <version>
283 # <program> <version>
284 # {GNU,Free} <program> <version>
285 # <program> ({GNU,Free} <package>) <version>
286 # <program> - {GNU,Free} <package> <version>
288 # and separated from any copyright/author details by a blank line.
290 ($_, $version_text) = ((split /\n+/, $version_text, 2), '');
292 if (/^(\S+) +\(((?:GNU|Free) +[^)]+)\) +(.*)/ or
293 /^(\S+) +- *((?:GNU|Free) +\S+) +(.*)/)
295 $program = program_basename $1;
296 $package = $2;
297 $version = $3;
299 elsif (/^((?:GNU|Free) +)?(\S+) +(.*)/)
301 $program = program_basename $2;
302 $package = $1 ? "$1$program" : $program;
303 $version = $3;
305 else
307 $version = $_;
310 # No info for `info' itself.
311 $opt_no_info = 1 if $program eq 'info';
313 if ($opt_name)
315 # --name overrides --include contents.
316 $replace{_('NAME')} = "$program \\- $opt_name\n";
319 # Translators: "NAME", "SYNOPSIS" and other one or two word strings in all
320 # upper case are manual page section headings. The man(1) manual page in your
321 # language, if available should provide the conventional translations.
322 for ($replace{_('NAME')} || ($include{_('NAME')} ||= ''))
324 if ($_) # Use first name given as $program
326 $program = $1 if /^([^\s,]+)(?:,?\s*[^\s,\\-]+)*\s+\\?-/;
328 else # Set a default (useless) NAME paragraph.
330 $_ = sprintf _("%s \\- manual page for %s %s") . "\n", $program,
331 $program, $version;
335 # Man pages traditionally have the page title in caps.
336 my $PROGRAM = uc $program;
338 # Set default page head/footers
339 $source ||= "$program $version";
340 unless ($manual)
342 for ($section)
344 if (/^(1[Mm]|8)/) { $manual = enc _('System Administration Utilities') }
345 elsif (/^6/) { $manual = enc _('Games') }
346 else { $manual = enc _('User Commands') }
350 # Extract usage clause(s) [if any] for SYNOPSIS.
351 # Translators: "Usage" and "or" here are patterns (regular expressions) which
352 # are used to match the usage synopsis in program output. An example from cp
353 # (GNU coreutils) which contains both strings:
354 # Usage: cp [OPTION]... [-T] SOURCE DEST
355 # or: cp [OPTION]... SOURCE... DIRECTORY
356 # or: cp [OPTION]... -t DIRECTORY SOURCE...
357 my $PAT_USAGE = _('Usage');
358 my $PAT_USAGE_CONT = _('or');
359 if ($help_text =~ s/^($PAT_USAGE):( +(\S+))(.*)((?:\n(?: {6}\1| *($PAT_USAGE_CONT): +\S).*)*)//om)
361 my @syn = $3 . $4;
363 if ($_ = $5)
365 s/^\n//;
366 for (split /\n/) { s/^ *(($PAT_USAGE_CONT): +)?//o; push @syn, $_ }
369 my $synopsis = '';
370 for (@syn)
372 $synopsis .= ".br\n" if $synopsis;
373 s!^\S*/!!;
374 s/^lt-// if $opt_libtool;
375 s/^(\S+) *//;
376 $synopsis .= ".B $1\n";
377 s/\s+$//;
378 s/(([][]|\.\.+)+)/\\fR$1\\fI/g;
379 s/^/\\fI/ unless s/^\\fR//;
380 $_ .= '\fR';
381 s/(\\fI)( *)/$2$1/g;
382 s/\\fI\\fR//g;
383 s/^\\fR//;
384 s/\\fI$//;
385 s/^\./\\&./;
387 $_ = fix_italic_spacing $_;
388 $synopsis .= "$_\n";
391 $include{_('SYNOPSIS')} .= $synopsis;
394 # Process text, initial section is DESCRIPTION.
395 my $sect = _('DESCRIPTION');
396 $_ = "$help_text\n\n$version_text";
398 # Normalise paragraph breaks.
399 s/^\n+//;
400 s/\n*$/\n/;
401 s/\n\n+/\n\n/g;
403 # Join hyphenated lines.
404 s/([A-Za-z])-\n *([A-Za-z])/$1$2/g;
406 # Temporarily exchange leading dots, apostrophes and backslashes for
407 # tokens.
408 s/^\./\x80/mg;
409 s/^'/\x81/mg;
410 s/\\/\x82/g;
412 # Translators: patterns are used to match common program output. In the source
413 # these strings are all of the form of "my $PAT_something = _('...');" and are
414 # regular expressions. If there is more than one commonly used string, you
415 # may separate alternatives with "|". Spaces in these expressions are written
416 # as " +" to indicate that more than one space may be matched. The string
417 # "(?:[\\w-]+ +)?" in the bug reporting pattern is used to indicate an
418 # optional word, so that either "Report bugs" or "Report _program_ bugs" will
419 # be matched.
420 my $PAT_BUGS = _('Report +(?:[\w-]+ +)?bugs|Email +bug +reports +to');
421 my $PAT_AUTHOR = _('Written +by');
422 my $PAT_OPTIONS = _('Options');
423 my $PAT_ENVIRONMENT = _('Environment');
424 my $PAT_FILES = _('Files');
425 my $PAT_EXAMPLES = _('Examples');
426 my $PAT_FREE_SOFTWARE = _('This +is +free +software');
428 # Start a new paragraph (if required) for these.
429 s/([^\n])\n($PAT_BUGS|$PAT_AUTHOR) /$1\n\n$2 /og;
431 # Convert iso-8859-1 copyright symbol or (c) to nroff
432 # character.
433 s/^Copyright +(?:\xa9|\([Cc]\))/Copyright \\(co/mg;
435 while (length)
437 # Convert some standard paragraph names.
438 if (s/^($PAT_OPTIONS): *\n+//o)
440 $sect = _('OPTIONS');
441 next;
443 if (s/^($PAT_ENVIRONMENT): *\n+//o)
445 $sect = _('ENVIRONMENT');
446 next;
448 if (s/^($PAT_FILES): *\n+//o)
450 $sect = _('FILES');
451 next;
453 elsif (s/^($PAT_EXAMPLES): *\n+//o)
455 $sect = _('EXAMPLES');
456 next;
459 # Custom section indicated by a line containing "*Section Name*".
460 if (s/^\*(\w(.*\w)?)\* *\n+//)
462 $sect = uc $1;
463 $sect =~ tr/*/ /; # also accept *Section*Name*
464 push @sections, $sect;
465 next;
468 # Copyright section.
469 if (/^Copyright /)
471 $sect = _('COPYRIGHT');
474 # Bug reporting section.
475 elsif (/^($PAT_BUGS) /o)
477 $sect = _('REPORTING BUGS');
480 # Author section.
481 elsif (/^($PAT_AUTHOR)/o)
483 $sect = _('AUTHOR');
486 # Examples, indicated by an indented leading $, % or > are
487 # rendered in a constant width font.
488 if (/^( +)([\$\%>] )\S/)
490 my $indent = $1;
491 my $prefix = $2;
492 my $break = '.IP';
493 while (s/^$indent\Q$prefix\E(\S.*)\n*//)
495 $include{$sect} .= "$break\n\\f(CW$prefix$1\\fR\n";
496 $break = '.br';
499 next;
502 my $matched = '';
504 # Sub-sections have a trailing colon and the second line indented.
505 if (s/^(\S.*:) *\n / /)
507 $matched .= $& if %append_match;
508 $include{$sect} .= qq(.SS "$1"\n);
511 my $indent = 0;
512 my $content = '';
514 # Option with description.
515 if (s/^( {1,10}([+-]\S.*?))(?:( +(?!-))|\n( {20,}))(\S.*)\n//)
517 $matched .= $& if %append_match;
518 $indent = length ($4 || "$1$3");
519 $content = ".TP\n\x84$2\n\x84$5\n";
520 unless ($4)
522 # Indent may be different on second line.
523 $indent = length $& if /^ {20,}/;
527 # Option without description.
528 elsif (s/^ {1,10}([+-]\S.*)\n//)
530 $matched .= $& if %append_match;
531 $content = ".HP\n\x84$1\n";
532 $indent = 80; # not continued
535 # Indented paragraph with tag.
536 elsif (s/^( +(\S.*?))(?:( +)|\n( {20,}))(\S.*)\n//)
538 $matched .= $& if %append_match;
539 $indent = length ($4 || "$1$3");
540 $content = ".TP\n\x84$2\n\x84$5\n";
543 # Indented paragraph.
544 elsif (s/^( +)(\S.*)\n//)
546 $matched .= $& if %append_match;
547 $indent = length $1;
548 $content = ".IP\n\x84$2\n";
551 # Left justified paragraph.
552 else
554 s/(.*)\n//;
555 $matched .= $& if %append_match;
556 $content = ".PP\n" if $include{$sect};
557 $content .= "$1\n";
560 # Append continuations.
561 while ($indent ? s/^ {$indent}(\S.*)\n// : s/^(\S.*)\n//)
563 $matched .= $& if %append_match;
564 $content .= "\x84$1\n";
567 # Move to next paragraph.
568 s/^\n+//;
570 for ($content)
572 # Leading dot and apostrophe protection.
573 s/\x84\./\x80/g;
574 s/\x84'/\x81/g;
575 s/\x84//g;
577 # Examples should be verbatim.
578 unless ($sect eq _('EXAMPLES'))
580 # Convert options.
581 s/(^|[ (])(-[][\w=-]+)/$1 . convert_option $2/mge;
583 # Italicise filenames: /a/b, $VAR/c/d, ~/e/f
585 (^|[ (]) # space/punctuation before
587 (?:\$\w+|~)? # leading variable, or tilde
588 (?:/\w(?:[\w.-]*\w)?)+ # path components
590 ($|[ ,;.)]) # space/punctuation after
591 !$1\\fI$2\\fP$3!xmg;
593 $_ = fix_italic_spacing $_;
596 # Escape remaining hyphens.
597 s/-/\x83/g;
599 if ($sect eq _('COPYRIGHT'))
601 # Insert line breaks before additional copyright messages
602 # and the disclaimer.
603 s/\n(Copyright |$PAT_FREE_SOFTWARE)/\n.br\n$1/og;
605 elsif ($sect eq _('REPORTING BUGS'))
607 # Handle multi-line bug reporting sections of the form:
609 # Report <program> bugs to <addr>
610 # GNU <package> home page: <url>
611 # ...
612 s/\n([[:upper:]])/\n.br\n$1/g;
616 # Check if matched paragraph contains /pat/.
617 if (%append_match)
619 for my $pat (keys %append_match)
621 if ($matched =~ $pat)
623 $content .= ".PP\n" unless $append_match{$pat} =~ /^\./;
624 $content .= $append_match{$pat};
629 $include{$sect} .= $content;
632 # Refer to the real documentation.
633 unless ($opt_no_info)
635 my $info_page = $opt_info || $program;
637 $sect = _('SEE ALSO');
638 $include{$sect} .= ".PP\n" if $include{$sect};
639 $include{$sect} .= sprintf _(<<'EOT'), $program, $program, $info_page;
640 The full documentation for
641 .B %s
642 is maintained as a Texinfo manual. If the
643 .B info
645 .B %s
646 programs are properly installed at your site, the command
648 .B info %s
650 should give you access to the complete manual.
654 # Append additional text.
655 while (my ($sect, $text) = each %append)
657 $include{$sect} .= $append{$sect};
660 # Replace sections.
661 while (my ($sect, $text) = each %replace)
663 $include{$sect} = $replace{$sect};
666 # Output header.
667 print <<EOT;
668 .\\" DO NOT MODIFY THIS FILE! It was generated by $this_program $this_version.
669 .TH $PROGRAM "$section" "$date" "$source" "$manual"
672 # Section ordering.
673 my @pre = (_('NAME'), _('SYNOPSIS'), _('DESCRIPTION'), _('OPTIONS'));
674 my @post = (_('ENVIRONMENT'), _('FILES'), _('EXAMPLES'), _('AUTHOR'),
675 _('REPORTING BUGS'), _('COPYRIGHT'), _('SEE ALSO'));
676 my %filter = map { $_ => 1 } @pre, @post;
678 # Output content.
679 my %done;
680 for my $sect (@pre, (grep !$filter{$_}, @sections), @post)
682 next if $done{$sect}++; # ignore duplicates
683 next unless $include{$sect};
684 if ($include{$sect})
686 my $quote = $sect =~ /\W/ ? '"' : '';
687 print enc ".SH $quote$sect$quote\n";
689 for ($include{$sect})
691 # Replace leading dot, apostrophe, backslash and hyphen
692 # tokens.
693 s/\x80/\\&./g;
694 s/\x81/\\&'/g;
695 s/\x82/\\e/g;
696 s/\x83/\\-/g;
698 # Convert some latin1 chars to troff equivalents
699 s/\xa0/\\ /g; # non-breaking space
701 print enc $_;
706 close STDOUT or kark N_("%s: error writing to %s (%s)"), $this_program,
707 $opt_output || 'stdout', $!;
709 exit;
711 # Get program basename, and strip libtool "lt-" prefix if required.
712 sub program_basename
714 local $_ = shift;
715 s!.*/!!;
716 s/^lt-// if $opt_libtool;
720 # Call program with given option and return results.
721 sub get_option_value
723 my ($prog, $opt) = @_;
724 my $stderr = $discard_stderr ? '/dev/null' : '&1';
725 my $value = join '',
726 map { s/ +$//; expand $_ }
727 map { dec $_ }
728 `$prog $opt 2>$stderr`;
730 unless ($value)
732 my $err = N_("%s: can't get `%s' info from %s%s");
733 my $extra = $discard_stderr
734 ? "\n" . N_("Try `--no-discard-stderr' if option outputs to stderr")
735 : '';
737 kark $err, $this_program, $opt, $prog, $extra;
740 $value;
743 # Convert option dashes to \- to stop nroff from hyphenating 'em, and
744 # embolden. Option arguments get italicised.
745 sub convert_option
747 local $_ = '\fB' . shift;
749 s/-/\x83/g;
750 unless (s/\[=(.*)\]$/\\fR[=\\fI$1\\fR]/)
752 s/=(.)/\\fR=\\fI$1/;
753 s/ (.)/ \\fI$1/;
754 $_ .= '\fR';
760 # Insert spacing escape characters \, and \/ before and after italic text. See
761 # https://www.gnu.org/software/groff/manual/html_node/Ligatures-and-Kerning.html
762 sub fix_italic_spacing
764 local $_ = shift;
765 s!\\fI(.*?)\\f([BRP])!\\fI\\,$1\\/\\f$2!g;
766 return $_;