Protect against multiple inclusion.
[glibc.git] / argp / argp-help.c
blob616db9b47c97ee684340f5fe041fa4af2833f241
1 /* Hierarchial argument parsing help output
2 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Written by Miles Bader <miles@gnu.ai.mit.edu>.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public License as
8 published by the Free Software Foundation; either version 2 of the
9 License, or (at your option) any later version.
11 The GNU C Library 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 GNU
14 Library General Public License for more details.
16 You should have received a copy of the GNU Library General Public
17 License along with the GNU C Library; see the file COPYING.LIB. If not,
18 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 #ifndef _GNU_SOURCE
22 # define _GNU_SOURCE 1
23 #endif
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
29 #ifndef alloca
30 # ifdef __GNUC__
31 # define alloca __builtin_alloca
32 # define HAVE_ALLOCA 1
33 # else
34 # if defined HAVE_ALLOCA_H || defined _LIBC
35 # include <alloca.h>
36 # else
37 # ifdef _AIX
38 #pragma alloca
39 # else
40 # ifndef alloca
41 char *alloca ();
42 # endif
43 # endif
44 # endif
45 # endif
46 #endif
48 #include <stddef.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <assert.h>
52 #include <stdarg.h>
53 #include <malloc.h>
54 #include <ctype.h>
56 #ifndef _
57 /* This is for other GNU distributions with internationalized messages. */
58 # ifdef HAVE_LIBINTL_H
59 # include <libintl.h>
60 # else
61 # define dgettext(domain, msgid) (msgid)
62 # endif
63 #endif
65 #ifdef USE_IN_LIBIO
66 # define flockfile(s) _IO_flockfile (s)
67 # define funlockfile(s) _IO_funlockfile (s)
68 #endif
70 #include "argp.h"
71 #include "argp-fmtstream.h"
72 #include "argp-namefrob.h"
74 /* User-selectable (using an environment variable) formatting parameters.
76 These may be specified in an environment variable called `ARGP_HELP_FMT',
77 with a contents like: VAR1=VAL1,VAR2=VAL2,BOOLVAR2,no-BOOLVAR2
78 Where VALn must be a positive integer. The list of variables is in the
79 UPARAM_NAMES vector, below. */
81 /* Default parameters. */
82 #define DUP_ARGS 0 /* True if option argument can be duplicated. */
83 #define DUP_ARGS_NOTE 1 /* True to print a note about duplicate args. */
84 #define SHORT_OPT_COL 2 /* column in which short options start */
85 #define LONG_OPT_COL 6 /* column in which long options start */
86 #define DOC_OPT_COL 2 /* column in which doc options start */
87 #define OPT_DOC_COL 29 /* column in which option text starts */
88 #define HEADER_COL 1 /* column in which group headers are printed */
89 #define USAGE_INDENT 12 /* indentation of wrapped usage lines */
90 #define RMARGIN 79 /* right margin used for wrapping */
92 /* User-selectable (using an environment variable) formatting parameters.
93 They must all be of type `int' for the parsing code to work. */
94 struct uparams
96 /* If true, arguments for an option are shown with both short and long
97 options, even when a given option has both, e.g. `-x ARG, --longx=ARG'.
98 If false, then if an option has both, the argument is only shown with
99 the long one, e.g., `-x, --longx=ARG', and a message indicating that
100 this really means both is printed below the options. */
101 int dup_args;
103 /* This is true if when DUP_ARGS is false, and some duplicate arguments have
104 been suppressed, an explanatory message should be printed. */
105 int dup_args_note;
107 /* Various output columns. */
108 int short_opt_col;
109 int long_opt_col;
110 int doc_opt_col;
111 int opt_doc_col;
112 int header_col;
113 int usage_indent;
114 int rmargin;
116 int valid; /* True when the values in here are valid. */
119 /* This is a global variable, as user options are only ever read once. */
120 static struct uparams uparams = {
121 DUP_ARGS, DUP_ARGS_NOTE,
122 SHORT_OPT_COL, LONG_OPT_COL, DOC_OPT_COL, OPT_DOC_COL, HEADER_COL,
123 USAGE_INDENT, RMARGIN,
127 /* A particular uparam, and what the user name is. */
128 struct uparam_name
130 const char *name; /* User name. */
131 int is_bool; /* Whether it's `boolean'. */
132 size_t uparams_offs; /* Location of the (int) field in UPARAMS. */
135 /* The name-field mappings we know about. */
136 static const struct uparam_name uparam_names[] =
138 { "dup-args", 1, offsetof (struct uparams, dup_args) },
139 { "dup-args-note", 1, offsetof (struct uparams, dup_args_note) },
140 { "short-opt-col", 0, offsetof (struct uparams, short_opt_col) },
141 { "long-opt-col", 0, offsetof (struct uparams, long_opt_col) },
142 { "doc-opt-col", 0, offsetof (struct uparams, doc_opt_col) },
143 { "opt-doc-col", 0, offsetof (struct uparams, opt_doc_col) },
144 { "header-col", 0, offsetof (struct uparams, header_col) },
145 { "usage-indent", 0, offsetof (struct uparams, usage_indent) },
146 { "rmargin", 0, offsetof (struct uparams, rmargin) },
147 { 0 }
150 /* Read user options from the environment, and fill in UPARAMS appropiately. */
151 static void
152 fill_in_uparams (const struct argp_state *state)
154 const char *var = getenv ("ARGP_HELP_FMT");
156 #define SKIPWS(p) do { while (isspace (*p)) p++; } while (0);
158 if (var)
159 /* Parse var. */
160 while (*var)
162 SKIPWS (var);
164 if (isalpha (*var))
166 size_t var_len;
167 const struct uparam_name *un;
168 int unspec = 0, val = 0;
169 const char *arg = var;
171 while (isalnum (*arg) || *arg == '-' || *arg == '_')
172 arg++;
173 var_len = arg - var;
175 SKIPWS (arg);
177 if (*arg == '\0' || *arg == ',')
178 unspec = 1;
179 else if (*arg == '=')
181 arg++;
182 SKIPWS (arg);
185 if (unspec)
186 if (var[0] == 'n' && var[1] == 'o' && var[2] == '-')
188 val = 0;
189 var += 3;
190 var_len -= 3;
192 else
193 val = 1;
194 else if (isdigit (*arg))
196 val = atoi (arg);
197 while (isdigit (*arg))
198 arg++;
199 SKIPWS (arg);
202 for (un = uparam_names; un->name; un++)
203 if (strlen (un->name) == var_len
204 && strncmp (var, un->name, var_len) == 0)
206 if (unspec && !un->is_bool)
207 __argp_failure (state, 0, 0,
208 dgettext (state->root_argp->argp_domain, "\
209 %.*s: ARGP_HELP_FMT parameter requires a value"),
210 (int) var_len, var);
211 else
212 *(int *)((char *)&uparams + un->uparams_offs) = val;
213 break;
215 if (! un->name)
216 __argp_failure (state, 0, 0,
217 dgettext (state->root_argp->argp_domain, "\
218 %.*s: Unknown ARGP_HELP_FMT parameter"),
219 (int) var_len, var);
221 var = arg;
222 if (*var == ',')
223 var++;
225 else if (*var)
227 __argp_failure (state, 0, 0,
228 dgettext (state->root_argp->argp_domain,
229 "Garbage in ARGP_HELP_FMT: %s"), var);
230 break;
235 /* Returns true if OPT hasn't been marked invisible. Visibility only affects
236 whether OPT is displayed or used in sorting, not option shadowing. */
237 #define ovisible(opt) (! ((opt)->flags & OPTION_HIDDEN))
239 /* Returns true if OPT is an alias for an earlier option. */
240 #define oalias(opt) ((opt)->flags & OPTION_ALIAS)
242 /* Returns true if OPT is an documentation-only entry. */
243 #define odoc(opt) ((opt)->flags & OPTION_DOC)
245 /* Returns true if OPT is the end-of-list marker for a list of options. */
246 #define oend(opt) __option_is_end (opt)
248 /* Returns true if OPT has a short option. */
249 #define oshort(opt) __option_is_short (opt)
252 The help format for a particular option is like:
254 -xARG, -yARG, --long1=ARG, --long2=ARG Documentation...
256 Where ARG will be omitted if there's no argument, for this option, or
257 will be surrounded by "[" and "]" appropiately if the argument is
258 optional. The documentation string is word-wrapped appropiately, and if
259 the list of options is long enough, it will be started on a separate line.
260 If there are no short options for a given option, the first long option is
261 indented slighly in a way that's supposed to make most long options appear
262 to be in a separate column.
264 For example, the following output (from ps):
266 -p PID, --pid=PID List the process PID
267 --pgrp=PGRP List processes in the process group PGRP
268 -P, -x, --no-parent Include processes without parents
269 -Q, --all-fields Don't elide unusable fields (normally if there's
270 some reason ps can't print a field for any
271 process, it's removed from the output entirely)
272 -r, --reverse, --gratuitously-long-reverse-option
273 Reverse the order of any sort
274 --session[=SID] Add the processes from the session SID (which
275 defaults to the sid of the current process)
277 Here are some more options:
278 -f ZOT, --foonly=ZOT Glork a foonly
279 -z, --zaza Snit a zar
281 -?, --help Give this help list
282 --usage Give a short usage message
283 -V, --version Print program version
285 The struct argp_option array for the above could look like:
288 {"pid", 'p', "PID", 0, "List the process PID"},
289 {"pgrp", OPT_PGRP, "PGRP", 0, "List processes in the process group PGRP"},
290 {"no-parent", 'P', 0, 0, "Include processes without parents"},
291 {0, 'x', 0, OPTION_ALIAS},
292 {"all-fields",'Q', 0, 0, "Don't elide unusable fields (normally"
293 " if there's some reason ps can't"
294 " print a field for any process, it's"
295 " removed from the output entirely)" },
296 {"reverse", 'r', 0, 0, "Reverse the order of any sort"},
297 {"gratuitously-long-reverse-option", 0, 0, OPTION_ALIAS},
298 {"session", OPT_SESS, "SID", OPTION_ARG_OPTIONAL,
299 "Add the processes from the session"
300 " SID (which defaults to the sid of"
301 " the current process)" },
303 {0,0,0,0, "Here are some more options:"},
304 {"foonly", 'f', "ZOT", 0, "Glork a foonly"},
305 {"zaza", 'z', 0, 0, "Snit a zar"},
310 Note that the last three options are automatically supplied by argp_parse,
311 unless you tell it not to with ARGP_NO_HELP.
315 /* Returns true if CH occurs between BEG and END. */
316 static int
317 find_char (char ch, char *beg, char *end)
319 while (beg < end)
320 if (*beg == ch)
321 return 1;
322 else
323 beg++;
324 return 0;
327 struct hol_cluster; /* fwd decl */
329 struct hol_entry
331 /* First option. */
332 const struct argp_option *opt;
333 /* Number of options (including aliases). */
334 unsigned num;
336 /* A pointers into the HOL's short_options field, to the first short option
337 letter for this entry. The order of the characters following this point
338 corresponds to the order of options pointed to by OPT, and there are at
339 most NUM. A short option recorded in a option following OPT is only
340 valid if it occurs in the right place in SHORT_OPTIONS (otherwise it's
341 probably been shadowed by some other entry). */
342 char *short_options;
344 /* Entries are sorted by their group first, in the order:
345 1, 2, ..., n, 0, -m, ..., -2, -1
346 and then alphabetically within each group. The default is 0. */
347 int group;
349 /* The cluster of options this entry belongs to, or 0 if none. */
350 struct hol_cluster *cluster;
352 /* The argp from which this option came. */
353 const struct argp *argp;
356 /* A cluster of entries to reflect the argp tree structure. */
357 struct hol_cluster
359 /* A descriptive header printed before options in this cluster. */
360 const char *header;
362 /* Used to order clusters within the same group with the same parent,
363 according to the order in which they occured in the parent argp's child
364 list. */
365 int index;
367 /* How to sort this cluster with respect to options and other clusters at the
368 same depth (clusters always follow options in the same group). */
369 int group;
371 /* The cluster to which this cluster belongs, or 0 if it's at the base
372 level. */
373 struct hol_cluster *parent;
375 /* The argp from which this cluster is (eventually) derived. */
376 const struct argp *argp;
378 /* The distance this cluster is from the root. */
379 int depth;
381 /* Clusters in a given hol are kept in a linked list, to make freeing them
382 possible. */
383 struct hol_cluster *next;
386 /* A list of options for help. */
387 struct hol
389 /* An array of hol_entry's. */
390 struct hol_entry *entries;
391 /* The number of entries in this hol. If this field is zero, the others
392 are undefined. */
393 unsigned num_entries;
395 /* A string containing all short options in this HOL. Each entry contains
396 pointers into this string, so the order can't be messed with blindly. */
397 char *short_options;
399 /* Clusters of entries in this hol. */
400 struct hol_cluster *clusters;
403 /* Create a struct hol from the options in ARGP. CLUSTER is the
404 hol_cluster in which these entries occur, or 0, if at the root. */
405 static struct hol *
406 make_hol (const struct argp *argp, struct hol_cluster *cluster)
408 char *so;
409 const struct argp_option *o;
410 const struct argp_option *opts = argp->options;
411 struct hol_entry *entry;
412 unsigned num_short_options = 0;
413 struct hol *hol = malloc (sizeof (struct hol));
415 assert (hol);
417 hol->num_entries = 0;
418 hol->clusters = 0;
420 if (opts)
422 int cur_group = 0;
424 /* The first option must not be an alias. */
425 assert (! oalias (opts));
427 /* Calculate the space needed. */
428 for (o = opts; ! oend (o); o++)
430 if (! oalias (o))
431 hol->num_entries++;
432 if (oshort (o))
433 num_short_options++; /* This is an upper bound. */
436 hol->entries = malloc (sizeof (struct hol_entry) * hol->num_entries);
437 hol->short_options = malloc (num_short_options + 1);
439 assert (hol->entries && hol->short_options);
441 /* Fill in the entries. */
442 so = hol->short_options;
443 for (o = opts, entry = hol->entries; ! oend (o); entry++)
445 entry->opt = o;
446 entry->num = 0;
447 entry->short_options = so;
448 entry->group = cur_group =
449 o->group
450 ? o->group
451 : ((!o->name && !o->key)
452 ? cur_group + 1
453 : cur_group);
454 entry->cluster = cluster;
455 entry->argp = argp;
459 entry->num++;
460 if (oshort (o) && ! find_char (o->key, hol->short_options, so))
461 /* O has a valid short option which hasn't already been used.*/
462 *so++ = o->key;
463 o++;
465 while (! oend (o) && oalias (o));
467 *so = '\0'; /* null terminated so we can find the length */
470 return hol;
473 /* Add a new cluster to HOL, with the given GROUP and HEADER (taken from the
474 associated argp child list entry), INDEX, and PARENT, and return a pointer
475 to it. ARGP is the argp that this cluster results from. */
476 static struct hol_cluster *
477 hol_add_cluster (struct hol *hol, int group, const char *header, int index,
478 struct hol_cluster *parent, const struct argp *argp)
480 struct hol_cluster *cl = malloc (sizeof (struct hol_cluster));
481 if (cl)
483 cl->group = group;
484 cl->header = header;
486 cl->index = index;
487 cl->parent = parent;
488 cl->argp = argp;
489 cl->depth = parent ? parent->depth + 1 : 0;
491 cl->next = hol->clusters;
492 hol->clusters = cl;
494 return cl;
497 /* Free HOL and any resources it uses. */
498 static void
499 hol_free (struct hol *hol)
501 struct hol_cluster *cl = hol->clusters;
503 while (cl)
505 struct hol_cluster *next = cl->next;
506 free (cl);
507 cl = next;
510 if (hol->num_entries > 0)
512 free (hol->entries);
513 free (hol->short_options);
516 free (hol);
519 static inline int
520 hol_entry_short_iterate (const struct hol_entry *entry,
521 int (*func)(const struct argp_option *opt,
522 const struct argp_option *real,
523 const char *domain, void *cookie),
524 const char *domain, void *cookie)
526 unsigned nopts;
527 int val = 0;
528 const struct argp_option *opt, *real = entry->opt;
529 char *so = entry->short_options;
531 for (opt = real, nopts = entry->num; nopts > 0 && !val; opt++, nopts--)
532 if (oshort (opt) && *so == opt->key)
534 if (!oalias (opt))
535 real = opt;
536 if (ovisible (opt))
537 val = (*func)(opt, real, domain, cookie);
538 so++;
541 return val;
544 static inline int
545 hol_entry_long_iterate (const struct hol_entry *entry,
546 int (*func)(const struct argp_option *opt,
547 const struct argp_option *real,
548 const char *domain, void *cookie),
549 const char *domain, void *cookie)
551 unsigned nopts;
552 int val = 0;
553 const struct argp_option *opt, *real = entry->opt;
555 for (opt = real, nopts = entry->num; nopts > 0 && !val; opt++, nopts--)
556 if (opt->name)
558 if (!oalias (opt))
559 real = opt;
560 if (ovisible (opt))
561 val = (*func)(opt, real, domain, cookie);
564 return val;
567 /* Iterator that returns true for the first short option. */
568 static inline int
569 until_short (const struct argp_option *opt, const struct argp_option *real,
570 const char *domain, void *cookie)
572 return oshort (opt) ? opt->key : 0;
575 /* Returns the first valid short option in ENTRY, or 0 if there is none. */
576 static char
577 hol_entry_first_short (const struct hol_entry *entry)
579 return hol_entry_short_iterate (entry, until_short,
580 entry->argp->argp_domain, 0);
583 /* Returns the first valid long option in ENTRY, or 0 if there is none. */
584 static const char *
585 hol_entry_first_long (const struct hol_entry *entry)
587 const struct argp_option *opt;
588 unsigned num;
589 for (opt = entry->opt, num = entry->num; num > 0; opt++, num--)
590 if (opt->name && ovisible (opt))
591 return opt->name;
592 return 0;
595 /* Returns the entry in HOL with the long option name NAME, or 0 if there is
596 none. */
597 static struct hol_entry *
598 hol_find_entry (struct hol *hol, const char *name)
600 struct hol_entry *entry = hol->entries;
601 unsigned num_entries = hol->num_entries;
603 while (num_entries-- > 0)
605 const struct argp_option *opt = entry->opt;
606 unsigned num_opts = entry->num;
608 while (num_opts-- > 0)
609 if (opt->name && ovisible (opt) && strcmp (opt->name, name) == 0)
610 return entry;
611 else
612 opt++;
614 entry++;
617 return 0;
620 /* If an entry with the long option NAME occurs in HOL, set it's special
621 sort position to GROUP. */
622 static void
623 hol_set_group (struct hol *hol, const char *name, int group)
625 struct hol_entry *entry = hol_find_entry (hol, name);
626 if (entry)
627 entry->group = group;
630 /* Order by group: 0, 1, 2, ..., n, -m, ..., -2, -1.
631 EQ is what to return if GROUP1 and GROUP2 are the same. */
632 static int
633 group_cmp (int group1, int group2, int eq)
635 if (group1 == group2)
636 return eq;
637 else if ((group1 < 0 && group2 < 0) || (group1 >= 0 && group2 >= 0))
638 return group1 - group2;
639 else
640 return group2 - group1;
643 /* Compare clusters CL1 & CL2 by the order that they should appear in
644 output. */
645 static int
646 hol_cluster_cmp (const struct hol_cluster *cl1, const struct hol_cluster *cl2)
648 /* If one cluster is deeper than the other, use its ancestor at the same
649 level, so that finding the common ancestor is straightforward. */
650 while (cl1->depth < cl2->depth)
651 cl1 = cl1->parent;
652 while (cl2->depth < cl1->depth)
653 cl2 = cl2->parent;
655 /* Now reduce both clusters to their ancestors at the point where both have
656 a common parent; these can be directly compared. */
657 while (cl1->parent != cl2->parent)
658 cl1 = cl1->parent, cl2 = cl2->parent;
660 return group_cmp (cl1->group, cl2->group, cl2->index - cl1->index);
663 /* Return the ancestor of CL that's just below the root (i.e., has a parent
664 of 0). */
665 static struct hol_cluster *
666 hol_cluster_base (struct hol_cluster *cl)
668 while (cl->parent)
669 cl = cl->parent;
670 return cl;
673 /* Return true if CL1 is a child of CL2. */
674 static int
675 hol_cluster_is_child (const struct hol_cluster *cl1,
676 const struct hol_cluster *cl2)
678 while (cl1 && cl1 != cl2)
679 cl1 = cl1->parent;
680 return cl1 == cl2;
683 /* Given the name of a OPTION_DOC option, modifies NAME to start at the tail
684 that should be used for comparisons, and returns true iff it should be
685 treated as a non-option. */
686 static int
687 canon_doc_option (const char **name)
689 int non_opt;
690 /* Skip initial whitespace. */
691 while (isspace (**name))
692 (*name)++;
693 /* Decide whether this looks like an option (leading `-') or not. */
694 non_opt = (**name != '-');
695 /* Skip until part of name used for sorting. */
696 while (**name && !isalnum (**name))
697 (*name)++;
698 return non_opt;
701 /* Order ENTRY1 & ENTRY2 by the order which they should appear in a help
702 listing. */
703 static int
704 hol_entry_cmp (const struct hol_entry *entry1,
705 const struct hol_entry *entry2)
707 /* The group numbers by which the entries should be ordered; if either is
708 in a cluster, then this is just the group within the cluster. */
709 int group1 = entry1->group, group2 = entry2->group;
711 if (entry1->cluster != entry2->cluster)
712 /* The entries are not within the same cluster, so we can't compare them
713 directly, we have to use the appropiate clustering level too. */
714 if (! entry1->cluster)
715 /* ENTRY1 is at the `base level', not in a cluster, so we have to
716 compare it's group number with that of the base cluster in which
717 ENTRY2 resides. Note that if they're in the same group, the
718 clustered option always comes laster. */
719 return group_cmp (group1, hol_cluster_base (entry2->cluster)->group, -1);
720 else if (! entry2->cluster)
721 /* Likewise, but ENTRY2's not in a cluster. */
722 return group_cmp (hol_cluster_base (entry1->cluster)->group, group2, 1);
723 else
724 /* Both entries are in clusters, we can just compare the clusters. */
725 return hol_cluster_cmp (entry1->cluster, entry2->cluster);
726 else if (group1 == group2)
727 /* The entries are both in the same cluster and group, so compare them
728 alphabetically. */
730 int short1 = hol_entry_first_short (entry1);
731 int short2 = hol_entry_first_short (entry2);
732 int doc1 = odoc (entry1->opt);
733 int doc2 = odoc (entry2->opt);
734 const char *long1 = hol_entry_first_long (entry1);
735 const char *long2 = hol_entry_first_long (entry2);
737 if (doc1)
738 doc1 = canon_doc_option (&long1);
739 if (doc2)
740 doc2 = canon_doc_option (&long2);
742 if (doc1 != doc2)
743 /* `documentation' options always follow normal options (or
744 documentation options that *look* like normal options). */
745 return doc1 - doc2;
746 else if (!short1 && !short2 && long1 && long2)
747 /* Only long options. */
748 return __strcasecmp (long1, long2);
749 else
750 /* Compare short/short, long/short, short/long, using the first
751 character of long options. Entries without *any* valid
752 options (such as options with OPTION_HIDDEN set) will be put
753 first, but as they're not displayed, it doesn't matter where
754 they are. */
756 char first1 = short1 ? short1 : long1 ? *long1 : 0;
757 char first2 = short2 ? short2 : long2 ? *long2 : 0;
758 int lower_cmp = tolower (first1) - tolower (first2);
759 /* Compare ignoring case, except when the options are both the
760 same letter, in which case lower-case always comes first. */
761 return lower_cmp ? lower_cmp : first2 - first1;
764 else
765 /* Within the same cluster, but not the same group, so just compare
766 groups. */
767 return group_cmp (group1, group2, 0);
770 /* Version of hol_entry_cmp with correct signature for qsort. */
771 static int
772 hol_entry_qcmp (const void *entry1_v, const void *entry2_v)
774 return hol_entry_cmp (entry1_v, entry2_v);
777 /* Sort HOL by group and alphabetically by option name (with short options
778 taking precedence over long). Since the sorting is for display purposes
779 only, the shadowing of options isn't effected. */
780 static void
781 hol_sort (struct hol *hol)
783 if (hol->num_entries > 0)
784 qsort (hol->entries, hol->num_entries, sizeof (struct hol_entry),
785 hol_entry_qcmp);
788 /* Append MORE to HOL, destroying MORE in the process. Options in HOL shadow
789 any in MORE with the same name. */
790 static void
791 hol_append (struct hol *hol, struct hol *more)
793 struct hol_cluster **cl_end = &hol->clusters;
795 /* Steal MORE's cluster list, and add it to the end of HOL's. */
796 while (*cl_end)
797 cl_end = &(*cl_end)->next;
798 *cl_end = more->clusters;
799 more->clusters = 0;
801 /* Merge entries. */
802 if (more->num_entries > 0)
803 if (hol->num_entries == 0)
805 hol->num_entries = more->num_entries;
806 hol->entries = more->entries;
807 hol->short_options = more->short_options;
808 more->num_entries = 0; /* Mark MORE's fields as invalid. */
810 else
811 /* Append the entries in MORE to those in HOL, taking care to only add
812 non-shadowed SHORT_OPTIONS values. */
814 unsigned left;
815 char *so, *more_so;
816 struct hol_entry *e;
817 unsigned num_entries = hol->num_entries + more->num_entries;
818 struct hol_entry *entries =
819 malloc (num_entries * sizeof (struct hol_entry));
820 unsigned hol_so_len = strlen (hol->short_options);
821 char *short_options =
822 malloc (hol_so_len + strlen (more->short_options) + 1);
824 __mempcpy (__mempcpy (entries, hol->entries,
825 hol->num_entries * sizeof (struct hol_entry)),
826 more->entries,
827 more->num_entries * sizeof (struct hol_entry));
829 __mempcpy (short_options, hol->short_options, hol_so_len);
831 /* Fix up the short options pointers from HOL. */
832 for (e = entries, left = hol->num_entries; left > 0; e++, left--)
833 e->short_options += (short_options - hol->short_options);
835 /* Now add the short options from MORE, fixing up its entries too. */
836 so = short_options + hol_so_len;
837 more_so = more->short_options;
838 for (left = more->num_entries; left > 0; e++, left--)
840 int opts_left;
841 const struct argp_option *opt;
843 e->short_options = so;
845 for (opts_left = e->num, opt = e->opt; opts_left; opt++, opts_left--)
847 int ch = *more_so;
848 if (oshort (opt) && ch == opt->key)
849 /* The next short option in MORE_SO, CH, is from OPT. */
851 if (! find_char (ch, short_options,
852 short_options + hol_so_len))
853 /* The short option CH isn't shadowed by HOL's options,
854 so add it to the sum. */
855 *so++ = ch;
856 more_so++;
861 *so = '\0';
863 free (hol->entries);
864 free (hol->short_options);
866 hol->entries = entries;
867 hol->num_entries = num_entries;
868 hol->short_options = short_options;
871 hol_free (more);
874 /* Inserts enough spaces to make sure STREAM is at column COL. */
875 static void
876 indent_to (argp_fmtstream_t stream, unsigned col)
878 int needed = col - __argp_fmtstream_point (stream);
879 while (needed-- > 0)
880 __argp_fmtstream_putc (stream, ' ');
883 /* Output to STREAM either a space, or a newline if there isn't room for at
884 least ENSURE characters before the right margin. */
885 static void
886 space (argp_fmtstream_t stream, size_t ensure)
888 if (__argp_fmtstream_point (stream) + ensure
889 >= __argp_fmtstream_rmargin (stream))
890 __argp_fmtstream_putc (stream, '\n');
891 else
892 __argp_fmtstream_putc (stream, ' ');
895 /* If the option REAL has an argument, we print it in using the printf
896 format REQ_FMT or OPT_FMT depending on whether it's a required or
897 optional argument. */
898 static void
899 arg (const struct argp_option *real, const char *req_fmt, const char *opt_fmt,
900 const char *domain, argp_fmtstream_t stream)
902 if (real->arg)
903 if (real->flags & OPTION_ARG_OPTIONAL)
904 __argp_fmtstream_printf (stream, opt_fmt, dgettext (domain, real->arg));
905 else
906 __argp_fmtstream_printf (stream, req_fmt, dgettext (domain, real->arg));
909 /* Helper functions for hol_entry_help. */
911 /* State used during the execution of hol_help. */
912 struct hol_help_state
914 /* PREV_ENTRY should contain the previous entry printed, or 0. */
915 struct hol_entry *prev_entry;
917 /* If an entry is in a different group from the previous one, and SEP_GROUPS
918 is true, then a blank line will be printed before any output. */
919 int sep_groups;
921 /* True if a duplicate option argument was suppressed (only ever set if
922 UPARAMS.dup_args is false). */
923 int suppressed_dup_arg;
926 /* Some state used while printing a help entry (used to communicate with
927 helper functions). See the doc for hol_entry_help for more info, as most
928 of the fields are copied from its arguments. */
929 struct pentry_state
931 const struct hol_entry *entry;
932 argp_fmtstream_t stream;
933 struct hol_help_state *hhstate;
935 /* True if nothing's been printed so far. */
936 int first;
938 /* If non-zero, the state that was used to print this help. */
939 const struct argp_state *state;
942 /* If a user doc filter should be applied to DOC, do so. */
943 static const char *
944 filter_doc (const char *doc, int key, const struct argp *argp,
945 const struct argp_state *state)
947 if (argp->help_filter)
948 /* We must apply a user filter to this output. */
950 void *input = __argp_input (argp, state);
951 return (*argp->help_filter) (key, doc, input);
953 else
954 /* No filter. */
955 return doc;
958 /* Prints STR as a header line, with the margin lines set appropiately, and
959 notes the fact that groups should be separated with a blank line. ARGP is
960 the argp that should dictate any user doc filtering to take place. Note
961 that the previous wrap margin isn't restored, but the left margin is reset
962 to 0. */
963 static void
964 print_header (const char *str, const struct argp *argp,
965 struct pentry_state *pest)
967 const char *tstr = dgettext (argp->argp_domain, str);
968 const char *fstr = filter_doc (tstr, ARGP_KEY_HELP_HEADER, argp, pest->state);
970 if (fstr)
972 if (*fstr)
974 if (pest->hhstate->prev_entry)
975 /* Precede with a blank line. */
976 __argp_fmtstream_putc (pest->stream, '\n');
977 indent_to (pest->stream, uparams.header_col);
978 __argp_fmtstream_set_lmargin (pest->stream, uparams.header_col);
979 __argp_fmtstream_set_wmargin (pest->stream, uparams.header_col);
980 __argp_fmtstream_puts (pest->stream, fstr);
981 __argp_fmtstream_set_lmargin (pest->stream, 0);
982 __argp_fmtstream_putc (pest->stream, '\n');
985 pest->hhstate->sep_groups = 1; /* Separate subsequent groups. */
988 if (fstr != tstr)
989 free ((char *) fstr);
992 /* Inserts a comma if this isn't the first item on the line, and then makes
993 sure we're at least to column COL. If this *is* the first item on a line,
994 prints any pending whitespace/headers that should precede this line. Also
995 clears FIRST. */
996 static void
997 comma (unsigned col, struct pentry_state *pest)
999 if (pest->first)
1001 const struct hol_entry *pe = pest->hhstate->prev_entry;
1002 const struct hol_cluster *cl = pest->entry->cluster;
1004 if (pest->hhstate->sep_groups && pe && pest->entry->group != pe->group)
1005 __argp_fmtstream_putc (pest->stream, '\n');
1007 if (cl && cl->header && *cl->header
1008 && (!pe
1009 || (pe->cluster != cl
1010 && !hol_cluster_is_child (pe->cluster, cl))))
1011 /* If we're changing clusters, then this must be the start of the
1012 ENTRY's cluster unless that is an ancestor of the previous one
1013 (in which case we had just popped into a sub-cluster for a bit).
1014 If so, then print the cluster's header line. */
1016 int old_wm = __argp_fmtstream_wmargin (pest->stream);
1017 print_header (cl->header, cl->argp, pest);
1018 __argp_fmtstream_set_wmargin (pest->stream, old_wm);
1021 pest->first = 0;
1023 else
1024 __argp_fmtstream_puts (pest->stream, ", ");
1026 indent_to (pest->stream, col);
1029 /* Print help for ENTRY to STREAM. */
1030 static void
1031 hol_entry_help (struct hol_entry *entry, const struct argp_state *state,
1032 argp_fmtstream_t stream, struct hol_help_state *hhstate)
1034 unsigned num;
1035 const struct argp_option *real = entry->opt, *opt;
1036 char *so = entry->short_options;
1037 int have_long_opt = 0; /* We have any long options. */
1038 /* Saved margins. */
1039 int old_lm = __argp_fmtstream_set_lmargin (stream, 0);
1040 int old_wm = __argp_fmtstream_wmargin (stream);
1041 /* PEST is a state block holding some of our variables that we'd like to
1042 share with helper functions. */
1043 struct pentry_state pest = { entry, stream, hhstate, 1, state };
1045 if (! odoc (real))
1046 for (opt = real, num = entry->num; num > 0; opt++, num--)
1047 if (opt->name && ovisible (opt))
1049 have_long_opt = 1;
1050 break;
1053 /* First emit short options. */
1054 __argp_fmtstream_set_wmargin (stream, uparams.short_opt_col); /* For truly bizarre cases. */
1055 for (opt = real, num = entry->num; num > 0; opt++, num--)
1056 if (oshort (opt) && opt->key == *so)
1057 /* OPT has a valid (non shadowed) short option. */
1059 if (ovisible (opt))
1061 comma (uparams.short_opt_col, &pest);
1062 __argp_fmtstream_putc (stream, '-');
1063 __argp_fmtstream_putc (stream, *so);
1064 if (!have_long_opt || uparams.dup_args)
1065 arg (real, " %s", "[%s]", state->root_argp->argp_domain, stream);
1066 else if (real->arg)
1067 hhstate->suppressed_dup_arg = 1;
1069 so++;
1072 /* Now, long options. */
1073 if (odoc (real))
1074 /* A `documentation' option. */
1076 __argp_fmtstream_set_wmargin (stream, uparams.doc_opt_col);
1077 for (opt = real, num = entry->num; num > 0; opt++, num--)
1078 if (opt->name && ovisible (opt))
1080 comma (uparams.doc_opt_col, &pest);
1081 /* Calling gettext here isn't quite right, since sorting will
1082 have been done on the original; but documentation options
1083 should be pretty rare anyway... */
1084 __argp_fmtstream_puts (stream,
1085 dgettext (state->root_argp->argp_domain,
1086 opt->name));
1089 else
1090 /* A real long option. */
1092 int first_long_opt = 1;
1094 __argp_fmtstream_set_wmargin (stream, uparams.long_opt_col);
1095 for (opt = real, num = entry->num; num > 0; opt++, num--)
1096 if (opt->name && ovisible (opt))
1098 comma (uparams.long_opt_col, &pest);
1099 __argp_fmtstream_printf (stream, "--%s", opt->name);
1100 if (first_long_opt || uparams.dup_args)
1101 arg (real, "=%s", "[=%s]", state->root_argp->argp_domain,
1102 stream);
1103 else if (real->arg)
1104 hhstate->suppressed_dup_arg = 1;
1108 /* Next, documentation strings. */
1109 __argp_fmtstream_set_lmargin (stream, 0);
1111 if (pest.first)
1112 /* Didn't print any switches, what's up? */
1113 if (!oshort (real) && !real->name)
1114 /* This is a group header, print it nicely. */
1115 print_header (real->doc, entry->argp, &pest);
1116 else
1117 /* Just a totally shadowed option or null header; print nothing. */
1118 goto cleanup; /* Just return, after cleaning up. */
1119 else
1121 const char *tstr = real->doc ? dgettext (state->root_argp->argp_domain,
1122 real->doc) : 0;
1123 const char *fstr = filter_doc (tstr, real->key, entry->argp, state);
1124 if (fstr && *fstr)
1126 unsigned int col = __argp_fmtstream_point (stream);
1128 __argp_fmtstream_set_lmargin (stream, uparams.opt_doc_col);
1129 __argp_fmtstream_set_wmargin (stream, uparams.opt_doc_col);
1131 if (col > (unsigned int) (uparams.opt_doc_col + 3))
1132 __argp_fmtstream_putc (stream, '\n');
1133 else if (col >= (unsigned int) uparams.opt_doc_col)
1134 __argp_fmtstream_puts (stream, " ");
1135 else
1136 indent_to (stream, uparams.opt_doc_col);
1138 __argp_fmtstream_puts (stream, fstr);
1140 if (fstr && fstr != tstr)
1141 free ((char *) fstr);
1143 /* Reset the left margin. */
1144 __argp_fmtstream_set_lmargin (stream, 0);
1145 __argp_fmtstream_putc (stream, '\n');
1148 hhstate->prev_entry = entry;
1150 cleanup:
1151 __argp_fmtstream_set_lmargin (stream, old_lm);
1152 __argp_fmtstream_set_wmargin (stream, old_wm);
1155 /* Output a long help message about the options in HOL to STREAM. */
1156 static void
1157 hol_help (struct hol *hol, const struct argp_state *state,
1158 argp_fmtstream_t stream)
1160 unsigned num;
1161 struct hol_entry *entry;
1162 struct hol_help_state hhstate = { 0, 0, 0 };
1164 for (entry = hol->entries, num = hol->num_entries; num > 0; entry++, num--)
1165 hol_entry_help (entry, state, stream, &hhstate);
1167 if (hhstate.suppressed_dup_arg && uparams.dup_args_note)
1169 const char *tstr = dgettext (state->root_argp->argp_domain, "\
1170 Mandatory or optional arguments to long options are also mandatory or \
1171 optional for any corresponding short options.");
1172 const char *fstr = filter_doc (tstr, ARGP_KEY_HELP_DUP_ARGS_NOTE,
1173 state ? state->root_argp : 0, state);
1174 if (fstr && *fstr)
1176 __argp_fmtstream_putc (stream, '\n');
1177 __argp_fmtstream_puts (stream, fstr);
1178 __argp_fmtstream_putc (stream, '\n');
1180 if (fstr && fstr != tstr)
1181 free ((char *) fstr);
1185 /* Helper functions for hol_usage. */
1187 /* If OPT is a short option without an arg, append its key to the string
1188 pointer pointer to by COOKIE, and advance the pointer. */
1189 static int
1190 add_argless_short_opt (const struct argp_option *opt,
1191 const struct argp_option *real,
1192 const char *domain, void *cookie)
1194 char **snao_end = cookie;
1195 if (!(opt->arg || real->arg)
1196 && !((opt->flags | real->flags) & OPTION_NO_USAGE))
1197 *(*snao_end)++ = opt->key;
1198 return 0;
1201 /* If OPT is a short option with an arg, output a usage entry for it to the
1202 stream pointed at by COOKIE. */
1203 static int
1204 usage_argful_short_opt (const struct argp_option *opt,
1205 const struct argp_option *real,
1206 const char *domain, void *cookie)
1208 argp_fmtstream_t stream = cookie;
1209 const char *arg = opt->arg;
1210 int flags = opt->flags | real->flags;
1212 if (! arg)
1213 arg = real->arg;
1215 if (arg && !(flags & OPTION_NO_USAGE))
1217 arg = dgettext (domain, arg);
1219 if (flags & OPTION_ARG_OPTIONAL)
1220 __argp_fmtstream_printf (stream, " [-%c[%s]]", opt->key, arg);
1221 else
1223 /* Manually do line wrapping so that it (probably) won't
1224 get wrapped at the embedded space. */
1225 space (stream, 6 + strlen (arg));
1226 __argp_fmtstream_printf (stream, "[-%c %s]", opt->key, arg);
1230 return 0;
1233 /* Output a usage entry for the long option opt to the stream pointed at by
1234 COOKIE. */
1235 static int
1236 usage_long_opt (const struct argp_option *opt,
1237 const struct argp_option *real,
1238 const char *domain, void *cookie)
1240 argp_fmtstream_t stream = cookie;
1241 const char *arg = opt->arg;
1242 int flags = opt->flags | real->flags;
1244 if (! arg)
1245 arg = real->arg;
1247 if (! (flags & OPTION_NO_USAGE))
1248 if (arg)
1250 arg = dgettext (domain, arg);
1251 if (flags & OPTION_ARG_OPTIONAL)
1252 __argp_fmtstream_printf (stream, " [--%s[=%s]]", opt->name, arg);
1253 else
1254 __argp_fmtstream_printf (stream, " [--%s=%s]", opt->name, arg);
1256 else
1257 __argp_fmtstream_printf (stream, " [--%s]", opt->name);
1259 return 0;
1262 /* Print a short usage description for the arguments in HOL to STREAM. */
1263 static void
1264 hol_usage (struct hol *hol, argp_fmtstream_t stream)
1266 if (hol->num_entries > 0)
1268 unsigned nentries;
1269 struct hol_entry *entry;
1270 char *short_no_arg_opts = alloca (strlen (hol->short_options) + 1);
1271 char *snao_end = short_no_arg_opts;
1273 /* First we put a list of short options without arguments. */
1274 for (entry = hol->entries, nentries = hol->num_entries
1275 ; nentries > 0
1276 ; entry++, nentries--)
1277 hol_entry_short_iterate (entry, add_argless_short_opt,
1278 entry->argp->argp_domain, &snao_end);
1279 if (snao_end > short_no_arg_opts)
1281 *snao_end++ = 0;
1282 __argp_fmtstream_printf (stream, " [-%s]", short_no_arg_opts);
1285 /* Now a list of short options *with* arguments. */
1286 for (entry = hol->entries, nentries = hol->num_entries
1287 ; nentries > 0
1288 ; entry++, nentries--)
1289 hol_entry_short_iterate (entry, usage_argful_short_opt,
1290 entry->argp->argp_domain, stream);
1292 /* Finally, a list of long options (whew!). */
1293 for (entry = hol->entries, nentries = hol->num_entries
1294 ; nentries > 0
1295 ; entry++, nentries--)
1296 hol_entry_long_iterate (entry, usage_long_opt,
1297 entry->argp->argp_domain, stream);
1301 /* Make a HOL containing all levels of options in ARGP. CLUSTER is the
1302 cluster in which ARGP's entries should be clustered, or 0. */
1303 static struct hol *
1304 argp_hol (const struct argp *argp, struct hol_cluster *cluster)
1306 const struct argp_child *child = argp->children;
1307 struct hol *hol = make_hol (argp, cluster);
1308 if (child)
1309 while (child->argp)
1311 struct hol_cluster *child_cluster =
1312 ((child->group || child->header)
1313 /* Put CHILD->argp within its own cluster. */
1314 ? hol_add_cluster (hol, child->group, child->header,
1315 child - argp->children, cluster, argp)
1316 /* Just merge it into the parent's cluster. */
1317 : cluster);
1318 hol_append (hol, argp_hol (child->argp, child_cluster)) ;
1319 child++;
1321 return hol;
1324 /* Calculate how many different levels with alternative args strings exist in
1325 ARGP. */
1326 static size_t
1327 argp_args_levels (const struct argp *argp)
1329 size_t levels = 0;
1330 const struct argp_child *child = argp->children;
1332 if (argp->args_doc && strchr (argp->args_doc, '\n'))
1333 levels++;
1335 if (child)
1336 while (child->argp)
1337 levels += argp_args_levels ((child++)->argp);
1339 return levels;
1342 /* Print all the non-option args documented in ARGP to STREAM. Any output is
1343 preceded by a space. LEVELS is a pointer to a byte vector the length
1344 returned by argp_args_levels; it should be initialized to zero, and
1345 updated by this routine for the next call if ADVANCE is true. True is
1346 returned as long as there are more patterns to output. */
1347 static int
1348 argp_args_usage (const struct argp *argp, const struct argp_state *state,
1349 char **levels, int advance, argp_fmtstream_t stream)
1351 char *our_level = *levels;
1352 int multiple = 0;
1353 const struct argp_child *child = argp->children;
1354 const char *tdoc = dgettext (argp->argp_domain, argp->args_doc), *nl = 0;
1355 const char *fdoc = filter_doc (tdoc, ARGP_KEY_HELP_ARGS_DOC, argp, state);
1357 if (fdoc)
1359 const char *cp = fdoc;
1360 nl = strchr (cp, '\n');
1361 if (nl)
1362 /* This is a `multi-level' args doc; advance to the correct position
1363 as determined by our state in LEVELS, and update LEVELS. */
1365 int i;
1366 multiple = 1;
1367 for (i = 0; i < *our_level; i++)
1368 cp = nl + 1, nl = strchr (cp, '\n');
1369 (*levels)++;
1371 if (! nl)
1372 nl = cp + strlen (cp);
1374 /* Manually do line wrapping so that it (probably) won't get wrapped at
1375 any embedded spaces. */
1376 space (stream, 1 + nl - cp);
1378 __argp_fmtstream_write (stream, cp, nl - cp);
1380 if (fdoc && fdoc != tdoc)
1381 free ((char *)fdoc); /* Free user's modified doc string. */
1383 if (child)
1384 while (child->argp)
1385 advance = !argp_args_usage ((child++)->argp, state, levels, advance, stream);
1387 if (advance && multiple)
1388 /* Need to increment our level. */
1389 if (*nl)
1390 /* There's more we can do here. */
1392 (*our_level)++;
1393 advance = 0; /* Our parent shouldn't advance also. */
1395 else if (*our_level > 0)
1396 /* We had multiple levels, but used them up; reset to zero. */
1397 *our_level = 0;
1399 return !advance;
1402 /* Print the documentation for ARGP to STREAM; if POST is false, then
1403 everything preceeding a `\v' character in the documentation strings (or
1404 the whole string, for those with none) is printed, otherwise, everything
1405 following the `\v' character (nothing for strings without). Each separate
1406 bit of documentation is separated a blank line, and if PRE_BLANK is true,
1407 then the first is as well. If FIRST_ONLY is true, only the first
1408 occurance is output. Returns true if anything was output. */
1409 static int
1410 argp_doc (const struct argp *argp, const struct argp_state *state,
1411 int post, int pre_blank, int first_only,
1412 argp_fmtstream_t stream)
1414 const char *text;
1415 const char *inp_text;
1416 void *input = 0;
1417 int anything = 0;
1418 size_t inp_text_limit = 0;
1419 const char *doc = dgettext (argp->argp_domain, argp->doc);
1420 const struct argp_child *child = argp->children;
1422 if (doc)
1424 char *vt = strchr (doc, '\v');
1425 inp_text = post ? (vt ? vt + 1 : 0) : doc;
1426 inp_text_limit = (!post && vt) ? (vt - doc) : 0;
1428 else
1429 inp_text = 0;
1431 if (argp->help_filter)
1432 /* We have to filter the doc strings. */
1434 if (inp_text_limit)
1435 /* Copy INP_TEXT so that it's nul-terminated. */
1436 inp_text = __strndup (inp_text, inp_text_limit);
1437 input = __argp_input (argp, state);
1438 text =
1439 (*argp->help_filter) (post
1440 ? ARGP_KEY_HELP_POST_DOC
1441 : ARGP_KEY_HELP_PRE_DOC,
1442 inp_text, input);
1444 else
1445 text = (const char *) inp_text;
1447 if (text)
1449 if (pre_blank)
1450 __argp_fmtstream_putc (stream, '\n');
1452 if (text == inp_text && inp_text_limit)
1453 __argp_fmtstream_write (stream, inp_text, inp_text_limit);
1454 else
1455 __argp_fmtstream_puts (stream, text);
1457 if (__argp_fmtstream_point (stream) > __argp_fmtstream_lmargin (stream))
1458 __argp_fmtstream_putc (stream, '\n');
1460 anything = 1;
1463 if (text && text != inp_text)
1464 free ((char *) text); /* Free TEXT returned from the help filter. */
1465 if (inp_text && inp_text_limit && argp->help_filter)
1466 free ((char *) inp_text); /* We copied INP_TEXT, so free it now. */
1468 if (post && argp->help_filter)
1469 /* Now see if we have to output a ARGP_KEY_HELP_EXTRA text. */
1471 text = (*argp->help_filter) (ARGP_KEY_HELP_EXTRA, 0, input);
1472 if (text)
1474 if (anything || pre_blank)
1475 __argp_fmtstream_putc (stream, '\n');
1476 __argp_fmtstream_puts (stream, text);
1477 free ((char *) text);
1478 if (__argp_fmtstream_point (stream)
1479 > __argp_fmtstream_lmargin (stream))
1480 __argp_fmtstream_putc (stream, '\n');
1481 anything = 1;
1485 if (child)
1486 while (child->argp && !(first_only && anything))
1487 anything |=
1488 argp_doc ((child++)->argp, state,
1489 post, anything || pre_blank, first_only,
1490 stream);
1492 return anything;
1495 /* Output a usage message for ARGP to STREAM. If called from
1496 argp_state_help, STATE is the relevent parsing state. FLAGS are from the
1497 set ARGP_HELP_*. NAME is what to use wherever a `program name' is
1498 needed. */
1499 static void
1500 _help (const struct argp *argp, const struct argp_state *state, FILE *stream,
1501 unsigned flags, char *name)
1503 int anything = 0; /* Whether we've output anything. */
1504 struct hol *hol = 0;
1505 argp_fmtstream_t fs;
1507 if (! stream)
1508 return;
1510 flockfile (stream);
1512 if (! uparams.valid)
1513 fill_in_uparams (state);
1515 fs = __argp_make_fmtstream (stream, 0, uparams.rmargin, 0);
1516 if (! fs)
1518 funlockfile (stream);
1519 return;
1522 if (flags & (ARGP_HELP_USAGE | ARGP_HELP_SHORT_USAGE | ARGP_HELP_LONG))
1524 hol = argp_hol (argp, 0);
1526 /* If present, these options always come last. */
1527 hol_set_group (hol, "help", -1);
1528 hol_set_group (hol, "version", -1);
1530 hol_sort (hol);
1533 if (flags & (ARGP_HELP_USAGE | ARGP_HELP_SHORT_USAGE))
1534 /* Print a short `Usage:' message. */
1536 int first_pattern = 1, more_patterns;
1537 size_t num_pattern_levels = argp_args_levels (argp);
1538 char *pattern_levels = alloca (num_pattern_levels);
1540 memset (pattern_levels, 0, num_pattern_levels);
1544 int old_lm;
1545 int old_wm = __argp_fmtstream_set_wmargin (fs, uparams.usage_indent);
1546 char *levels = pattern_levels;
1548 if (first_pattern)
1549 __argp_fmtstream_printf (fs, "%s %s",
1550 dgettext (argp->argp_domain, "Usage:"),
1551 name);
1552 else
1553 __argp_fmtstream_printf (fs, "%s %s",
1554 dgettext (argp->argp_domain, " or: "),
1555 name);
1557 /* We set the lmargin as well as the wmargin, because hol_usage
1558 manually wraps options with newline to avoid annoying breaks. */
1559 old_lm = __argp_fmtstream_set_lmargin (fs, uparams.usage_indent);
1561 if (flags & ARGP_HELP_SHORT_USAGE)
1562 /* Just show where the options go. */
1564 if (hol->num_entries > 0)
1565 __argp_fmtstream_puts (fs, dgettext (argp->argp_domain,
1566 " [OPTION...]"));
1568 else
1569 /* Actually print the options. */
1571 hol_usage (hol, fs);
1572 flags |= ARGP_HELP_SHORT_USAGE; /* But only do so once. */
1575 more_patterns = argp_args_usage (argp, state, &levels, 1, fs);
1577 __argp_fmtstream_set_wmargin (fs, old_wm);
1578 __argp_fmtstream_set_lmargin (fs, old_lm);
1580 __argp_fmtstream_putc (fs, '\n');
1581 anything = 1;
1583 first_pattern = 0;
1585 while (more_patterns);
1588 if (flags & ARGP_HELP_PRE_DOC)
1589 anything |= argp_doc (argp, state, 0, 0, 1, fs);
1591 if (flags & ARGP_HELP_SEE)
1593 __argp_fmtstream_printf (fs, dgettext (argp->argp_domain, "\
1594 Try `%s --help' or `%s --usage' for more information.\n"),
1595 name, name);
1596 anything = 1;
1599 if (flags & ARGP_HELP_LONG)
1600 /* Print a long, detailed help message. */
1602 /* Print info about all the options. */
1603 if (hol->num_entries > 0)
1605 if (anything)
1606 __argp_fmtstream_putc (fs, '\n');
1607 hol_help (hol, state, fs);
1608 anything = 1;
1612 if (flags & ARGP_HELP_POST_DOC)
1613 /* Print any documentation strings at the end. */
1614 anything |= argp_doc (argp, state, 1, anything, 0, fs);
1616 if ((flags & ARGP_HELP_BUG_ADDR) && argp_program_bug_address)
1618 if (anything)
1619 __argp_fmtstream_putc (fs, '\n');
1620 __argp_fmtstream_printf (fs, dgettext (argp->argp_domain,
1621 "Report bugs to %s.\n"),
1622 argp_program_bug_address);
1623 anything = 1;
1626 funlockfile (stream);
1628 if (hol)
1629 hol_free (hol);
1631 __argp_fmtstream_free (fs);
1634 /* Output a usage message for ARGP to STREAM. FLAGS are from the set
1635 ARGP_HELP_*. NAME is what to use wherever a `program name' is needed. */
1636 void __argp_help (const struct argp *argp, FILE *stream,
1637 unsigned flags, char *name)
1639 _help (argp, 0, stream, flags, name);
1641 #ifdef weak_alias
1642 weak_alias (__argp_help, argp_help)
1643 #endif
1645 /* Output, if appropriate, a usage message for STATE to STREAM. FLAGS are
1646 from the set ARGP_HELP_*. */
1647 void
1648 __argp_state_help (const struct argp_state *state, FILE *stream, unsigned flags)
1650 if ((!state || ! (state->flags & ARGP_NO_ERRS)) && stream)
1652 if (state && (state->flags & ARGP_LONG_ONLY))
1653 flags |= ARGP_HELP_LONG_ONLY;
1655 _help (state ? state->root_argp : 0, state, stream, flags,
1656 state ? state->name : program_invocation_short_name);
1658 if (!state || ! (state->flags & ARGP_NO_EXIT))
1660 if (flags & ARGP_HELP_EXIT_ERR)
1661 exit (argp_err_exit_status);
1662 if (flags & ARGP_HELP_EXIT_OK)
1663 exit (0);
1667 #ifdef weak_alias
1668 weak_alias (__argp_state_help, argp_state_help)
1669 #endif
1671 /* If appropriate, print the printf string FMT and following args, preceded
1672 by the program name and `:', to stderr, and followed by a `Try ... --help'
1673 message, then exit (1). */
1674 void
1675 __argp_error (const struct argp_state *state, const char *fmt, ...)
1677 if (!state || !(state->flags & ARGP_NO_ERRS))
1679 FILE *stream = state ? state->err_stream : stderr;
1681 if (stream)
1683 va_list ap;
1685 flockfile (stream);
1687 fputs_unlocked (state ? state->name : program_invocation_short_name,
1688 stream);
1689 putc_unlocked (':', stream);
1690 putc_unlocked (' ', stream);
1692 va_start (ap, fmt);
1693 vfprintf (stream, fmt, ap);
1694 va_end (ap);
1696 putc_unlocked ('\n', stream);
1698 __argp_state_help (state, stream, ARGP_HELP_STD_ERR);
1700 funlockfile (stream);
1704 #ifdef weak_alias
1705 weak_alias (__argp_error, argp_error)
1706 #endif
1708 /* Similar to the standard gnu error-reporting function error(), but will
1709 respect the ARGP_NO_EXIT and ARGP_NO_ERRS flags in STATE, and will print
1710 to STATE->err_stream. This is useful for argument parsing code that is
1711 shared between program startup (when exiting is desired) and runtime
1712 option parsing (when typically an error code is returned instead). The
1713 difference between this function and argp_error is that the latter is for
1714 *parsing errors*, and the former is for other problems that occur during
1715 parsing but don't reflect a (syntactic) problem with the input. */
1716 void
1717 __argp_failure (const struct argp_state *state, int status, int errnum,
1718 const char *fmt, ...)
1720 if (!state || !(state->flags & ARGP_NO_ERRS))
1722 FILE *stream = state ? state->err_stream : stderr;
1724 if (stream)
1726 flockfile (stream);
1728 fputs_unlocked (state ? state->name : program_invocation_short_name,
1729 stream);
1731 if (fmt)
1733 va_list ap;
1735 putc_unlocked (':', stream);
1736 putc_unlocked (' ', stream);
1738 va_start (ap, fmt);
1739 vfprintf (stream, fmt, ap);
1740 va_end (ap);
1743 if (errnum)
1745 putc_unlocked (':', stream);
1746 putc_unlocked (' ', stream);
1747 fputs (strerror (errnum), stream);
1750 putc_unlocked ('\n', stream);
1752 funlockfile (stream);
1754 if (status && (!state || !(state->flags & ARGP_NO_EXIT)))
1755 exit (status);
1759 #ifdef weak_alias
1760 weak_alias (__argp_failure, argp_failure)
1761 #endif