ARC: Fix max ULP for cosine test
[uclibc-ng.git] / libuargp / argp-help.c
blob0d63ae30b4f4d2cded68c6159cdea8ffce95c2fd
1 /* Hierarchial argument parsing help output
2 Copyright (C) 1995-2003, 2004, 2005, 2006, 2007
3 Free Software Foundation, Inc.
4 This file is part of the GNU C Library.
5 Written by Miles Bader <miles at gnu.ai.mit.edu>.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or (at your option) any later version.
12 The GNU C Library 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 GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with the GNU C Library; see the file COPYING.LIB. If
19 not, see <http://www.gnu.org/licenses/>.
21 Modified for uClibc by: Salvatore Cro <salvatore.cro at st.com>
24 #ifndef _GNU_SOURCE
25 # define _GNU_SOURCE 1
26 #endif
28 #ifdef HAVE_CONFIG_H
29 #include <config.h>
30 #endif
32 /* AIX requires this to be the first thing in the file. */
33 #ifndef __GNUC__
34 # if HAVE_ALLOCA_H || defined _LIBC
35 # include <alloca.h>
36 # else
37 # ifdef _AIX
38 #pragma alloca
39 # else
40 # ifndef alloca /* predefined by HP cc +Olibcalls */
41 char *alloca ();
42 # endif
43 # endif
44 # endif
45 #endif
47 #include <stddef.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <assert.h>
51 #include <stdarg.h>
52 #include <ctype.h>
53 #include <limits.h>
54 #ifdef _LIBC
55 # include <wchar.h>
56 #endif
58 #include <features.h>
59 #ifndef _
60 /* This is for other GNU distributions with internationalized messages. */
61 # if (defined HAVE_LIBINTL_H || defined _LIBC) && defined __UCLIBC_HAS_GETTEXT_AWARENESS__
62 # include <libintl.h>
63 # ifdef _LIBC
64 # undef dgettext
65 # define dgettext(domain, msgid) \
66 INTUSE(__dcgettext) (domain, msgid, LC_MESSAGES)
67 # endif
68 # else
69 # define dgettext(domain, msgid) (msgid)
70 # endif
71 #endif
73 #ifndef _LIBC
74 # if HAVE_STRERROR_R
75 # if !HAVE_DECL_STRERROR_R
76 char *strerror_r (int errnum, char *buf, size_t buflen);
77 # endif
78 # else
79 # if !HAVE_DECL_STRERROR
80 char *strerror (int errnum);
81 # endif
82 # endif
83 #endif
85 #include <argp.h>
86 #include "argp-fmtstream.h"
87 #include <stdbool.h>
88 #include <stdint.h>
90 #ifndef SIZE_MAX
91 # define SIZE_MAX ((size_t) -1)
92 #endif
94 /* User-selectable (using an environment variable) formatting parameters.
96 These may be specified in an environment variable called `ARGP_HELP_FMT',
97 with a contents like: VAR1=VAL1,VAR2=VAL2,BOOLVAR2,no-BOOLVAR2
98 Where VALn must be a positive integer. The list of variables is in the
99 UPARAM_NAMES vector, below. */
101 /* Default parameters. */
102 #define DUP_ARGS 0 /* True if option argument can be duplicated. */
103 #define DUP_ARGS_NOTE 1 /* True to print a note about duplicate args. */
104 #define SHORT_OPT_COL 2 /* column in which short options start */
105 #define LONG_OPT_COL 6 /* column in which long options start */
106 #define DOC_OPT_COL 2 /* column in which doc options start */
107 #define OPT_DOC_COL 29 /* column in which option text starts */
108 #define HEADER_COL 1 /* column in which group headers are printed */
109 #define USAGE_INDENT 12 /* indentation of wrapped usage lines */
110 #define RMARGIN 79 /* right margin used for wrapping */
112 /* User-selectable (using an environment variable) formatting parameters.
113 They must all be of type `int' for the parsing code to work. */
114 struct uparams
116 /* If true, arguments for an option are shown with both short and long
117 options, even when a given option has both, e.g. `-x ARG, --longx=ARG'.
118 If false, then if an option has both, the argument is only shown with
119 the long one, e.g., `-x, --longx=ARG', and a message indicating that
120 this really means both is printed below the options. */
121 int dup_args;
123 /* This is true if when DUP_ARGS is false, and some duplicate arguments have
124 been suppressed, an explanatory message should be printed. */
125 int dup_args_note;
127 /* Various output columns. */
128 int short_opt_col;
129 int long_opt_col;
130 int doc_opt_col;
131 int opt_doc_col;
132 int header_col;
133 int usage_indent;
134 int rmargin;
137 /* This is a global variable, as user options are only ever read once. */
138 static struct uparams uparams = {
139 DUP_ARGS, DUP_ARGS_NOTE,
140 SHORT_OPT_COL, LONG_OPT_COL, DOC_OPT_COL, OPT_DOC_COL, HEADER_COL,
141 USAGE_INDENT, RMARGIN
144 /* A particular uparam, and what the user name is. */
145 struct uparam_name
147 const char name[14]; /* User name. */
148 bool is_bool; /* Whether it's `boolean'. */
149 uint8_t uparams_offs; /* Location of the (int) field in UPARAMS. */
152 /* The name-field mappings we know about. */
153 static const struct uparam_name uparam_names[] =
155 { "dup-args", true, offsetof (struct uparams, dup_args) },
156 { "dup-args-note", true, offsetof (struct uparams, dup_args_note) },
157 { "short-opt-col", false, offsetof (struct uparams, short_opt_col) },
158 { "long-opt-col", false, offsetof (struct uparams, long_opt_col) },
159 { "doc-opt-col", false, offsetof (struct uparams, doc_opt_col) },
160 { "opt-doc-col", false, offsetof (struct uparams, opt_doc_col) },
161 { "header-col", false, offsetof (struct uparams, header_col) },
162 { "usage-indent", false, offsetof (struct uparams, usage_indent) },
163 { "rmargin", false, offsetof (struct uparams, rmargin) }
165 #define nuparam_names (sizeof (uparam_names) / sizeof (uparam_names[0]))
167 /* Read user options from the environment, and fill in UPARAMS appropiately. */
168 static void
169 fill_in_uparams (const struct argp_state *state)
171 const char *var = getenv ("ARGP_HELP_FMT");
173 #define SKIPWS(p) do { while (isspace (*p)) p++; } while (0);
175 if (var)
176 /* Parse var. */
177 while (*var)
179 SKIPWS (var);
181 if (isalpha (*var))
183 size_t var_len;
184 const struct uparam_name *un;
185 int unspec = 0, val = 0;
186 const char *arg = var;
188 while (isalnum (*arg) || *arg == '-' || *arg == '_')
189 arg++;
190 var_len = arg - var;
192 SKIPWS (arg);
194 if (*arg == '\0' || *arg == ',')
195 unspec = 1;
196 else if (*arg == '=')
198 arg++;
199 SKIPWS (arg);
202 if (unspec)
204 if (var[0] == 'n' && var[1] == 'o' && var[2] == '-')
206 val = 0;
207 var += 3;
208 var_len -= 3;
210 else
211 val = 1;
213 else if (isdigit (*arg))
215 val = atoi (arg);
216 while (isdigit (*arg))
217 arg++;
218 SKIPWS (arg);
221 un = uparam_names;
222 size_t u;
223 for (u = 0; u < nuparam_names; ++un, ++u)
224 if (strlen (un->name) == var_len
225 && strncmp (var, un->name, var_len) == 0)
227 if (unspec && !un->is_bool)
228 argp_failure (state, 0, 0,
229 dgettext (state == NULL ? NULL
230 : state->root_argp->argp_domain,
232 %.*s: ARGP_HELP_FMT parameter requires a value"),
233 (int) var_len, var);
234 else
235 *(int *)((char *)&uparams + un->uparams_offs) = val;
236 break;
238 if (u == nuparam_names)
239 argp_failure (state, 0, 0,
240 dgettext (state == NULL ? NULL
241 : state->root_argp->argp_domain, "\
242 %.*s: Unknown ARGP_HELP_FMT parameter"),
243 (int) var_len, var);
245 var = arg;
246 if (*var == ',')
247 var++;
249 else if (*var)
251 argp_failure (state, 0, 0,
252 dgettext (state == NULL ? NULL
253 : state->root_argp->argp_domain,
254 "Garbage in ARGP_HELP_FMT: %s"), var);
255 break;
260 /* Returns true if OPT hasn't been marked invisible. Visibility only affects
261 whether OPT is displayed or used in sorting, not option shadowing. */
262 #define ovisible(opt) (! ((opt)->flags & OPTION_HIDDEN))
264 /* Returns true if OPT is an alias for an earlier option. */
265 #define oalias(opt) ((opt)->flags & OPTION_ALIAS)
267 /* Returns true if OPT is an documentation-only entry. */
268 #define odoc(opt) ((opt)->flags & OPTION_DOC)
270 /* Returns true if OPT is the end-of-list marker for a list of options. */
271 #define oend(opt) __option_is_end (opt)
273 /* Returns true if OPT has a short option. */
274 #define oshort(opt) __option_is_short (opt)
277 The help format for a particular option is like:
279 -xARG, -yARG, --long1=ARG, --long2=ARG Documentation...
281 Where ARG will be omitted if there's no argument, for this option, or
282 will be surrounded by "[" and "]" appropiately if the argument is
283 optional. The documentation string is word-wrapped appropiately, and if
284 the list of options is long enough, it will be started on a separate line.
285 If there are no short options for a given option, the first long option is
286 indented slighly in a way that's supposed to make most long options appear
287 to be in a separate column.
289 For example, the following output (from ps):
291 -p PID, --pid=PID List the process PID
292 --pgrp=PGRP List processes in the process group PGRP
293 -P, -x, --no-parent Include processes without parents
294 -Q, --all-fields Don't elide unusable fields (normally if there's
295 some reason ps can't print a field for any
296 process, it's removed from the output entirely)
297 -r, --reverse, --gratuitously-long-reverse-option
298 Reverse the order of any sort
299 --session[=SID] Add the processes from the session SID (which
300 defaults to the sid of the current process)
302 Here are some more options:
303 -f ZOT, --foonly=ZOT Glork a foonly
304 -z, --zaza Snit a zar
306 -?, --help Give this help list
307 --usage Give a short usage message
308 -V, --version Print program version
310 The struct argp_option array for the above could look like:
313 {"pid", 'p', "PID", 0, "List the process PID"},
314 {"pgrp", OPT_PGRP, "PGRP", 0, "List processes in the process group PGRP"},
315 {"no-parent", 'P', 0, 0, "Include processes without parents"},
316 {0, 'x', 0, OPTION_ALIAS},
317 {"all-fields",'Q', 0, 0, "Don't elide unusable fields (normally"
318 " if there's some reason ps can't"
319 " print a field for any process, it's"
320 " removed from the output entirely)" },
321 {"reverse", 'r', 0, 0, "Reverse the order of any sort"},
322 {"gratuitously-long-reverse-option", 0, 0, OPTION_ALIAS},
323 {"session", OPT_SESS, "SID", OPTION_ARG_OPTIONAL,
324 "Add the processes from the session"
325 " SID (which defaults to the sid of"
326 " the current process)" },
328 {0,0,0,0, "Here are some more options:"},
329 {"foonly", 'f', "ZOT", 0, "Glork a foonly"},
330 {"zaza", 'z', 0, 0, "Snit a zar"},
335 Note that the last three options are automatically supplied by argp_parse,
336 unless you tell it not to with ARGP_NO_HELP.
340 /* Returns true if CH occurs between BEG and END. */
341 static int
342 find_char (char ch, char *beg, char *end)
344 while (beg < end)
345 if (*beg == ch)
346 return 1;
347 else
348 beg++;
349 return 0;
352 struct hol_cluster; /* fwd decl */
354 struct hol_entry
356 /* First option. */
357 const struct argp_option *opt;
358 /* Number of options (including aliases). */
359 unsigned num;
361 /* A pointers into the HOL's short_options field, to the first short option
362 letter for this entry. The order of the characters following this point
363 corresponds to the order of options pointed to by OPT, and there are at
364 most NUM. A short option recorded in a option following OPT is only
365 valid if it occurs in the right place in SHORT_OPTIONS (otherwise it's
366 probably been shadowed by some other entry). */
367 char *short_options;
369 /* Entries are sorted by their group first, in the order:
370 1, 2, ..., n, 0, -m, ..., -2, -1
371 and then alphabetically within each group. The default is 0. */
372 int group;
374 /* The cluster of options this entry belongs to, or 0 if none. */
375 struct hol_cluster *cluster;
377 /* The argp from which this option came. */
378 const struct argp *argp;
381 /* A cluster of entries to reflect the argp tree structure. */
382 struct hol_cluster
384 /* A descriptive header printed before options in this cluster. */
385 const char *header;
387 /* Used to order clusters within the same group with the same parent,
388 according to the order in which they occurred in the parent argp's child
389 list. */
390 int index;
392 /* How to sort this cluster with respect to options and other clusters at the
393 same depth (clusters always follow options in the same group). */
394 int group;
396 /* The cluster to which this cluster belongs, or 0 if it's at the base
397 level. */
398 struct hol_cluster *parent;
400 /* The argp from which this cluster is (eventually) derived. */
401 const struct argp *argp;
403 /* The distance this cluster is from the root. */
404 int depth;
406 /* Clusters in a given hol are kept in a linked list, to make freeing them
407 possible. */
408 struct hol_cluster *next;
411 /* A list of options for help. */
412 struct hol
414 /* An array of hol_entry's. */
415 struct hol_entry *entries;
416 /* The number of entries in this hol. If this field is zero, the others
417 are undefined. */
418 unsigned num_entries;
420 /* A string containing all short options in this HOL. Each entry contains
421 pointers into this string, so the order can't be messed with blindly. */
422 char *short_options;
424 /* Clusters of entries in this hol. */
425 struct hol_cluster *clusters;
428 /* Create a struct hol from the options in ARGP. CLUSTER is the
429 hol_cluster in which these entries occur, or 0, if at the root. */
430 static struct hol *
431 make_hol (const struct argp *argp, struct hol_cluster *cluster)
433 char *so;
434 const struct argp_option *o;
435 const struct argp_option *opts = argp->options;
436 struct hol_entry *entry;
437 unsigned num_short_options = 0;
438 struct hol *hol = malloc (sizeof (struct hol));
440 assert (hol);
442 hol->num_entries = 0;
443 hol->clusters = 0;
445 if (opts)
447 int cur_group = 0;
449 /* The first option must not be an alias. */
450 assert (! oalias (opts));
452 /* Calculate the space needed. */
453 for (o = opts; ! oend (o); o++)
455 if (! oalias (o))
456 hol->num_entries++;
457 if (oshort (o))
458 num_short_options++; /* This is an upper bound. */
461 hol->entries = malloc (sizeof (struct hol_entry) * hol->num_entries);
462 hol->short_options = malloc (num_short_options + 1);
464 assert (hol->entries && hol->short_options);
465 #if SIZE_MAX <= UINT_MAX
466 assert (hol->num_entries <= SIZE_MAX / sizeof (struct hol_entry));
467 #endif
469 /* Fill in the entries. */
470 so = hol->short_options;
471 for (o = opts, entry = hol->entries; ! oend (o); entry++)
473 entry->opt = o;
474 entry->num = 0;
475 entry->short_options = so;
476 entry->group = cur_group =
477 o->group
478 ? o->group
479 : ((!o->name && !o->key)
480 ? cur_group + 1
481 : cur_group);
482 entry->cluster = cluster;
483 entry->argp = argp;
487 entry->num++;
488 if (oshort (o) && ! find_char (o->key, hol->short_options, so))
489 /* O has a valid short option which hasn't already been used.*/
490 *so++ = o->key;
491 o++;
493 while (! oend (o) && oalias (o));
495 *so = '\0'; /* null terminated so we can find the length */
498 return hol;
501 /* Add a new cluster to HOL, with the given GROUP and HEADER (taken from the
502 associated argp child list entry), INDEX, and PARENT, and return a pointer
503 to it. ARGP is the argp that this cluster results from. */
504 static struct hol_cluster *
505 hol_add_cluster (struct hol *hol, int group, const char *header, int index,
506 struct hol_cluster *parent, const struct argp *argp)
508 struct hol_cluster *cl = malloc (sizeof (struct hol_cluster));
509 if (cl)
511 cl->group = group;
512 cl->header = header;
514 cl->index = index;
515 cl->parent = parent;
516 cl->argp = argp;
517 cl->depth = parent ? parent->depth + 1 : 0;
519 cl->next = hol->clusters;
520 hol->clusters = cl;
522 return cl;
525 /* Free HOL and any resources it uses. */
526 static void
527 hol_free (struct hol *hol)
529 struct hol_cluster *cl = hol->clusters;
531 while (cl)
533 struct hol_cluster *next = cl->next;
534 free (cl);
535 cl = next;
538 if (hol->num_entries > 0)
540 free (hol->entries);
541 free (hol->short_options);
544 free (hol);
547 static int
548 hol_entry_short_iterate (const struct hol_entry *entry,
549 int (*func)(const struct argp_option *opt,
550 const struct argp_option *real,
551 const char *domain, void *cookie),
552 const char *domain, void *cookie)
554 unsigned nopts;
555 int val = 0;
556 const struct argp_option *opt, *real = entry->opt;
557 char *so = entry->short_options;
559 for (opt = real, nopts = entry->num; nopts > 0 && !val; opt++, nopts--)
560 if (oshort (opt) && *so == opt->key)
562 if (!oalias (opt))
563 real = opt;
564 if (ovisible (opt))
565 val = (*func)(opt, real, domain, cookie);
566 so++;
569 return val;
572 static __inline__ int
573 __attribute__ ((always_inline))
574 hol_entry_long_iterate (const struct hol_entry *entry,
575 int (*func)(const struct argp_option *opt,
576 const struct argp_option *real,
577 const char *domain, void *cookie),
578 const char *domain, void *cookie)
580 unsigned nopts;
581 int val = 0;
582 const struct argp_option *opt, *real = entry->opt;
584 for (opt = real, nopts = entry->num; nopts > 0 && !val; opt++, nopts--)
585 if (opt->name)
587 if (!oalias (opt))
588 real = opt;
589 if (ovisible (opt))
590 val = (*func)(opt, real, domain, cookie);
593 return val;
596 /* Iterator that returns true for the first short option. */
597 static __inline__ int
598 until_short (const struct argp_option *opt, const struct argp_option *real,
599 const char *domain, void *cookie)
601 return oshort (opt) ? opt->key : 0;
604 /* Returns the first valid short option in ENTRY, or 0 if there is none. */
605 static char
606 hol_entry_first_short (const struct hol_entry *entry)
608 return hol_entry_short_iterate (entry, until_short,
609 entry->argp->argp_domain, 0);
612 /* Returns the first valid long option in ENTRY, or 0 if there is none. */
613 static const char *
614 hol_entry_first_long (const struct hol_entry *entry)
616 const struct argp_option *opt;
617 unsigned num;
618 for (opt = entry->opt, num = entry->num; num > 0; opt++, num--)
619 if (opt->name && ovisible (opt))
620 return opt->name;
621 return 0;
624 /* Returns the entry in HOL with the long option name NAME, or 0 if there is
625 none. */
626 static struct hol_entry *
627 hol_find_entry (struct hol *hol, const char *name)
629 struct hol_entry *entry = hol->entries;
630 unsigned num_entries = hol->num_entries;
632 while (num_entries-- > 0)
634 const struct argp_option *opt = entry->opt;
635 unsigned num_opts = entry->num;
637 while (num_opts-- > 0)
638 if (opt->name && ovisible (opt) && strcmp (opt->name, name) == 0)
639 return entry;
640 else
641 opt++;
643 entry++;
646 return 0;
649 /* If an entry with the long option NAME occurs in HOL, set it's special
650 sort position to GROUP. */
651 static void
652 hol_set_group (struct hol *hol, const char *name, int group)
654 struct hol_entry *entry = hol_find_entry (hol, name);
655 if (entry)
656 entry->group = group;
659 /* Order by group: 0, 1, 2, ..., n, -m, ..., -2, -1.
660 EQ is what to return if GROUP1 and GROUP2 are the same. */
661 static int
662 group_cmp (int group1, int group2, int eq)
664 if (group1 == group2)
665 return eq;
666 else if ((group1 < 0 && group2 < 0) || (group1 >= 0 && group2 >= 0))
667 return group1 - group2;
668 else
669 return group2 - group1;
672 /* Compare clusters CL1 & CL2 by the order that they should appear in
673 output. */
674 static int
675 hol_cluster_cmp (const struct hol_cluster *cl1, const struct hol_cluster *cl2)
677 /* If one cluster is deeper than the other, use its ancestor at the same
678 level, so that finding the common ancestor is straightforward. */
679 while (cl1->depth > cl2->depth)
680 cl1 = cl1->parent;
681 while (cl2->depth > cl1->depth)
682 cl2 = cl2->parent;
684 /* Now reduce both clusters to their ancestors at the point where both have
685 a common parent; these can be directly compared. */
686 while (cl1->parent != cl2->parent)
687 cl1 = cl1->parent, cl2 = cl2->parent;
689 return group_cmp (cl1->group, cl2->group, cl2->index - cl1->index);
692 /* Return the ancestor of CL that's just below the root (i.e., has a parent
693 of 0). */
694 static struct hol_cluster *
695 hol_cluster_base (struct hol_cluster *cl)
697 while (cl->parent)
698 cl = cl->parent;
699 return cl;
702 /* Return true if CL1 is a child of CL2. */
703 static int
704 hol_cluster_is_child (const struct hol_cluster *cl1,
705 const struct hol_cluster *cl2)
707 while (cl1 && cl1 != cl2)
708 cl1 = cl1->parent;
709 return cl1 == cl2;
712 /* Given the name of a OPTION_DOC option, modifies NAME to start at the tail
713 that should be used for comparisons, and returns true iff it should be
714 treated as a non-option. */
715 static int
716 canon_doc_option (const char **name)
718 int non_opt;
719 /* Skip initial whitespace. */
720 while (isspace (**name))
721 (*name)++;
722 /* Decide whether this looks like an option (leading `-') or not. */
723 non_opt = (**name != '-');
724 /* Skip until part of name used for sorting. */
725 while (**name && !isalnum (**name))
726 (*name)++;
727 return non_opt;
730 /* Order ENTRY1 & ENTRY2 by the order which they should appear in a help
731 listing. */
732 static int
733 hol_entry_cmp (const struct hol_entry *entry1,
734 const struct hol_entry *entry2)
736 /* The group numbers by which the entries should be ordered; if either is
737 in a cluster, then this is just the group within the cluster. */
738 int group1 = entry1->group, group2 = entry2->group;
740 if (entry1->cluster != entry2->cluster)
742 /* The entries are not within the same cluster, so we can't compare them
743 directly, we have to use the appropiate clustering level too. */
744 if (! entry1->cluster)
745 /* ENTRY1 is at the `base level', not in a cluster, so we have to
746 compare it's group number with that of the base cluster in which
747 ENTRY2 resides. Note that if they're in the same group, the
748 clustered option always comes laster. */
749 return group_cmp (group1, hol_cluster_base (entry2->cluster)->group, -1);
750 else if (! entry2->cluster)
751 /* Likewise, but ENTRY2's not in a cluster. */
752 return group_cmp (hol_cluster_base (entry1->cluster)->group, group2, 1);
753 else
754 /* Both entries are in clusters, we can just compare the clusters. */
755 return hol_cluster_cmp (entry1->cluster, entry2->cluster);
757 else if (group1 == group2)
758 /* The entries are both in the same cluster and group, so compare them
759 alphabetically. */
761 int short1 = hol_entry_first_short (entry1);
762 int short2 = hol_entry_first_short (entry2);
763 int doc1 = odoc (entry1->opt);
764 int doc2 = odoc (entry2->opt);
765 const char *long1 = hol_entry_first_long (entry1);
766 const char *long2 = hol_entry_first_long (entry2);
768 if (doc1)
769 doc1 = long1 != NULL && canon_doc_option (&long1);
770 if (doc2)
771 doc2 = long2 != NULL && canon_doc_option (&long2);
773 if (doc1 != doc2)
774 /* `documentation' options always follow normal options (or
775 documentation options that *look* like normal options). */
776 return doc1 - doc2;
777 else if (!short1 && !short2 && long1 && long2)
778 /* Only long options. */
779 return strcasecmp (long1, long2);
780 else
781 /* Compare short/short, long/short, short/long, using the first
782 character of long options. Entries without *any* valid
783 options (such as options with OPTION_HIDDEN set) will be put
784 first, but as they're not displayed, it doesn't matter where
785 they are. */
787 char first1 = short1 ? short1 : long1 ? *long1 : 0;
788 char first2 = short2 ? short2 : long2 ? *long2 : 0;
789 #ifdef _tolower
790 int lower_cmp = _tolower (first1) - _tolower (first2);
791 #else
792 int lower_cmp = tolower (first1) - tolower (first2);
793 #endif
794 /* Compare ignoring case, except when the options are both the
795 same letter, in which case lower-case always comes first. */
796 return lower_cmp ? lower_cmp : first2 - first1;
799 else
800 /* Within the same cluster, but not the same group, so just compare
801 groups. */
802 return group_cmp (group1, group2, 0);
805 /* Version of hol_entry_cmp with correct signature for qsort. */
806 static int
807 hol_entry_qcmp (const void *entry1_v, const void *entry2_v)
809 return hol_entry_cmp (entry1_v, entry2_v);
812 /* Sort HOL by group and alphabetically by option name (with short options
813 taking precedence over long). Since the sorting is for display purposes
814 only, the shadowing of options isn't effected. */
815 static void
816 hol_sort (struct hol *hol)
818 if (hol->num_entries > 0)
819 qsort (hol->entries, hol->num_entries, sizeof (struct hol_entry),
820 hol_entry_qcmp);
823 /* Append MORE to HOL, destroying MORE in the process. Options in HOL shadow
824 any in MORE with the same name. */
825 static void
826 hol_append (struct hol *hol, struct hol *more)
828 struct hol_cluster **cl_end = &hol->clusters;
830 /* Steal MORE's cluster list, and add it to the end of HOL's. */
831 while (*cl_end)
832 cl_end = &(*cl_end)->next;
833 *cl_end = more->clusters;
834 more->clusters = 0;
836 /* Merge entries. */
837 if (more->num_entries > 0)
839 if (hol->num_entries == 0)
841 hol->num_entries = more->num_entries;
842 hol->entries = more->entries;
843 hol->short_options = more->short_options;
844 more->num_entries = 0; /* Mark MORE's fields as invalid. */
846 else
847 /* Append the entries in MORE to those in HOL, taking care to only add
848 non-shadowed SHORT_OPTIONS values. */
850 unsigned left;
851 char *so, *more_so;
852 struct hol_entry *e;
853 unsigned num_entries = hol->num_entries + more->num_entries;
854 struct hol_entry *entries =
855 malloc (num_entries * sizeof (struct hol_entry));
856 unsigned hol_so_len = strlen (hol->short_options);
857 char *short_options =
858 malloc (hol_so_len + strlen (more->short_options) + 1);
860 assert (entries && short_options);
861 #if SIZE_MAX <= UINT_MAX
862 assert (num_entries <= SIZE_MAX / sizeof (struct hol_entry));
863 #endif
865 mempcpy (mempcpy (entries, hol->entries,
866 hol->num_entries * sizeof (struct hol_entry)),
867 more->entries,
868 more->num_entries * sizeof (struct hol_entry));
870 mempcpy (short_options, hol->short_options, hol_so_len);
872 /* Fix up the short options pointers from HOL. */
873 for (e = entries, left = hol->num_entries; left > 0; e++, left--)
874 e->short_options += (short_options - hol->short_options);
876 /* Now add the short options from MORE, fixing up its entries
877 too. */
878 so = short_options + hol_so_len;
879 more_so = more->short_options;
880 for (left = more->num_entries; left > 0; e++, left--)
882 int opts_left;
883 const struct argp_option *opt;
885 e->short_options = so;
887 for (opts_left = e->num, opt = e->opt; opts_left; opt++, opts_left--)
889 int ch = *more_so;
890 if (oshort (opt) && ch == opt->key)
891 /* The next short option in MORE_SO, CH, is from OPT. */
893 if (! find_char (ch, short_options,
894 short_options + hol_so_len))
895 /* The short option CH isn't shadowed by HOL's options,
896 so add it to the sum. */
897 *so++ = ch;
898 more_so++;
903 *so = '\0';
905 free (hol->entries);
906 free (hol->short_options);
908 hol->entries = entries;
909 hol->num_entries = num_entries;
910 hol->short_options = short_options;
914 hol_free (more);
917 /* Inserts enough spaces to make sure STREAM is at column COL. */
918 static void
919 indent_to (argp_fmtstream_t stream, unsigned col)
921 int needed = col - __argp_fmtstream_point (stream);
922 while (needed-- > 0)
923 __argp_fmtstream_putc (stream, ' ');
926 /* Output to STREAM either a space, or a newline if there isn't room for at
927 least ENSURE characters before the right margin. */
928 static void
929 space (argp_fmtstream_t stream, size_t ensure)
931 if (__argp_fmtstream_point (stream) + ensure
932 >= __argp_fmtstream_rmargin (stream))
933 __argp_fmtstream_putc (stream, '\n');
934 else
935 __argp_fmtstream_putc (stream, ' ');
938 /* If the option REAL has an argument, we print it in using the printf
939 format REQ_FMT or OPT_FMT depending on whether it's a required or
940 optional argument. */
941 static void
942 arg (const struct argp_option *real, const char *req_fmt, const char *opt_fmt,
943 const char *domain, argp_fmtstream_t stream)
945 if (real->arg)
947 if (real->flags & OPTION_ARG_OPTIONAL)
948 __argp_fmtstream_printf (stream, opt_fmt,
949 dgettext (domain, real->arg));
950 else
951 __argp_fmtstream_printf (stream, req_fmt,
952 dgettext (domain, real->arg));
956 /* Helper functions for hol_entry_help. */
958 /* State used during the execution of hol_help. */
959 struct hol_help_state
961 /* PREV_ENTRY should contain the previous entry printed, or 0. */
962 struct hol_entry *prev_entry;
964 /* If an entry is in a different group from the previous one, and SEP_GROUPS
965 is true, then a blank line will be printed before any output. */
966 int sep_groups;
968 /* True if a duplicate option argument was suppressed (only ever set if
969 UPARAMS.dup_args is false). */
970 int suppressed_dup_arg;
973 /* Some state used while printing a help entry (used to communicate with
974 helper functions). See the doc for hol_entry_help for more info, as most
975 of the fields are copied from its arguments. */
976 struct pentry_state
978 const struct hol_entry *entry;
979 argp_fmtstream_t stream;
980 struct hol_help_state *hhstate;
982 /* True if nothing's been printed so far. */
983 int first;
985 /* If non-zero, the state that was used to print this help. */
986 const struct argp_state *state;
989 /* If a user doc filter should be applied to DOC, do so. */
990 static const char *
991 filter_doc (const char *doc, int key, const struct argp *argp,
992 const struct argp_state *state)
994 if (argp && argp->help_filter)
995 /* We must apply a user filter to this output. */
997 void *input = __argp_input (argp, state);
998 return (*argp->help_filter) (key, doc, input);
1000 else
1001 /* No filter. */
1002 return doc;
1005 /* Prints STR as a header line, with the margin lines set appropiately, and
1006 notes the fact that groups should be separated with a blank line. ARGP is
1007 the argp that should dictate any user doc filtering to take place. Note
1008 that the previous wrap margin isn't restored, but the left margin is reset
1009 to 0. */
1010 static void
1011 print_header (const char *str, const struct argp *argp,
1012 struct pentry_state *pest)
1014 const char *tstr = dgettext (argp->argp_domain, str);
1015 const char *fstr = filter_doc (tstr, ARGP_KEY_HELP_HEADER, argp, pest->state);
1017 if (fstr)
1019 if (*fstr)
1021 if (pest->hhstate->prev_entry)
1022 /* Precede with a blank line. */
1023 __argp_fmtstream_putc (pest->stream, '\n');
1024 indent_to (pest->stream, uparams.header_col);
1025 __argp_fmtstream_set_lmargin (pest->stream, uparams.header_col);
1026 __argp_fmtstream_set_wmargin (pest->stream, uparams.header_col);
1027 __argp_fmtstream_puts (pest->stream, fstr);
1028 __argp_fmtstream_set_lmargin (pest->stream, 0);
1029 __argp_fmtstream_putc (pest->stream, '\n');
1032 pest->hhstate->sep_groups = 1; /* Separate subsequent groups. */
1035 if (fstr != tstr)
1036 free ((char *) fstr);
1039 /* Inserts a comma if this isn't the first item on the line, and then makes
1040 sure we're at least to column COL. If this *is* the first item on a line,
1041 prints any pending whitespace/headers that should precede this line. Also
1042 clears FIRST. */
1043 static void
1044 comma (unsigned col, struct pentry_state *pest)
1046 if (pest->first)
1048 const struct hol_entry *pe = pest->hhstate->prev_entry;
1049 const struct hol_cluster *cl = pest->entry->cluster;
1051 if (pest->hhstate->sep_groups && pe && pest->entry->group != pe->group)
1052 __argp_fmtstream_putc (pest->stream, '\n');
1054 if (cl && cl->header && *cl->header
1055 && (!pe
1056 || (pe->cluster != cl
1057 && !hol_cluster_is_child (pe->cluster, cl))))
1058 /* If we're changing clusters, then this must be the start of the
1059 ENTRY's cluster unless that is an ancestor of the previous one
1060 (in which case we had just popped into a sub-cluster for a bit).
1061 If so, then print the cluster's header line. */
1063 int old_wm = __argp_fmtstream_wmargin (pest->stream);
1064 print_header (cl->header, cl->argp, pest);
1065 __argp_fmtstream_set_wmargin (pest->stream, old_wm);
1068 pest->first = 0;
1070 else
1071 __argp_fmtstream_puts (pest->stream, ", ");
1073 indent_to (pest->stream, col);
1076 /* Print help for ENTRY to STREAM. */
1077 static void
1078 hol_entry_help (struct hol_entry *entry, const struct argp_state *state,
1079 argp_fmtstream_t stream, struct hol_help_state *hhstate)
1081 unsigned num;
1082 const struct argp_option *real = entry->opt, *opt;
1083 char *so = entry->short_options;
1084 int have_long_opt = 0; /* We have any long options. */
1085 /* Saved margins. */
1086 int old_lm = __argp_fmtstream_set_lmargin (stream, 0);
1087 int old_wm = __argp_fmtstream_wmargin (stream);
1088 /* PEST is a state block holding some of our variables that we'd like to
1089 share with helper functions. */
1090 struct pentry_state pest = { entry, stream, hhstate, 1, state };
1092 if (! odoc (real))
1093 for (opt = real, num = entry->num; num > 0; opt++, num--)
1094 if (opt->name && ovisible (opt))
1096 have_long_opt = 1;
1097 break;
1100 /* First emit short options. */
1101 __argp_fmtstream_set_wmargin (stream, uparams.short_opt_col); /* For truly bizarre cases. */
1102 for (opt = real, num = entry->num; num > 0; opt++, num--)
1103 if (oshort (opt) && opt->key == *so)
1104 /* OPT has a valid (non shadowed) short option. */
1106 if (ovisible (opt))
1108 comma (uparams.short_opt_col, &pest);
1109 __argp_fmtstream_putc (stream, '-');
1110 __argp_fmtstream_putc (stream, *so);
1111 if (!have_long_opt || uparams.dup_args)
1112 arg (real, " %s", "[%s]",
1113 state == NULL ? NULL : state->root_argp->argp_domain,
1114 stream);
1115 else if (real->arg)
1116 hhstate->suppressed_dup_arg = 1;
1118 so++;
1121 /* Now, long options. */
1122 if (odoc (real))
1123 /* A `documentation' option. */
1125 __argp_fmtstream_set_wmargin (stream, uparams.doc_opt_col);
1126 for (opt = real, num = entry->num; num > 0; opt++, num--)
1127 if (opt->name && ovisible (opt))
1129 comma (uparams.doc_opt_col, &pest);
1130 /* Calling gettext here isn't quite right, since sorting will
1131 have been done on the original; but documentation options
1132 should be pretty rare anyway... */
1133 __argp_fmtstream_puts (stream,
1134 dgettext (state == NULL ? NULL
1135 : state->root_argp->argp_domain,
1136 opt->name));
1139 else
1140 /* A real long option. */
1142 __argp_fmtstream_set_wmargin (stream, uparams.long_opt_col);
1143 for (opt = real, num = entry->num; num > 0; opt++, num--)
1144 if (opt->name && ovisible (opt))
1146 comma (uparams.long_opt_col, &pest);
1147 __argp_fmtstream_printf (stream, "--%s", opt->name);
1148 arg (real, "=%s", "[=%s]",
1149 state == NULL ? NULL : state->root_argp->argp_domain, stream);
1153 /* Next, documentation strings. */
1154 __argp_fmtstream_set_lmargin (stream, 0);
1156 if (pest.first)
1158 /* Didn't print any switches, what's up? */
1159 if (!oshort (real) && !real->name)
1160 /* This is a group header, print it nicely. */
1161 print_header (real->doc, entry->argp, &pest);
1162 else
1163 /* Just a totally shadowed option or null header; print nothing. */
1164 goto cleanup; /* Just return, after cleaning up. */
1166 else
1168 const char *tstr = real->doc ? dgettext (state == NULL ? NULL
1169 : state->root_argp->argp_domain,
1170 real->doc) : 0;
1171 const char *fstr = filter_doc (tstr, real->key, entry->argp, state);
1172 if (fstr && *fstr)
1174 unsigned int col = __argp_fmtstream_point (stream);
1176 __argp_fmtstream_set_lmargin (stream, uparams.opt_doc_col);
1177 __argp_fmtstream_set_wmargin (stream, uparams.opt_doc_col);
1179 if (col > (unsigned int) (uparams.opt_doc_col + 3))
1180 __argp_fmtstream_putc (stream, '\n');
1181 else if (col >= (unsigned int) uparams.opt_doc_col)
1182 __argp_fmtstream_puts (stream, " ");
1183 else
1184 indent_to (stream, uparams.opt_doc_col);
1186 __argp_fmtstream_puts (stream, fstr);
1188 if (fstr && fstr != tstr)
1189 free ((char *) fstr);
1191 /* Reset the left margin. */
1192 __argp_fmtstream_set_lmargin (stream, 0);
1193 __argp_fmtstream_putc (stream, '\n');
1196 hhstate->prev_entry = entry;
1198 cleanup:
1199 __argp_fmtstream_set_lmargin (stream, old_lm);
1200 __argp_fmtstream_set_wmargin (stream, old_wm);
1203 /* Output a long help message about the options in HOL to STREAM. */
1204 static void
1205 hol_help (struct hol *hol, const struct argp_state *state,
1206 argp_fmtstream_t stream)
1208 unsigned num;
1209 struct hol_entry *entry;
1210 struct hol_help_state hhstate = { 0, 0, 0 };
1212 for (entry = hol->entries, num = hol->num_entries; num > 0; entry++, num--)
1213 hol_entry_help (entry, state, stream, &hhstate);
1215 if (hhstate.suppressed_dup_arg && uparams.dup_args_note)
1217 const char *tstr = dgettext (state == NULL ? NULL
1218 : state->root_argp->argp_domain, "\
1219 Mandatory or optional arguments to long options are also mandatory or \
1220 optional for any corresponding short options.");
1221 const char *fstr = filter_doc (tstr, ARGP_KEY_HELP_DUP_ARGS_NOTE,
1222 state ? state->root_argp : 0, state);
1223 if (fstr && *fstr)
1225 __argp_fmtstream_putc (stream, '\n');
1226 __argp_fmtstream_puts (stream, fstr);
1227 __argp_fmtstream_putc (stream, '\n');
1229 if (fstr && fstr != tstr)
1230 free ((char *) fstr);
1234 /* Helper functions for hol_usage. */
1236 /* If OPT is a short option without an arg, append its key to the string
1237 pointer pointer to by COOKIE, and advance the pointer. */
1238 static int
1239 add_argless_short_opt (const struct argp_option *opt,
1240 const struct argp_option *real,
1241 const char *domain, void *cookie)
1243 char **snao_end = cookie;
1244 if (!(opt->arg || real->arg)
1245 && !((opt->flags | real->flags) & OPTION_NO_USAGE))
1246 *(*snao_end)++ = opt->key;
1247 return 0;
1250 /* If OPT is a short option with an arg, output a usage entry for it to the
1251 stream pointed at by COOKIE. */
1252 static int
1253 usage_argful_short_opt (const struct argp_option *opt,
1254 const struct argp_option *real,
1255 const char *domain, void *cookie)
1257 argp_fmtstream_t stream = cookie;
1258 const char *arg = opt->arg;
1259 int flags = opt->flags | real->flags;
1261 if (! arg)
1262 arg = real->arg;
1264 if (arg && !(flags & OPTION_NO_USAGE))
1266 arg = dgettext (domain, arg);
1268 if (flags & OPTION_ARG_OPTIONAL)
1269 __argp_fmtstream_printf (stream, " [-%c[%s]]", opt->key, arg);
1270 else
1272 /* Manually do line wrapping so that it (probably) won't
1273 get wrapped at the embedded space. */
1274 space (stream, 6 + strlen (arg));
1275 __argp_fmtstream_printf (stream, "[-%c %s]", opt->key, arg);
1279 return 0;
1282 /* Output a usage entry for the long option opt to the stream pointed at by
1283 COOKIE. */
1284 static int
1285 usage_long_opt (const struct argp_option *opt,
1286 const struct argp_option *real,
1287 const char *domain, void *cookie)
1289 argp_fmtstream_t stream = cookie;
1290 const char *arg = opt->arg;
1291 int flags = opt->flags | real->flags;
1293 if (! arg)
1294 arg = real->arg;
1296 if (! (flags & OPTION_NO_USAGE))
1298 if (arg)
1300 arg = dgettext (domain, arg);
1301 if (flags & OPTION_ARG_OPTIONAL)
1302 __argp_fmtstream_printf (stream, " [--%s[=%s]]", opt->name, arg);
1303 else
1304 __argp_fmtstream_printf (stream, " [--%s=%s]", opt->name, arg);
1306 else
1307 __argp_fmtstream_printf (stream, " [--%s]", opt->name);
1310 return 0;
1313 /* Print a short usage description for the arguments in HOL to STREAM. */
1314 static void
1315 hol_usage (struct hol *hol, argp_fmtstream_t stream)
1317 if (hol->num_entries > 0)
1319 unsigned nentries;
1320 struct hol_entry *entry;
1321 char *short_no_arg_opts = alloca (strlen (hol->short_options) + 1);
1322 char *snao_end = short_no_arg_opts;
1324 /* First we put a list of short options without arguments. */
1325 for (entry = hol->entries, nentries = hol->num_entries
1326 ; nentries > 0
1327 ; entry++, nentries--)
1328 hol_entry_short_iterate (entry, add_argless_short_opt,
1329 entry->argp->argp_domain, &snao_end);
1330 if (snao_end > short_no_arg_opts)
1332 *snao_end++ = 0;
1333 __argp_fmtstream_printf (stream, " [-%s]", short_no_arg_opts);
1336 /* Now a list of short options *with* arguments. */
1337 for (entry = hol->entries, nentries = hol->num_entries
1338 ; nentries > 0
1339 ; entry++, nentries--)
1340 hol_entry_short_iterate (entry, usage_argful_short_opt,
1341 entry->argp->argp_domain, stream);
1343 /* Finally, a list of long options (whew!). */
1344 for (entry = hol->entries, nentries = hol->num_entries
1345 ; nentries > 0
1346 ; entry++, nentries--)
1347 hol_entry_long_iterate (entry, usage_long_opt,
1348 entry->argp->argp_domain, stream);
1352 /* Make a HOL containing all levels of options in ARGP. CLUSTER is the
1353 cluster in which ARGP's entries should be clustered, or 0. */
1354 static struct hol *
1355 argp_hol (const struct argp *argp, struct hol_cluster *cluster)
1357 const struct argp_child *child = argp->children;
1358 struct hol *hol = make_hol (argp, cluster);
1359 if (child)
1360 while (child->argp)
1362 struct hol_cluster *child_cluster =
1363 ((child->group || child->header)
1364 /* Put CHILD->argp within its own cluster. */
1365 ? hol_add_cluster (hol, child->group, child->header,
1366 child - argp->children, cluster, argp)
1367 /* Just merge it into the parent's cluster. */
1368 : cluster);
1369 hol_append (hol, argp_hol (child->argp, child_cluster)) ;
1370 child++;
1372 return hol;
1375 /* Calculate how many different levels with alternative args strings exist in
1376 ARGP. */
1377 static size_t
1378 argp_args_levels (const struct argp *argp)
1380 size_t levels = 0;
1381 const struct argp_child *child = argp->children;
1383 if (argp->args_doc && strchr (argp->args_doc, '\n'))
1384 levels++;
1386 if (child)
1387 while (child->argp)
1388 levels += argp_args_levels ((child++)->argp);
1390 return levels;
1393 /* Print all the non-option args documented in ARGP to STREAM. Any output is
1394 preceded by a space. LEVELS is a pointer to a byte vector the length
1395 returned by argp_args_levels; it should be initialized to zero, and
1396 updated by this routine for the next call if ADVANCE is true. True is
1397 returned as long as there are more patterns to output. */
1398 static int
1399 argp_args_usage (const struct argp *argp, const struct argp_state *state,
1400 char **levels, int advance, argp_fmtstream_t stream)
1402 char *our_level = *levels;
1403 int multiple = 0;
1404 const struct argp_child *child = argp->children;
1405 const char *tdoc = dgettext (argp->argp_domain, argp->args_doc), *nl = 0;
1406 const char *fdoc = filter_doc (tdoc, ARGP_KEY_HELP_ARGS_DOC, argp, state);
1408 if (fdoc)
1410 const char *cp = fdoc;
1411 nl = strchrnul (cp, '\n');
1412 if (*nl != '\0')
1413 /* This is a `multi-level' args doc; advance to the correct position
1414 as determined by our state in LEVELS, and update LEVELS. */
1416 int i;
1417 multiple = 1;
1418 for (i = 0; i < *our_level; i++)
1419 cp = nl + 1, nl = strchrnul (cp, '\n');
1420 (*levels)++;
1423 /* Manually do line wrapping so that it (probably) won't get wrapped at
1424 any embedded spaces. */
1425 space (stream, 1 + nl - cp);
1427 __argp_fmtstream_write (stream, cp, nl - cp);
1429 if (fdoc && fdoc != tdoc)
1430 free ((char *)fdoc); /* Free user's modified doc string. */
1432 if (child)
1433 while (child->argp)
1434 advance = !argp_args_usage ((child++)->argp, state, levels, advance, stream);
1436 if (advance && multiple)
1438 /* Need to increment our level. */
1439 if (*nl)
1440 /* There's more we can do here. */
1442 (*our_level)++;
1443 advance = 0; /* Our parent shouldn't advance also. */
1445 else if (*our_level > 0)
1446 /* We had multiple levels, but used them up; reset to zero. */
1447 *our_level = 0;
1450 return !advance;
1453 /* Print the documentation for ARGP to STREAM; if POST is false, then
1454 everything preceeding a `\v' character in the documentation strings (or
1455 the whole string, for those with none) is printed, otherwise, everything
1456 following the `\v' character (nothing for strings without). Each separate
1457 bit of documentation is separated a blank line, and if PRE_BLANK is true,
1458 then the first is as well. If FIRST_ONLY is true, only the first
1459 occurrence is output. Returns true if anything was output. */
1460 static int
1461 argp_doc (const struct argp *argp, const struct argp_state *state,
1462 int post, int pre_blank, int first_only,
1463 argp_fmtstream_t stream)
1465 const char *text;
1466 const char *inp_text;
1467 void *input = 0;
1468 int anything = 0;
1469 size_t inp_text_limit = 0;
1470 const char *doc = dgettext (argp->argp_domain, argp->doc);
1471 const struct argp_child *child = argp->children;
1473 if (doc)
1475 char *vt = strchr (doc, '\v');
1476 inp_text = post ? (vt ? vt + 1 : 0) : doc;
1477 inp_text_limit = (!post && vt) ? (vt - doc) : 0;
1479 else
1480 inp_text = 0;
1482 if (argp->help_filter)
1483 /* We have to filter the doc strings. */
1485 if (inp_text_limit)
1486 /* Copy INP_TEXT so that it's nul-terminated. */
1487 inp_text = strndup (inp_text, inp_text_limit);
1488 input = __argp_input (argp, state);
1489 text =
1490 (*argp->help_filter) (post
1491 ? ARGP_KEY_HELP_POST_DOC
1492 : ARGP_KEY_HELP_PRE_DOC,
1493 inp_text, input);
1495 else
1496 text = (const char *) inp_text;
1498 if (text)
1500 if (pre_blank)
1501 __argp_fmtstream_putc (stream, '\n');
1503 if (text == inp_text && inp_text_limit)
1504 __argp_fmtstream_write (stream, inp_text, inp_text_limit);
1505 else
1506 __argp_fmtstream_puts (stream, text);
1508 if (__argp_fmtstream_point (stream) > __argp_fmtstream_lmargin (stream))
1509 __argp_fmtstream_putc (stream, '\n');
1511 anything = 1;
1514 if (text && text != inp_text)
1515 free ((char *) text); /* Free TEXT returned from the help filter. */
1516 if (inp_text && inp_text_limit && argp->help_filter)
1517 free ((char *) inp_text); /* We copied INP_TEXT, so free it now. */
1519 if (post && argp->help_filter)
1520 /* Now see if we have to output a ARGP_KEY_HELP_EXTRA text. */
1522 text = (*argp->help_filter) (ARGP_KEY_HELP_EXTRA, 0, input);
1523 if (text)
1525 if (anything || pre_blank)
1526 __argp_fmtstream_putc (stream, '\n');
1527 __argp_fmtstream_puts (stream, text);
1528 free ((char *) text);
1529 if (__argp_fmtstream_point (stream)
1530 > __argp_fmtstream_lmargin (stream))
1531 __argp_fmtstream_putc (stream, '\n');
1532 anything = 1;
1536 if (child)
1537 while (child->argp && !(first_only && anything))
1538 anything |=
1539 argp_doc ((child++)->argp, state,
1540 post, anything || pre_blank, first_only,
1541 stream);
1543 return anything;
1546 /* Output a usage message for ARGP to STREAM. If called from
1547 argp_state_help, STATE is the relevent parsing state. FLAGS are from the
1548 set ARGP_HELP_*. NAME is what to use wherever a `program name' is
1549 needed. */
1550 static void
1551 _help (const struct argp *argp, const struct argp_state *state, FILE *stream,
1552 unsigned flags, char *name)
1554 int anything = 0; /* Whether we've output anything. */
1555 struct hol *hol = 0;
1556 argp_fmtstream_t fs;
1558 if (! stream)
1559 return;
1561 #if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
1562 flockfile (stream);
1563 #endif
1565 fill_in_uparams (state);
1567 fs = __argp_make_fmtstream (stream, 0, uparams.rmargin, 0);
1568 if (! fs)
1570 #if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
1571 funlockfile (stream);
1572 #endif
1573 return;
1576 if (flags & (ARGP_HELP_USAGE | ARGP_HELP_SHORT_USAGE | ARGP_HELP_LONG))
1578 hol = argp_hol (argp, 0);
1580 /* If present, these options always come last. */
1581 hol_set_group (hol, "help", -1);
1582 hol_set_group (hol, "version", -1);
1584 hol_sort (hol);
1587 if (flags & (ARGP_HELP_USAGE | ARGP_HELP_SHORT_USAGE))
1588 /* Print a short `Usage:' message. */
1590 int first_pattern = 1, more_patterns;
1591 size_t num_pattern_levels = argp_args_levels (argp);
1592 char *pattern_levels = alloca (num_pattern_levels);
1594 memset (pattern_levels, 0, num_pattern_levels);
1598 int old_lm;
1599 int old_wm = __argp_fmtstream_set_wmargin (fs, uparams.usage_indent);
1600 char *levels = pattern_levels;
1602 if (first_pattern)
1603 __argp_fmtstream_printf (fs, "%s %s",
1604 dgettext (argp->argp_domain, "Usage:"),
1605 name);
1606 else
1607 __argp_fmtstream_printf (fs, "%s %s",
1608 dgettext (argp->argp_domain, " or: "),
1609 name);
1611 /* We set the lmargin as well as the wmargin, because hol_usage
1612 manually wraps options with newline to avoid annoying breaks. */
1613 old_lm = __argp_fmtstream_set_lmargin (fs, uparams.usage_indent);
1615 if (flags & ARGP_HELP_SHORT_USAGE)
1616 /* Just show where the options go. */
1618 if (hol->num_entries > 0)
1619 __argp_fmtstream_puts (fs, dgettext (argp->argp_domain,
1620 " [OPTION...]"));
1622 else
1623 /* Actually print the options. */
1625 hol_usage (hol, fs);
1626 flags |= ARGP_HELP_SHORT_USAGE; /* But only do so once. */
1629 more_patterns = argp_args_usage (argp, state, &levels, 1, fs);
1631 __argp_fmtstream_set_wmargin (fs, old_wm);
1632 __argp_fmtstream_set_lmargin (fs, old_lm);
1634 __argp_fmtstream_putc (fs, '\n');
1635 anything = 1;
1637 first_pattern = 0;
1639 while (more_patterns);
1642 if (flags & ARGP_HELP_PRE_DOC)
1643 anything |= argp_doc (argp, state, 0, 0, 1, fs);
1645 if (flags & ARGP_HELP_SEE)
1647 __argp_fmtstream_printf (fs, dgettext (argp->argp_domain, "\
1648 Try `%s --help' or `%s --usage' for more information.\n"),
1649 name, name);
1650 anything = 1;
1653 if (flags & ARGP_HELP_LONG)
1654 /* Print a long, detailed help message. */
1656 /* Print info about all the options. */
1657 if (hol->num_entries > 0)
1659 if (anything)
1660 __argp_fmtstream_putc (fs, '\n');
1661 hol_help (hol, state, fs);
1662 anything = 1;
1666 if (flags & ARGP_HELP_POST_DOC)
1667 /* Print any documentation strings at the end. */
1668 anything |= argp_doc (argp, state, 1, anything, 0, fs);
1670 if ((flags & ARGP_HELP_BUG_ADDR) && argp_program_bug_address)
1672 if (anything)
1673 __argp_fmtstream_putc (fs, '\n');
1674 __argp_fmtstream_printf (fs, dgettext (argp->argp_domain,
1675 "Report bugs to %s.\n"),
1676 argp_program_bug_address);
1677 anything = 1;
1680 #if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
1681 funlockfile (stream);
1682 #endif
1684 if (hol)
1685 hol_free (hol);
1687 __argp_fmtstream_free (fs);
1690 /* Output a usage message for ARGP to STREAM. FLAGS are from the set
1691 ARGP_HELP_*. NAME is what to use wherever a `program name' is needed. */
1692 void argp_help (const struct argp *argp, FILE *stream,
1693 unsigned flags, char *name)
1695 _help (argp, 0, stream, flags, name);
1698 char *
1699 __argp_short_program_name (void)
1701 # ifdef __UCLIBC_HAS_PROGRAM_INVOCATION_NAME__
1703 * uClibc provides both program_invocation_name and
1704 * program_invocation_short_name
1706 return (char *) program_invocation_short_name;
1707 # else
1708 /* FIXME: What now? Miles suggests that it is better to use NULL,
1709 but currently the value is passed on directly to fputs_unlocked,
1710 so that requires more changes. */
1711 # if __GNUC__
1712 # warning No reasonable value to return
1713 # endif /* __GNUC__ */
1714 return "";
1715 # endif
1718 /* Output, if appropriate, a usage message for STATE to STREAM. FLAGS are
1719 from the set ARGP_HELP_*. */
1720 void
1721 argp_state_help (const struct argp_state *state, FILE *stream, unsigned flags)
1723 if ((!state || ! (state->flags & ARGP_NO_ERRS)) && stream)
1725 if (state && (state->flags & ARGP_LONG_ONLY))
1726 flags |= ARGP_HELP_LONG_ONLY;
1728 _help (state ? state->root_argp : 0, state, stream, flags,
1729 state ? state->name : __argp_short_program_name ());
1731 if (!state || ! (state->flags & ARGP_NO_EXIT))
1733 if (flags & ARGP_HELP_EXIT_ERR)
1734 exit (argp_err_exit_status);
1735 if (flags & ARGP_HELP_EXIT_OK)
1736 exit (0);
1741 /* If appropriate, print the printf string FMT and following args, preceded
1742 by the program name and `:', to stderr, and followed by a `Try ... --help'
1743 message, then exit (1). */
1744 void
1745 argp_error (const struct argp_state *state, const char *fmt, ...)
1747 if (!state || !(state->flags & ARGP_NO_ERRS))
1749 FILE *stream = state ? state->err_stream : stderr;
1751 if (stream)
1753 va_list ap;
1755 #if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
1756 flockfile (stream);
1757 #endif
1759 va_start (ap, fmt);
1761 #if defined _LIBC && defined USE_IN_LIBIO
1762 char *buf;
1764 if (_IO_vasprintf (&buf, fmt, ap) < 0)
1765 buf = NULL;
1767 __fxprintf (stream, "%s: %s\n",
1768 state ? state->name : __argp_short_program_name (), buf);
1770 free (buf);
1771 #else
1772 fputs_unlocked (state ? state->name : __argp_short_program_name (),
1773 stream);
1774 putc_unlocked (':', stream);
1775 putc_unlocked (' ', stream);
1777 vfprintf (stream, fmt, ap);
1779 putc_unlocked ('\n', stream);
1780 #endif
1782 argp_state_help (state, stream, ARGP_HELP_STD_ERR);
1784 va_end (ap);
1786 #if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
1787 funlockfile (stream);
1788 #endif
1793 /* Similar to the standard gnu error-reporting function error(), but will
1794 respect the ARGP_NO_EXIT and ARGP_NO_ERRS flags in STATE, and will print
1795 to STATE->err_stream. This is useful for argument parsing code that is
1796 shared between program startup (when exiting is desired) and runtime
1797 option parsing (when typically an error code is returned instead). The
1798 difference between this function and argp_error is that the latter is for
1799 *parsing errors*, and the former is for other problems that occur during
1800 parsing but don't reflect a (syntactic) problem with the input. */
1801 void
1802 argp_failure (const struct argp_state *state, int status, int errnum,
1803 const char *fmt, ...)
1805 if (!state || !(state->flags & ARGP_NO_ERRS))
1807 FILE *stream = state ? state->err_stream : stderr;
1809 if (stream)
1811 #if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
1812 flockfile (stream);
1813 #endif
1815 #if defined _LIBC && defined USE_IN_LIBIO
1816 __fxprintf (stream, "%s",
1817 state ? state->name : __argp_short_program_name ());
1818 #else
1819 fputs_unlocked (state ? state->name : __argp_short_program_name (),
1820 stream);
1821 #endif
1823 if (fmt)
1825 va_list ap;
1827 va_start (ap, fmt);
1828 #if defined _LIBC && defined USE_IN_LIBIO
1829 char *buf;
1831 if (_IO_vasprintf (&buf, fmt, ap) < 0)
1832 buf = NULL;
1834 __fxprintf (stream, ": %s", buf);
1836 free (buf);
1837 #else
1838 putc_unlocked (':', stream);
1839 putc_unlocked (' ', stream);
1841 vfprintf (stream, fmt, ap);
1842 #endif
1844 va_end (ap);
1847 if (errnum)
1849 #if (defined _LIBC && defined USE_IN_LIBIO) || defined HAVE_STRERROR_R
1850 char buf[200];
1851 #endif
1852 #if defined _LIBC && defined USE_IN_LIBIO
1853 __fxprintf (stream, ": %s",
1854 strerror_r (errnum, buf, sizeof (buf)));
1855 #else
1856 putc_unlocked (':', stream);
1857 putc_unlocked (' ', stream);
1858 # ifdef HAVE_STRERROR_R
1859 fputs (strerror_r (errnum, buf, sizeof (buf)), stream);
1860 # else
1861 fputs (strerror (errnum), stream);
1862 # endif
1863 #endif
1866 #ifdef USE_IN_LIBIO
1867 if (_IO_fwide (stream, 0) > 0)
1868 putwc_unlocked (L'\n', stream);
1869 else
1870 #endif
1871 putc_unlocked ('\n', stream);
1873 #if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
1874 funlockfile (stream);
1875 #endif
1877 if (status && (!state || !(state->flags & ARGP_NO_EXIT)))
1878 exit (status);