3 # Generate a short man page from --help and --version output.
4 # Copyright (C) 1997-2025 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)
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/
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.49.3';
36 die "$this_program: no locale support (Locale::gettext required)\n"
37 unless $locale eq 'C';
42 sub enc_user
{ $_[0] }
43 sub kark
{ die +(sprintf shift, @_), "\n" }
49 sub fix_italic_spacing
;
51 my $version_info = enc_user
sprintf _
(<<'EOT'), $this_program, $this_version;
54 Copyright (C) 1997-2025 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>
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>.
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,
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,
121 Getopt
::Long
::config
('bundling');
122 die $help_info unless GetOptions
%opt_def and @ARGV == 1;
127 my %append_match = ();
128 my @sections = (); # retain order of include file or in-line *section*s
130 # Process include file (if given). Format is:
132 # Optional initial text, ignored. May include lines starting with `-'
133 # which are processed as options.
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.
141 # Verbatim text to be inserted at the start of the named section.
144 # Verbatim text to replace the named section.
147 # Verbatim text to be appended to the end of the named section.
150 # Verbatim text for inclusion below a paragraph matching `pattern'.
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;
166 # Convert input to internal Perl format, so that multibyte
167 # sequences are treated as single characters.
171 if (/^\[([^]]+)\]\s*$/)
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'))
193 push @sections, $key;
198 if (m!^/(.*)/([ims]*)\s*$!)
200 my $pat = $2 ?
"(?$2)$1" : $1;
203 eval { $key = qr
($pat) };
206 $@
=~ s/ at .*? line \d.*//;
210 $hash = \
%append_match;
214 # Check for options before the first section--anything else is
215 # silently ignored, allowing the first for comments and
222 local @ARGV = shellwords
$_;
234 kark N_
("%s: no valid information found in `%s'"), $this_program, $inc
238 # Compress trailing blank lines.
239 for my $hash (\
(%include, %replace, %append, %append_match))
241 for (keys %$hash) { $hash->{$_} =~ s/\n+$/\n/ }
244 # Grab help and version info from executable.
245 my $help_text = get_option_value
$ARGV[0], $help_option;
246 $version_text ||= get_option_value
$ARGV[0], $version_option;
248 # By default the generated manual pages will include the current date. This may
249 # however be overridden by setting the environment variable $SOURCE_DATE_EPOCH
250 # to an integer value of the seconds since the UNIX epoch. This is primarily
251 # intended to support reproducible builds (wiki.debian.org/ReproducibleBuilds)
252 # and will additionally ensure that the output date string is UTC.
253 my $epoch_secs = time;
254 if (exists $ENV{SOURCE_DATE_EPOCH
} and $ENV{SOURCE_DATE_EPOCH
} =~ /^(\d+)$/)
260 # Translators: the following message is a strftime(3) format string, which in
261 # the English version expands to the month as a word and the full year. It
262 # is used on the footer of the generated manual pages. If in doubt, you may
263 # just use %x as the value (which should be the full locale-specific date).
264 my $date = strftime _
("%B %Y"), localtime $epoch_secs;
265 my $program = program_basename
$ARGV[0];
266 my $package = $program;
271 unlink $opt_output or kark N_
("%s: can't unlink %s (%s)"),
272 $this_program, $opt_output, $! if -e
$opt_output;
274 open STDOUT
, ">$opt_output"
275 or kark N_
("%s: can't create %s (%s)"), $this_program, $opt_output, $!;
278 # The first line of the --version information is assumed to be in one
279 # of the following formats:
282 # <program> <version>
283 # {GNU,Free} <program> <version>
284 # <program> ({GNU,Free,} <package>) <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) +)?[^)]+)\) +(\S.*)$/ or
293 /^(\S+) +- +((?:(?:GNU|Free) +)?\S.*) +- +(\S.*)$/ or
294 /^(\S+) +- +((?:(?:GNU|Free) +)?\S+) +(\S.*)$/)
296 $program = program_basename
$1;
300 elsif (/^((?:GNU|Free) +)?(\S+) +(\S.*)$/)
302 $program = program_basename
$2;
303 $package = $1 ?
"$1$program" : $program;
311 # No info for `info' itself.
312 $opt_no_info = 1 if $program eq 'info';
316 # --name overrides --include contents.
317 $replace{_
('NAME')} = "$program \\- $opt_name\n";
320 # Translators: "NAME", "SYNOPSIS" and other one or two word strings in all
321 # upper case are manual page section headings. The man(1) manual page in your
322 # language, if available should provide the conventional translations.
323 for ($replace{_
('NAME')} || ($include{_
('NAME')} ||= ''))
325 if ($_) # Use first name given as $program
327 $program = $1 if /^([^\s,]+)(?:,?\s*[^\s,\\-]+)*\s+\\?-/;
329 else # Set a default (useless) NAME paragraph.
331 $_ = sprintf _
("%s \\- manual page for %s %s") . "\n", $program,
336 # Man pages traditionally have the page title in caps.
337 my $PROGRAM = uc $program;
339 # Set default page head/footers.
340 $source ||= "$package $version";
345 if (/^(1[Mm]|8)/) { $manual = _
('System Administration Utilities') }
346 elsif (/^6/) { $manual = _
('Games') }
347 else { $manual = _
('User Commands') }
351 # Extract usage clause(s) [if any] for SYNOPSIS.
352 # Translators: "Usage" and "or" here are patterns (regular expressions) which
353 # are used to match the usage synopsis in program output. An example from cp
354 # (GNU coreutils) which contains both strings:
355 # Usage: cp [OPTION]... [-T] SOURCE DEST
356 # or: cp [OPTION]... SOURCE... DIRECTORY
357 # or: cp [OPTION]... -t DIRECTORY SOURCE...
358 my $PAT_USAGE = _
('Usage');
359 my $PAT_USAGE_CONT = _
('or');
360 if ($help_text =~ s/^($PAT_USAGE):( +(\S+))(.*)((?:\n(?: {6}\1| *($PAT_USAGE_CONT): +\S).*)*)//om)
367 for (split /\n/) { s/^ *(($PAT_USAGE_CONT): +)?//o; push @syn, $_ }
373 $synopsis .= ".br\n" if $synopsis;
375 s/^lt-// if $opt_libtool;
377 $synopsis .= ".B $1\n";
379 s/(([][]|\.\.+)+)/\\fR$1\\fI/g;
380 s/^/\\fI/ unless s/^\\fR//;
388 $_ = fix_italic_spacing
$_;
392 $include{_
('SYNOPSIS')} .= $synopsis;
395 # Process text, initial section is DESCRIPTION.
396 my $sect = _
('DESCRIPTION');
397 $_ = "$help_text\n\n$version_text";
399 # Normalise paragraph breaks.
404 # Join hyphenated lines.
405 s/([A-Za-z])-\n *([A-Za-z])/$1$2/g;
407 # Temporarily exchange leading dots, apostrophes and backslashes for
413 # Translators: patterns are used to match common program output. In the source
414 # these strings are all of the form of "my $PAT_something = _('...');" and are
415 # regular expressions. If there is more than one commonly used string, you
416 # may separate alternatives with "|". Spaces in these expressions are written
417 # as " +" to indicate that more than one space may be matched. The string
418 # "(?:[\\w-]+ +)?" in the bug reporting pattern is used to indicate an
419 # optional word, so that either "Report bugs" or "Report _program_ bugs" will
421 my $PAT_BUGS = _
('Report +(?:[\w-]+ +)?bugs|Email +bug +reports +to');
422 my $PAT_AUTHOR = _
('Written +by');
423 my $PAT_OPTIONS = _
('Options');
424 my $PAT_ENVIRONMENT = _
('Environment');
425 my $PAT_FILES = _
('Files');
426 my $PAT_EXAMPLES = _
('Examples');
427 my $PAT_FREE_SOFTWARE = _
('This +is +free +software');
429 # Start a new paragraph (if required) for these.
430 s/([^\n])\n($PAT_BUGS|$PAT_AUTHOR) /$1\n\n$2 /og;
432 # Convert iso-8859-1 copyright symbol or (c) to nroff
434 s/^Copyright +(?:\xa9|\([Cc]\))/Copyright \\(co/mg;
438 # Convert some standard paragraph names.
439 if (s/^($PAT_OPTIONS): *\n+//o)
441 $sect = _
('OPTIONS');
444 if (s/^($PAT_ENVIRONMENT): *\n+//o)
446 $sect = _
('ENVIRONMENT');
449 if (s/^($PAT_FILES): *\n+//o)
454 elsif (s/^($PAT_EXAMPLES): *\n+//o)
456 $sect = _
('EXAMPLES');
460 # Custom section indicated by a line containing "*Section Name*".
461 if (s/^\*(\w(.*\w)?)\* *\n+//)
464 $sect =~ tr/*/ /; # also accept *Section*Name*
465 push @sections, $sect;
472 $sect = _
('COPYRIGHT');
475 # Bug reporting section.
476 elsif (/^($PAT_BUGS) /o)
478 $sect = _
('REPORTING BUGS');
482 elsif (/^($PAT_AUTHOR)/o)
487 # Examples, indicated by an indented leading $, % or > are
488 # rendered in a constant width font.
489 if (/^( +)([\$\%>] )\S/)
494 while (s/^$indent\Q$prefix\E(\S.*)\n*//)
496 $include{$sect} .= "$break\n\\f(CW$prefix$1\\fR\n";
505 # Sub-sections have a trailing colon and the second line indented.
506 if (s/^(\S.*:) *\n / /)
508 $matched .= $& if %append_match;
509 $include{$sect} .= qq(.SS
"$1"\n);
515 # Option with description.
516 if (s/^( {1,10}([+-]\S.*?))(?:( +(?!-))|\n( {20,}))(\S.*)\n//)
518 $matched .= $& if %append_match;
519 $indent = length ($4 || "$1$3");
520 $content = ".TP\n\x84$2\n\x84$5\n";
523 # Indent may be different on second line.
524 $indent = length $& if /^ {20,}/;
528 # Option without description.
529 elsif (s/^ {1,10}([+-]\S.*)\n//)
531 $matched .= $& if %append_match;
532 $content = ".HP\n\x84$1\n";
533 $indent = 80; # not continued
536 # Indented paragraph with tag.
537 elsif (s/^( +(\S.*?))(?:( +)|\n( {20,}))(\S.*)\n//)
539 $matched .= $& if %append_match;
540 $indent = length ($4 || "$1$3");
541 $content = ".TP\n\x84$2\n\x84$5\n";
544 # Indented paragraph.
545 elsif (s/^( +)(\S.*)\n//)
547 $matched .= $& if %append_match;
549 $content = ".IP\n\x84$2\n";
552 # Left justified paragraph.
556 $matched .= $& if %append_match;
557 $content = ".PP\n" if $include{$sect};
561 # Append continuations.
562 while ($indent ?
s/^ {$indent}(\S.*)\n// : s/^(\S.*)\n//)
564 $matched .= $& if %append_match;
565 $content .= "\x84$1\n";
568 # Move to next paragraph.
573 # Leading dot and apostrophe protection.
578 # Examples should be verbatim.
579 unless ($sect eq _
('EXAMPLES'))
582 s/(^|[ (])(-[][\w=-]+)/$1 . convert_option $2/mge;
584 # Italicise filenames: /a/b, $VAR/c/d, ~/e/f
586 (^|[ (]) # space/punctuation before
588 (?
:\
$\w
+|~)?
# leading variable, or tilde
589 (?
:/\w
(?
:[\w
.-]*\w
)?
)+ # path components
591 ($|[ ,;.)]) # space/punctuation after
594 $_ = fix_italic_spacing
$_;
597 # Escape remaining hyphens.
600 if ($sect eq _
('COPYRIGHT'))
602 # Insert line breaks before additional copyright messages
603 # and the disclaimer.
604 s/\n(Copyright |$PAT_FREE_SOFTWARE)/\n.br\n$1/og;
606 elsif ($sect eq _
('REPORTING BUGS'))
608 # Handle multi-line bug reporting sections of the form:
610 # Report <program> bugs to <addr>
611 # GNU <package> home page: <url>
613 s/\n([[:upper:]])/\n.br\n$1/g;
617 # Check if matched paragraph contains /pat/.
620 for my $pat (keys %append_match)
622 if ($matched =~ $pat)
624 $content .= ".PP\n" unless $append_match{$pat} =~ /^\./;
625 $content .= $append_match{$pat};
630 $include{$sect} .= $content;
633 # Refer to the real documentation.
634 unless ($opt_no_info)
636 my $info_page = $opt_info || $program;
638 $sect = _
('SEE ALSO');
639 $include{$sect} .= ".PP\n" if $include{$sect};
640 $include{$sect} .= sprintf _
(<<'EOT'), $program, $program, $info_page;
641 The full documentation for
643 is maintained as a Texinfo manual. If the
647 programs are properly installed at your site, the command
651 should give you access to the complete manual.
655 # Append additional text.
656 while (my ($sect, $text) = each %append)
658 $include{$sect} .= $append{$sect};
662 while (my ($sect, $text) = each %replace)
664 $include{$sect} = $replace{$sect};
669 .\\" DO NOT MODIFY THIS FILE! It was generated by $this_program $this_version.
670 .TH $PROGRAM "$section" "$date" "$source" "$manual"
674 my @pre = (_
('NAME'), _
('SYNOPSIS'), _
('DESCRIPTION'), _
('OPTIONS'));
675 my @post = (_
('ENVIRONMENT'), _
('FILES'), _
('EXAMPLES'), _
('AUTHOR'),
676 _
('REPORTING BUGS'), _
('COPYRIGHT'), _
('SEE ALSO'));
677 my %filter = map { $_ => 1 } @pre, @post;
681 for my $sect (@pre, (grep !$filter{$_}, @sections), @post)
683 next if $done{$sect}++; # ignore duplicates
684 next unless $include{$sect};
687 my $quote = $sect =~ /\W/ ?
'"' : '';
688 print enc
".SH $quote$sect$quote\n";
690 for ($include{$sect})
692 # Replace leading dot, apostrophe, backslash and hyphen
699 # Convert some latin1 chars to troff equivalents.
700 s/\xa0/\\ /g; # non-breaking space
707 close STDOUT
or kark N_
("%s: error writing to %s (%s)"), $this_program,
708 $opt_output || 'stdout', $!;
712 # Get program basename, and strip libtool "lt-" prefix if required.
717 s/^lt-// if $opt_libtool;
721 # Call program with given option and return results.
724 my ($prog, $opt) = @_;
725 my $stderr = $discard_stderr ?
'/dev/null' : '&1';
727 map { s/ +$//; expand
$_ }
729 `$prog $opt 2>$stderr`;
733 my $err = N_
("%s: can't get `%s' info from %s%s");
734 my $extra = $discard_stderr
735 ?
"\n" . N_
("Try `--no-discard-stderr' if option outputs to stderr")
738 kark
$err, $this_program, $opt, $prog, $extra;
744 # Convert option dashes to \- to stop nroff from hyphenating 'em, and
745 # embolden. Option arguments get italicised.
748 local $_ = '\fB' . shift;
751 unless (s/\[=(.*)\]$/\\fR[=\\fI$1\\fR]/)
761 # Insert spacing escape characters \, and \/ before and after italic text. See
762 # https://www.gnu.org/software/groff/manual/html_node/Ligatures-and-Kerning.html
763 sub fix_italic_spacing
766 s!\\fI(.*?)\\f([BRP])!\\fI\\,$1\\/\\f$2!g;