sync: fix build with separate $(LIB_FDATASYNC)
[coreutils.git] / man / help2man
blobfe786ac2290ba83746b9272992f724706c7cf747
1 #!/usr/bin/perl -w
3 # Generate a short man page from --help and --version output.
4 # Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2009,
5 # 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3, or (at your option)
10 # any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, see <http://www.gnu.org/licenses/>.
20 # Written by Brendan O'Dea <bod@debian.org>
21 # Available from ftp://ftp.gnu.org/gnu/help2man/
23 use 5.008;
24 use strict;
25 use Getopt::Long;
26 use Text::Tabs qw(expand);
27 use POSIX qw(strftime setlocale LC_ALL);
29 my $this_program = 'help2man';
30 my $this_version = '1.43.3';
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;
50 my $version_info = enc_user sprintf _(<<'EOT'), $this_program, $this_version;
51 GNU %s %s
53 Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2009, 2010,
54 2011, 2012, 2013 Free Software Foundation, Inc.
55 This is free software; see the source for copying conditions. There is NO
56 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
58 Written by Brendan O'Dea <bod@debian.org>
59 EOT
61 my $help_info = enc_user sprintf _(<<'EOT'), $this_program, $this_program;
62 `%s' generates a man page out of `--help' and `--version' output.
64 Usage: %s [OPTION]... EXECUTABLE
66 -n, --name=STRING description for the NAME paragraph
67 -s, --section=SECTION section number for manual page (1, 6, 8)
68 -m, --manual=TEXT name of manual (User Commands, ...)
69 -S, --source=TEXT source of program (FSF, Debian, ...)
70 -L, --locale=STRING select locale (default "C")
71 -i, --include=FILE include material from `FILE'
72 -I, --opt-include=FILE include material from `FILE' if it exists
73 -o, --output=FILE send output to `FILE'
74 -p, --info-page=TEXT name of Texinfo manual
75 -N, --no-info suppress pointer to Texinfo manual
76 -l, --libtool exclude the `lt-' from the program name
77 --help print this help, then exit
78 --version print version number, then exit
80 EXECUTABLE should accept `--help' and `--version' options and produce output on
81 stdout although alternatives may be specified using:
83 -h, --help-option=STRING help option string
84 -v, --version-option=STRING version option string
85 --version-string=STRING version string
86 --no-discard-stderr include stderr when parsing option output
88 Report bugs to <bug-help2man@gnu.org>.
89 EOT
91 my $section = 1;
92 my $manual = '';
93 my $source = '';
94 my $help_option = '--help';
95 my $version_option = '--version';
96 my $discard_stderr = 1;
97 my ($opt_name, @opt_include, $opt_output, $opt_info, $opt_no_info, $opt_libtool,
98 $version_text);
100 my %opt_def = (
101 'n|name=s' => \$opt_name,
102 's|section=s' => \$section,
103 'm|manual=s' => \$manual,
104 'S|source=s' => \$source,
105 'L|locale=s' => sub { configure_locale pop },
106 'i|include=s' => sub { push @opt_include, [ pop, 1 ] },
107 'I|opt-include=s' => sub { push @opt_include, [ pop, 0 ] },
108 'o|output=s' => \$opt_output,
109 'p|info-page=s' => \$opt_info,
110 'N|no-info' => \$opt_no_info,
111 'l|libtool' => \$opt_libtool,
112 'help' => sub { print $help_info; exit },
113 'version' => sub { print $version_info; exit },
114 'h|help-option=s' => \$help_option,
115 'v|version-option=s' => \$version_option,
116 'version-string=s' => \$version_text,
117 'discard-stderr!' => \$discard_stderr,
120 # Parse options.
121 Getopt::Long::config('bundling');
122 die $help_info unless GetOptions %opt_def and @ARGV == 1;
124 my %include = ();
125 my %replace = ();
126 my %append = ();
127 my %append_match = ();
128 my @include = (); # retain order given in include file
130 # Process include file (if given). Format is:
132 # Optional initial text, ignored. May include lines starting with `-'
133 # which are processed as options.
135 # [section]
136 # Verbatim text to be included in the named section. By default at
137 # the start, but in the case of `name' and `synopsis' the content
138 # will replace the autogenerated contents.
140 # [<section]
141 # Verbatim text to be inserted at the start of the named section.
143 # [=section]
144 # Verbatim text to replace the named section.
146 # [>section]
147 # Verbatim text to be appended to the end of the named section.
149 # /pattern/
150 # Verbatim text for inclusion below a paragraph matching `pattern'.
153 while (@opt_include)
155 my ($inc, $required) = @{shift @opt_include};
157 next unless -f $inc or $required;
158 kark N_("%s: can't open `%s' (%s)"), $this_program, $inc, $!
159 unless open INC, $inc;
161 my $key;
162 my $hash;
164 while (<INC>)
166 # Convert input to internal Perl format, so that multibyte
167 # sequences are treated as single characters.
168 $_ = dec $_;
170 # [section]
171 if (/^\[([^]]+)\]\s*$/)
173 $key = uc $1;
174 $key =~ s/^\s+//;
175 $key =~ s/\s+$//;
176 $hash = \%include;
177 # Handle explicit [<section], [=section] and [>section]
178 if ($key =~ s/^([<>=])\s*//)
180 if ($1 eq '>') { $hash = \%append; }
181 elsif ($1 eq '=') { $hash = \%replace; }
183 # NAME/SYNOPSIS replace by default
184 elsif ($key eq _('NAME') or $key eq _('SYNOPSIS'))
186 $hash = \%replace;
188 else
190 $hash = \%include;
193 push @include, $key
194 unless $include{$key} or $replace{$key} or $append{$key};
196 next;
199 # /pattern/
200 if (m!^/(.*)/([ims]*)\s*$!)
202 my $pat = $2 ? "(?$2)$1" : $1;
204 # Check pattern.
205 eval { $key = qr($pat) };
206 if ($@)
208 $@ =~ s/ at .*? line \d.*//;
209 die "$inc:$.:$@";
212 $hash = \%append_match;
213 next;
216 # Check for options before the first section--anything else is
217 # silently ignored, allowing the first for comments and
218 # revision info.
219 unless ($key)
221 # handle options
222 if (/^-/)
224 local @ARGV = split;
225 GetOptions %opt_def;
228 next;
231 $hash->{$key} .= $_;
234 close INC;
236 kark N_("%s: no valid information found in `%s'"), $this_program, $inc
237 unless $key;
240 # Compress trailing blank lines.
241 for my $hash (\(%include, %replace, %append, %append_match))
243 for (keys %$hash) { $hash->{$_} =~ s/\n+$/\n/ }
246 # Grab help and version info from executable.
247 my $help_text = get_option_value $ARGV[0], $help_option;
248 $version_text ||= get_option_value $ARGV[0], $version_option;
250 # Translators: the following message is a strftime(3) format string, which in
251 # the English version expands to the month as a word and the full year. It
252 # is used on the footer of the generated manual pages. If in doubt, you may
253 # just use %x as the value (which should be the full locale-specific date).
254 my $date = enc strftime _("%B %Y"), localtime;
255 my $program = program_basename $ARGV[0];
256 my $package = $program;
257 my $version;
259 if ($opt_output)
261 unlink $opt_output or kark N_("%s: can't unlink %s (%s)"),
262 $this_program, $opt_output, $! if -e $opt_output;
264 open STDOUT, ">$opt_output"
265 or kark N_("%s: can't create %s (%s)"), $this_program, $opt_output, $!;
268 # The first line of the --version information is assumed to be in one
269 # of the following formats:
271 # <version>
272 # <program> <version>
273 # {GNU,Free} <program> <version>
274 # <program> ({GNU,Free} <package>) <version>
275 # <program> - {GNU,Free} <package> <version>
277 # and separated from any copyright/author details by a blank line.
279 ($_, $version_text) = ((split /\n+/, $version_text, 2), '');
281 if (/^(\S+) +\(((?:GNU|Free) +[^)]+)\) +(.*)/ or
282 /^(\S+) +- *((?:GNU|Free) +\S+) +(.*)/)
284 $program = program_basename $1;
285 $package = $2;
286 $version = $3;
288 elsif (/^((?:GNU|Free) +)?(\S+) +(.*)/)
290 $program = program_basename $2;
291 $package = $1 ? "$1$program" : $program;
292 $version = $3;
294 else
296 $version = $_;
299 # No info for `info' itself.
300 $opt_no_info = 1 if $program eq 'info';
302 if ($opt_name)
304 # --name overrides --include contents.
305 $replace{_('NAME')} = "$program \\- $opt_name\n";
308 # Translators: "NAME", "SYNOPSIS" and other one or two word strings in all
309 # upper case are manual page section headings. The man(1) manual page in your
310 # language, if available should provide the conventional translations.
311 for ($replace{_('NAME')} || ($include{_('NAME')} ||= ''))
313 if ($_) # Use first name given as $program
315 $program = $1 if /^([^\s,]+)(?:,?\s*[^\s,\\-]+)*\s+\\?-/;
317 else # Set a default (useless) NAME paragraph.
319 $_ = sprintf _("%s \\- manual page for %s %s") . "\n", $program,
320 $program, $version;
324 # Man pages traditionally have the page title in caps.
325 my $PROGRAM = uc $program;
327 # Set default page head/footers
328 $source ||= "$program $version";
329 unless ($manual)
331 for ($section)
333 if (/^(1[Mm]|8)/) { $manual = enc _('System Administration Utilities') }
334 elsif (/^6/) { $manual = enc _('Games') }
335 else { $manual = enc _('User Commands') }
339 # Extract usage clause(s) [if any] for SYNOPSIS.
340 # Translators: "Usage" and "or" here are patterns (regular expressions) which
341 # are used to match the usage synopsis in program output. An example from cp
342 # (GNU coreutils) which contains both strings:
343 # Usage: cp [OPTION]... [-T] SOURCE DEST
344 # or: cp [OPTION]... SOURCE... DIRECTORY
345 # or: cp [OPTION]... -t DIRECTORY SOURCE...
346 my $PAT_USAGE = _('Usage');
347 my $PAT_USAGE_CONT = _('or');
348 if ($help_text =~ s/^($PAT_USAGE):( +(\S+))(.*)((?:\n(?: {6}\1| *($PAT_USAGE_CONT): +\S).*)*)//om)
350 my @syn = $3 . $4;
352 if ($_ = $5)
354 s/^\n//;
355 for (split /\n/) { s/^ *(($PAT_USAGE_CONT): +)?//o; push @syn, $_ }
358 my $synopsis = '';
359 for (@syn)
361 $synopsis .= ".br\n" if $synopsis;
362 s!^\S*/!!;
363 s/^lt-// if $opt_libtool;
364 s/^(\S+) *//;
365 $synopsis .= ".B $1\n";
366 s/\s+$//;
367 s/(([][]|\.\.+)+)/\\fR$1\\fI/g;
368 s/^/\\fI/ unless s/^\\fR//;
369 $_ .= '\fR';
370 s/(\\fI)( *)/$2$1/g;
371 s/\\fI\\fR//g;
372 s/^\\fR//;
373 s/\\fI$//;
374 s/^\./\\&./;
376 $synopsis .= "$_\n";
379 $include{_('SYNOPSIS')} .= $synopsis;
382 # Process text, initial section is DESCRIPTION.
383 my $sect = _('DESCRIPTION');
384 $_ = "$help_text\n\n$version_text";
386 # Normalise paragraph breaks.
387 s/^\n+//;
388 s/\n*$/\n/;
389 s/\n\n+/\n\n/g;
391 # Join hyphenated lines.
392 s/([A-Za-z])-\n *([A-Za-z])/$1$2/g;
394 # Temporarily exchange leading dots, apostrophes and backslashes for
395 # tokens.
396 s/^\./\x80/mg;
397 s/^'/\x81/mg;
398 s/\\/\x82/g;
400 # Translators: patterns are used to match common program output. In the source
401 # these strings are all of the form of "my $PAT_something = _('...');" and are
402 # regular expressions. If there is more than one commonly used string, you
403 # may separate alternatives with "|". Spaces in these expressions are written
404 # as " +" to indicate that more than one space may be matched. The string
405 # "(?:[\\w-]+ +)?" in the bug reporting pattern is used to indicate an
406 # optional word, so that either "Report bugs" or "Report _program_ bugs" will
407 # be matched.
408 my $PAT_BUGS = _('Report +(?:[\w-]+ +)?bugs|' .
409 'Email +bug +reports +to|' .
410 '.* +online +help:');
411 my $PAT_AUTHOR = _('Written +by');
412 my $PAT_OPTIONS = _('Options');
413 my $PAT_ENVIRONMENT = _('Environment');
414 my $PAT_FILES = _('Files');
415 my $PAT_EXAMPLES = _('Examples');
416 my $PAT_FREE_SOFTWARE = _('This +is +free +software');
417 my $PAT_SEE_ALSO = _('Full +documentation');
419 # Start a new paragraph (if required) for these.
420 s/([^\n])\n($PAT_BUGS|$PAT_AUTHOR|$PAT_SEE_ALSO) /$1\n\n$2 /og;
422 # Convert iso-8859-1 copyright symbol or (c) to nroff
423 # character.
424 s/^Copyright +(?:\xa9|\([Cc]\))/Copyright \\(co/mg;
426 while (length)
428 # Convert some standard paragraph names.
429 if (s/^($PAT_OPTIONS): *\n//o)
431 $sect = _('OPTIONS');
432 next;
434 if (s/^($PAT_ENVIRONMENT): *\n//o)
436 $sect = _('ENVIRONMENT');
437 next;
439 if (s/^($PAT_FILES): *\n//o)
441 $sect = _('FILES');
442 next;
444 elsif (s/^($PAT_EXAMPLES): *\n//o)
446 $sect = _('EXAMPLES');
447 next;
450 # Copyright section
451 if (/^Copyright /)
453 $sect = _('COPYRIGHT');
456 # Bug reporting section.
457 elsif (/^($PAT_BUGS) /o)
459 $sect = _('REPORTING BUGS');
462 # Author section.
463 elsif (/^($PAT_AUTHOR)/o)
465 $sect = _('AUTHOR');
468 elsif (/^($PAT_SEE_ALSO)/o)
470 $sect = _('SEE ALSO');
471 $opt_no_info = 1;
474 # Examples, indicated by an indented leading $, % or > are
475 # rendered in a constant width font.
476 if (/^( +)([\$\%>] )\S/)
478 my $indent = $1;
479 my $prefix = $2;
480 my $break = '.IP';
481 while (s/^$indent\Q$prefix\E(\S.*)\n*//)
483 $include{$sect} .= "$break\n\\f(CW$prefix$1\\fR\n";
484 $break = '.br';
487 next;
490 my $matched = '';
492 # Sub-sections have a trailing colon and the second line indented.
493 if (s/^(\S.*:) *\n / /)
495 $matched .= $& if %append_match;
496 $include{$sect} .= qq(.SS "$1"\n);
499 my $indent = 0;
500 my $content = '';
502 # Option with description.
503 if (s/^( {1,10}([+-]\S.*?))(?:( +(?!-))|\n( {20,}))(\S.*)\n//)
505 $matched .= $& if %append_match;
506 $indent = length ($4 || "$1$3");
507 $content = ".TP\n\x84$2\n\x84$5\n";
508 unless ($4)
510 # Indent may be different on second line.
511 $indent = length $& if /^ {20,}/;
515 # Option without description.
516 elsif (s/^ {1,10}([+-]\S.*)\n//)
518 $matched .= $& if %append_match;
519 $content = ".HP\n\x84$1\n";
520 $indent = 80; # not continued
523 # Indented paragraph with tag.
524 elsif (s/^( +(\S.*?) +)(\S.*)\n//)
526 $matched .= $& if %append_match;
527 $indent = length $1;
528 $content = ".TP\n\x84$2\n\x84$3\n";
531 # Indented paragraph.
532 elsif (s/^( +)(\S.*)\n//)
534 $matched .= $& if %append_match;
535 $indent = length $1;
536 $content = ".IP\n\x84$2\n";
539 # Left justified paragraph.
540 else
542 s/(.*)\n//;
543 $matched .= $& if %append_match;
544 $content = ".PP\n" if $include{$sect};
545 $content .= "$1\n";
548 # Append continuations.
549 while ($indent ? s/^ {$indent}(\S.*)\n// : s/^(\S.*)\n//)
551 $matched .= $& if %append_match;
552 $content .= "\x84$1\n";
555 # Move to next paragraph.
556 s/^\n+//;
558 for ($content)
560 # Leading dot and apostrophe protection.
561 s/\x84\./\x80/g;
562 s/\x84'/\x81/g;
563 s/\x84//g;
565 # Examples should be verbatim.
566 unless ($sect eq _('EXAMPLES'))
568 # Convert options.
569 s/(^|[ (])(-[][\w=-]+)/$1 . convert_option $2/mge;
571 # Italicise filenames: /a/b, $VAR/c/d, ~/e/f
573 (^|[ (]) # space/punctuation before
575 (?:\$\w+|~)? # leading variable, or tilde
576 (?:/\w(?:[\w.-]*\w)?)+ # path components
578 ($|[ ,;.)]) # space/punctuation after
579 !$1\\fI$2\\fP$3!xmg;
582 # Escape remaining hyphens.
583 s/-/\x83/g;
585 if ($sect eq _('COPYRIGHT'))
587 # Insert line breaks before additional copyright messages
588 # and the disclaimer.
589 s/\n(Copyright |$PAT_FREE_SOFTWARE)/\n.br\n$1/og;
591 elsif ($sect eq _('REPORTING BUGS'))
593 # Handle multi-line bug reporting sections of the form:
595 # Report <program> bugs to <addr>
596 # GNU <package> home page: <url>
597 # ...
598 s/\n([[:upper:]])/\n.br\n$1/g;
600 elsif ($sect eq _('SEE ALSO'))
602 # Handle external references of the form:
604 # GNU <package> online resources: <addr>
605 # Full documentation at: <addr>
606 # or available locally via: info ...
608 s/\'/\\(aq/g; # shell quotes for info command
609 s/\n(.)/\n.br\n$1/g; # separate lines for each item
613 # Check if matched paragraph contains /pat/.
614 if (%append_match)
616 for my $pat (keys %append_match)
618 if ($matched =~ $pat)
620 $content .= ".PP\n" unless $append_match{$pat} =~ /^\./;
621 $content .= $append_match{$pat};
626 $include{$sect} .= $content;
629 # Refer to the real documentation.
630 unless ($opt_no_info)
632 my $info_page = $opt_info || $program;
634 $sect = _('SEE ALSO');
635 $include{$sect} .= ".PP\n" if $include{$sect};
636 $include{$sect} .= sprintf _(<<'EOT'), $program, $program, $info_page;
637 The full documentation for
638 .B %s
639 is maintained as a Texinfo manual. If the
640 .B info
642 .B %s
643 programs are properly installed at your site, the command
645 .B info %s
647 should give you access to the complete manual.
651 # Append additional text.
652 while (my ($sect, $text) = each %append)
654 $include{$sect} .= $append{$sect};
657 # Replace sections.
658 while (my ($sect, $text) = each %replace)
660 $include{$sect} = $replace{$sect};
663 # Output header.
664 print <<EOT;
665 .\\" DO NOT MODIFY THIS FILE! It was generated by $this_program $this_version.
666 .TH $PROGRAM "$section" "$date" "$source" "$manual"
669 # Section ordering.
670 my @pre = (_('NAME'), _('SYNOPSIS'), _('DESCRIPTION'), _('OPTIONS'),
671 _('ENVIRONMENT'), _('FILES'), _('EXAMPLES'));
673 my @post = (_('AUTHOR'), _('REPORTING BUGS'), _('COPYRIGHT'), _('SEE ALSO'));
674 my $filter = join '|', @pre, @post;
676 # Output content.
677 for my $sect (@pre, (grep ! /^($filter)$/o, @include), @post)
679 if ($include{$sect})
681 my $quote = $sect =~ /\W/ ? '"' : '';
682 print enc ".SH $quote$sect$quote\n";
684 for ($include{$sect})
686 # Replace leading dot, apostrophe, backslash and hyphen
687 # tokens.
688 s/\x80/\\&./g;
689 s/\x81/\\&'/g;
690 s/\x82/\\e/g;
691 s/\x83/\\-/g;
693 # Convert some latin1 chars to troff equivalents
694 s/\xa0/\\ /g; # non-breaking space
696 print enc $_;
701 close STDOUT or kark N_("%s: error writing to %s (%s)"), $this_program,
702 $opt_output || 'stdout', $!;
704 exit;
706 # Get program basename, and strip libtool "lt-" prefix if required.
707 sub program_basename
709 local $_ = shift;
710 s!.*/!!;
711 s/^lt-// if $opt_libtool;
715 # Call program with given option and return results.
716 sub get_option_value
718 my ($prog, $opt) = @_;
719 my $stderr = $discard_stderr ? '/dev/null' : '&1';
720 my $value = join '',
721 map { s/ +$//; expand $_ }
722 map { dec $_ }
723 `$prog $opt 2>$stderr`;
725 unless ($value)
727 my $err = N_("%s: can't get `%s' info from %s%s");
728 my $extra = $discard_stderr
729 ? "\n" . N_("Try `--no-discard-stderr' if option outputs to stderr")
730 : '';
732 kark $err, $this_program, $opt, $prog, $extra;
735 $value;
738 # Convert option dashes to \- to stop nroff from hyphenating 'em, and
739 # embolden. Option arguments get italicised.
740 sub convert_option
742 local $_ = '\fB' . shift;
744 s/-/\x83/g;
745 unless (s/\[=(.*)\]$/\\fR[=\\fI$1\\fR]/)
747 s/=(.)/\\fR=\\fI$1/;
748 s/ (.)/ \\fI$1/;
749 $_ .= '\fR';