argp-help.c
上传用户:shenzhenrh
上传日期:2013-05-12
资源大小:2904k
文件大小:51k
源码类别:

信息检索与抽取

开发平台:

Unix_Linux

  1. /* Hierarchial argument parsing help output
  2.    Copyright (C) 1995, 1996, 1997 Free Software Foundation, Inc.
  3.    This file is part of the GNU C Library.
  4.    Written by Miles Bader <miles@gnu.ai.mit.edu>.
  5.    The GNU C Library is free software; you can redistribute it and/or
  6.    modify it under the terms of the GNU Library General Public License as
  7.    published by the Free Software Foundation; either version 2 of the
  8.    License, or (at your option) any later version.
  9.    The GNU C Library is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  12.    Library General Public License for more details.
  13.    You should have received a copy of the GNU Library General Public
  14.    License along with the GNU C Library; see the file COPYING.LIB.  If not,
  15.    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  16.    Boston, MA 02111-1307, USA.  */
  17. /* Modified for use with garbage collecting malloc.
  18.    marcus@sysc.pdx.edu 1997-09-02 */
  19. #ifdef HAVE_CONFIG_H
  20. #include <swarmconfig.h>
  21. #endif
  22. #include <misc.h>
  23. #include <assert.h>
  24. #ifndef _
  25. /* This is for other GNU distributions with internationalized messages.
  26.    When compiling libc, the _ macro is predefined.  */
  27. #ifdef HAVE_LIBINTL_H
  28. # include <libintl.h>
  29. # define _(msgid)       gettext (msgid)
  30. #else
  31. # define _(msgid)       (msgid)
  32. # define gettext(msgid) (msgid)
  33. #endif
  34. #endif
  35. #include "argp.h"
  36. #include "argp-fmtstream.h"
  37. #include "argp-namefrob.h"
  38. /* User-selectable (using an environment variable) formatting parameters.
  39.    These may be specified in an environment variable called `ARGP_HELP_FMT',
  40.    with a contents like:  VAR1=VAL1,VAR2=VAL2,BOOLVAR2,no-BOOLVAR2
  41.    Where VALn must be a positive integer.  The list of variables is in the
  42.    UPARAM_NAMES vector, below.  */
  43. /* Default parameters.  */
  44. #define DUP_ARGS      0 /* True if option argument can be duplicated. */
  45. #define DUP_ARGS_NOTE 1 /* True to print a note about duplicate args. */
  46. #define SHORT_OPT_COL 2 /* column in which short options start */
  47. #define LONG_OPT_COL  6 /* column in which long options start */
  48. #define DOC_OPT_COL   2 /* column in which doc options start */
  49. #define OPT_DOC_COL  29 /* column in which option text starts */
  50. #define HEADER_COL    1 /* column in which group headers are printed */
  51. #define USAGE_INDENT 12 /* indentation of wrapped usage lines */
  52. #define RMARGIN      79 /* right margin used for wrapping */
  53. /* User-selectable (using an environment variable) formatting parameters.
  54.    They must all be of type `int' for the parsing code to work.  */
  55. struct uparams
  56. {
  57.   /* If true, arguments for an option are shown with both short and long
  58.      options, even when a given option has both, e.g. `-x ARG, --longx=ARG'.
  59.      If false, then if an option has both, the argument is only shown with
  60.      the long one, e.g., `-x, --longx=ARG', and a message indicating that
  61.      this really means both is printed below the options.  */
  62.   int dup_args;
  63.   /* This is true if when DUP_ARGS is false, and some duplicate arguments have
  64.      been suppressed, an explanatory message should be printed.  */
  65.   int dup_args_note;
  66.   /* Various output columns.  */
  67.   int short_opt_col;
  68.   int long_opt_col;
  69.   int doc_opt_col;
  70.   int opt_doc_col;
  71.   int header_col;
  72.   int usage_indent;
  73.   int rmargin;
  74.   int valid; /* True when the values in here are valid.  */
  75. };
  76. /* This is a global variable, as user options are only ever read once.  */
  77. static struct uparams uparams = {
  78.   DUP_ARGS, DUP_ARGS_NOTE,
  79.   SHORT_OPT_COL, LONG_OPT_COL, DOC_OPT_COL, OPT_DOC_COL, HEADER_COL,
  80.   USAGE_INDENT, RMARGIN,
  81.   0
  82. };
  83. /* A particular uparam, and what the user name is.  */
  84. struct uparam_name
  85. {
  86.   const char *name; /* User name.  */
  87.   int is_bool; /* Whether it's `boolean'.  */
  88.   size_t uparams_offs; /* Location of the (int) field in UPARAMS.  */
  89. };
  90. /* The name-field mappings we know about.  */
  91. static const struct uparam_name uparam_names[] =
  92. {
  93.   { "dup-args",       1, offsetof (struct uparams, dup_args) },
  94.   { "dup-args-note",  1, offsetof (struct uparams, dup_args_note) },
  95.   { "short-opt-col",  0, offsetof (struct uparams, short_opt_col) },
  96.   { "long-opt-col",   0, offsetof (struct uparams, long_opt_col) },
  97.   { "doc-opt-col",    0, offsetof (struct uparams, doc_opt_col) },
  98.   { "opt-doc-col",    0, offsetof (struct uparams, opt_doc_col) },
  99.   { "header-col",     0, offsetof (struct uparams, header_col) },
  100.   { "usage-indent",   0, offsetof (struct uparams, usage_indent) },
  101.   { "rmargin",        0, offsetof (struct uparams, rmargin) },
  102.   { 0 }
  103. };
  104. /* Read user options from the environment, and fill in UPARAMS appropiately.  */
  105. static void
  106. fill_in_uparams (const struct argp_state *state)
  107. {
  108.   const char *var = getenv ("ARGP_HELP_FMT");
  109. #define SKIPWS(p) do { while (isSpace (*p)) p++; } while (0);
  110.   if (var)
  111.     /* Parse var. */
  112.     while (*var)
  113.       {
  114. SKIPWS (var);
  115. if (isAlpha (*var))
  116.   {
  117.     size_t var_len;
  118.     const struct uparam_name *un;
  119.     int unspec = 0, val = 0;
  120.     const char *arg = var;
  121.             
  122.     while (isAlnum (*arg) || *arg == '-' || *arg == '_')
  123.       arg++;
  124.     var_len = arg - var;
  125.     SKIPWS (arg);
  126.     if (*arg == '' || *arg == ',')
  127.       unspec = 1;
  128.     else if (*arg == '=')
  129.       {
  130. arg++;
  131. SKIPWS (arg);
  132.       }
  133.     if (unspec)
  134.               {
  135.                 if (var[0] == 'n' && var[1] == 'o' && var[2] == '-')
  136.                   {
  137.                     val = 0;
  138.                     var += 3;
  139.                     var_len -= 3;
  140.                   }
  141.                 else
  142.                   val = 1;
  143.               }
  144.     else if (isDigit (*arg))
  145.       {
  146. val = atoi (arg);
  147. while (isDigit (*arg))
  148.   arg++;
  149. SKIPWS (arg);
  150.       }
  151.     for (un = uparam_names; un->name; un++)
  152.       if (strlen (un->name) == var_len
  153.   && strncmp (var, un->name, var_len) == 0)
  154. {
  155.   if (unspec && !un->is_bool)
  156.     __argp_failure (state, 0, 0,
  157.    _("%.*s: ARGP_HELP_FMT parameter requires a value"),
  158.     (int)var_len, var);
  159.   else
  160.     *(int *)((char *)&uparams + un->uparams_offs) = val;
  161.   break;
  162. }
  163.     if (! un->name)
  164.       __argp_failure (state, 0, 0,
  165.       _("%.*s: Unknown ARGP_HELP_FMT parameter"),
  166.       (int)var_len, var);
  167.     var = arg;
  168.     if (*var == ',')
  169.       var++;
  170.   }
  171. else if (*var)
  172.   {
  173.     __argp_failure (state, 0, 0,
  174.     _("Garbage in ARGP_HELP_FMT: %s"), var);
  175.     break;
  176.   }
  177.       }
  178. }
  179. /* Returns true if OPT hasn't been marked invisible.  Visibility only affects
  180.    whether OPT is displayed or used in sorting, not option shadowing.  */
  181. #define ovisible(opt) (! ((opt)->flags & OPTION_HIDDEN))
  182. /* Returns true if OPT is an alias for an earlier option.  */
  183. #define oalias(opt) ((opt)->flags & OPTION_ALIAS)
  184. /* Returns true if OPT is an documentation-only entry.  */
  185. #define odoc(opt) ((opt)->flags & OPTION_DOC)
  186. /* Returns true if OPT is the end-of-list marker for a list of options.  */
  187. #define oend(opt) __option_is_end (opt)
  188. /* Returns true if OPT has a short option.  */
  189. #define oshort(opt) __option_is_short (opt)
  190. /*
  191.    The help format for a particular option is like:
  192.      -xARG, -yARG, --long1=ARG, --long2=ARG        Documentation...
  193.    Where ARG will be omitted if there's no argument, for this option, or
  194.    will be surrounded by "[" and "]" appropiately if the argument is
  195.    optional.  The documentation string is word-wrapped appropiately, and if
  196.    the list of options is long enough, it will be started on a separate line.
  197.    If there are no short options for a given option, the first long option is
  198.    indented slighly in a way that's supposed to make most long options appear
  199.    to be in a separate column.
  200.    For example, the following output (from ps):
  201.      -p PID, --pid=PID          List the process PID
  202.  --pgrp=PGRP            List processes in the process group PGRP
  203.      -P, -x, --no-parent        Include processes without parents
  204.      -Q, --all-fields           Don't elide unusable fields (normally if there's
  205. some reason ps can't print a field for any
  206. process, it's removed from the output entirely)
  207.      -r, --reverse, --gratuitously-long-reverse-option
  208. Reverse the order of any sort
  209.  --session[=SID]        Add the processes from the session SID (which
  210. defaults to the sid of the current process)
  211.     Here are some more options:
  212.      -f ZOT, --foonly=ZOT       Glork a foonly
  213.      -z, --zaza                 Snit a zar
  214.      -?, --help                 Give this help list
  215.  --usage                Give a short usage message
  216.      -V, --version              Print program version
  217.    The struct argp_option array for the above could look like:
  218.    {
  219.      {"pid",       'p',      "PID",  0, "List the process PID"},
  220.      {"pgrp",      OPT_PGRP, "PGRP", 0, "List processes in the process group PGRP"},
  221.      {"no-parent", 'P',       0,     0, "Include processes without parents"},
  222.      {0,           'x',       0,     OPTION_ALIAS},
  223.      {"all-fields",'Q',       0,     0, "Don't elide unusable fields (normally"
  224.                                         " if there's some reason ps can't"
  225. " print a field for any process, it's"
  226.                                         " removed from the output entirely)" },
  227.      {"reverse",   'r',       0,     0, "Reverse the order of any sort"},
  228.      {"gratuitously-long-reverse-option", 0, 0, OPTION_ALIAS},
  229.      {"session",   OPT_SESS,  "SID", OPTION_ARG_OPTIONAL,
  230.                                         "Add the processes from the session"
  231. " SID (which defaults to the sid of"
  232. " the current process)" },
  233.      {0,0,0,0, "Here are some more options:"},
  234.      {"foonly", 'f', "ZOT", 0, "Glork a foonly"},
  235.      {"zaza", 'z', 0, 0, "Snit a zar"},
  236.      {0}
  237.    }
  238.    Note that the last three options are automatically supplied by argp_parse,
  239.    unless you tell it not to with ARGP_NO_HELP.
  240. */
  241. /* Returns true if CH occurs between BEG and END.  */
  242. static int
  243. find_char (char ch, char *beg, char *end)
  244. {
  245.   while (beg < end)
  246.     if (*beg == ch)
  247.       return 1;
  248.     else
  249.       beg++;
  250.   return 0;
  251. }
  252. struct hol_cluster; /* fwd decl */
  253. struct hol_entry
  254. {
  255.   /* First option.  */
  256.   const struct argp_option *opt;
  257.   /* Number of options (including aliases).  */
  258.   unsigned num;
  259.   /* A pointers into the HOL's short_options field, to the first short option
  260.      letter for this entry.  The order of the characters following this point
  261.      corresponds to the order of options pointed to by OPT, and there are at
  262.      most NUM.  A short option recorded in a option following OPT is only
  263.      valid if it occurs in the right place in SHORT_OPTIONS (otherwise it's
  264.      probably been shadowed by some other entry).  */
  265.   char *short_options;
  266.   /* Entries are sorted by their group first, in the order:
  267.        1, 2, ..., n, 0, -m, ..., -2, -1
  268.      and then alphabetically within each group.  The default is 0.  */
  269.   int group;
  270.   /* The cluster of options this entry belongs to, or 0 if none.  */
  271.   struct hol_cluster *cluster;
  272.   /* The argp from which this option came.  */
  273.   const struct argp *argp;
  274. };
  275. /* A cluster of entries to reflect the argp tree structure.  */
  276. struct hol_cluster
  277. {
  278.   /* A descriptive header printed before options in this cluster.  */
  279.   const char *header;
  280.   /* Used to order clusters within the same group with the same parent,
  281.      according to the order in which they occured in the parent argp's child
  282.      list.  */
  283.   int index;
  284.   /* How to sort this cluster with respect to options and other clusters at the
  285.      same depth (clusters always follow options in the same group).  */
  286.   int group;
  287.   /* The cluster to which this cluster belongs, or 0 if it's at the base
  288.      level.  */
  289.   struct hol_cluster *parent;
  290.   /* The argp from which this cluster is (eventually) derived.  */
  291.   const struct argp *argp;
  292.   /* The distance this cluster is from the root.  */
  293.   int depth;
  294.   /* Clusters in a given hol are kept in a linked list, to make freeing them
  295.      possible.  */
  296.   struct hol_cluster *next;
  297. };
  298. /* A list of options for help.  */
  299. struct hol
  300. {
  301.   /* An array of hol_entry's.  */
  302.   struct hol_entry *entries;
  303.   /* The number of entries in this hol.  If this field is zero, the others
  304.      are undefined.  */
  305.   unsigned num_entries;
  306.   /* A string containing all short options in this HOL.  Each entry contains
  307.      pointers into this string, so the order can't be messed with blindly.  */
  308.   char *short_options;
  309.   /* Clusters of entries in this hol.  */
  310.   struct hol_cluster *clusters;
  311. };
  312. /* Create a struct hol from the options in ARGP.  CLUSTER is the
  313.    hol_cluster in which these entries occur, or 0, if at the root.  */
  314. static struct hol *
  315. make_hol (const struct argp *argp, struct hol_cluster *cluster)
  316. {
  317.   char *so;
  318.   const struct argp_option *o;
  319.   const struct argp_option *opts = argp->options;
  320.   struct hol_entry *entry;
  321.   unsigned num_short_options = 0;
  322.   struct hol *hol = xmalloc (sizeof (struct hol));
  323.   hol->num_entries = 0;
  324.   hol->clusters = 0;
  325.   if (opts)
  326.     {
  327.       int cur_group = 0;
  328.       /* The first option must not be an alias.  */
  329.       assert (! oalias (opts));
  330.       /* Calculate the space needed.  */
  331.       for (o = opts; ! oend (o); o++)
  332. {
  333.   if (! oalias (o))
  334.     hol->num_entries++;
  335.   if (oshort (o))
  336.     num_short_options++; /* This is an upper bound.  */
  337. }
  338.       hol->entries = xmalloc (sizeof (struct hol_entry) * hol->num_entries);
  339.       hol->short_options = xmalloc_atomic (num_short_options + 1);
  340.       assert (hol->entries && hol->short_options);
  341.       /* Fill in the entries.  */
  342.       so = hol->short_options;
  343.       for (o = opts, entry = hol->entries; ! oend (o); entry++)
  344. {
  345.   entry->opt = o;
  346.   entry->num = 0;
  347.   entry->short_options = so;
  348.   entry->group = cur_group =
  349.     o->group
  350.     ? o->group
  351.     : ((!o->name && !o->key)
  352.        ? cur_group + 1
  353.        : cur_group);
  354.   entry->cluster = cluster;
  355.   entry->argp = argp;
  356.   do
  357.     {
  358.       entry->num++;
  359.       if (oshort (o) && ! find_char (o->key, hol->short_options, so))
  360. /* O has a valid short option which hasn't already been used.*/
  361. *so++ = o->key;
  362.       o++;
  363.     }
  364.   while (! oend (o) && oalias (o));
  365. }
  366.       *so = ''; /* null terminated so we can find the length */
  367.     }
  368.   return hol;
  369. }
  370. /* Add a new cluster to HOL, with the given GROUP and HEADER (taken from the
  371.    associated argp child list entry), INDEX, and PARENT, and return a pointer
  372.    to it.  ARGP is the argp that this cluster results from.  */
  373. static struct hol_cluster *
  374. hol_add_cluster (struct hol *hol, int group, const char *header, int index,
  375.  struct hol_cluster *parent, const struct argp *argp)
  376. {
  377.   struct hol_cluster *cl = xmalloc (sizeof (struct hol_cluster));
  378.   if (cl)
  379.     {
  380.       cl->group = group;
  381.       cl->header = header;
  382.       cl->index = index;
  383.       cl->parent = parent;
  384.       cl->argp = argp;
  385.       cl->depth = parent ? parent->depth + 1 : 0;
  386.       cl->next = hol->clusters;
  387.       hol->clusters = cl;
  388.     }
  389.   return cl;
  390. }
  391. /* Free HOL and any resources it uses.  */
  392. static void
  393. hol_free (struct hol *hol)
  394. {
  395.   struct hol_cluster *cl = hol->clusters;
  396.   while (cl)
  397.     {
  398.       struct hol_cluster *next = cl->next;
  399.       xfree (cl);
  400.       cl = next;
  401.     }
  402.   if (hol->num_entries > 0)
  403.     {
  404.       xfree (hol->entries);
  405.       xfree (hol->short_options);
  406.     }
  407.   xfree (hol);
  408. }
  409. static inline int
  410. hol_entry_short_iterate (const struct hol_entry *entry,
  411.  int (*func)(const struct argp_option *opt,
  412.      const struct argp_option *real,
  413.      void *cookie),
  414.  void *cookie)
  415. {
  416.   unsigned nopts;
  417.   int val = 0;
  418.   const struct argp_option *opt, *real = entry->opt;
  419.   char *so = entry->short_options;
  420.   for (opt = real, nopts = entry->num; nopts > 0 && !val; opt++, nopts--)
  421.     if (oshort (opt) && *so == opt->key)
  422.       {
  423. if (!oalias (opt))
  424.   real = opt;
  425. if (ovisible (opt))
  426.   val = (*func)(opt, real, cookie);
  427. so++;
  428.       }
  429.   return val;
  430. }
  431. static inline int
  432. hol_entry_long_iterate (const struct hol_entry *entry,
  433. int (*func)(const struct argp_option *opt,
  434.     const struct argp_option *real,
  435.     void *cookie),
  436. void *cookie)
  437. {
  438.   unsigned nopts;
  439.   int val = 0;
  440.   const struct argp_option *opt, *real = entry->opt;
  441.   for (opt = real, nopts = entry->num; nopts > 0 && !val; opt++, nopts--)
  442.     if (opt->name)
  443.       {
  444. if (!oalias (opt))
  445.   real = opt;
  446. if (ovisible (opt))
  447.   val = (*func)(opt, real, cookie);
  448.       }
  449.   return val;
  450. }
  451. /* Iterator that returns true for the first short option.  */
  452. static inline int
  453. until_short (const struct argp_option *opt, const struct argp_option *real,
  454.      void *cookie)
  455. {
  456.   return oshort (opt) ? opt->key : 0;
  457. }
  458. /* Returns the first valid short option in ENTRY, or 0 if there is none.  */
  459. static char
  460. hol_entry_first_short (const struct hol_entry *entry)
  461. {
  462.   return hol_entry_short_iterate (entry, until_short, 0);
  463. }
  464. /* Returns the first valid long option in ENTRY, or 0 if there is none.  */
  465. static const char *
  466. hol_entry_first_long (const struct hol_entry *entry)
  467. {
  468.   const struct argp_option *opt;
  469.   unsigned num;
  470.   for (opt = entry->opt, num = entry->num; num > 0; opt++, num--)
  471.     if (opt->name && ovisible (opt))
  472.       return opt->name;
  473.   return 0;
  474. }
  475. /* Returns the entry in HOL with the long option name NAME, or 0 if there is
  476.    none.  */
  477. static struct hol_entry *
  478. hol_find_entry (struct hol *hol, const char *name)
  479. {
  480.   struct hol_entry *entry = hol->entries;
  481.   unsigned num_entries = hol->num_entries;
  482.   while (num_entries-- > 0)
  483.     {
  484.       const struct argp_option *opt = entry->opt;
  485.       unsigned num_opts = entry->num;
  486.       while (num_opts-- > 0)
  487. if (opt->name && ovisible (opt) && strcmp (opt->name, name) == 0)
  488.   return entry;
  489. else
  490.   opt++;
  491.       entry++;
  492.     }
  493.   return 0;
  494. }
  495. /* If an entry with the long option NAME occurs in HOL, set it's special
  496.    sort position to GROUP.  */
  497. static void
  498. hol_set_group (struct hol *hol, const char *name, int group)
  499. {
  500.   struct hol_entry *entry = hol_find_entry (hol, name);
  501.   if (entry)
  502.     entry->group = group;
  503. }
  504. /* Order by group:  0, 1, 2, ..., n, -m, ..., -2, -1.
  505.    EQ is what to return if GROUP1 and GROUP2 are the same.  */
  506. static int
  507. group_cmp (int group1, int group2, int eq)
  508. {
  509.   if (group1 == group2)
  510.     return eq;
  511.   else if ((group1 < 0 && group2 < 0) || (group1 >= 0 && group2 >= 0))
  512.     return group1 - group2;
  513.   else
  514.     return group2 - group1;
  515. }
  516. /* Compare clusters CL1 & CL2 by the order that they should appear in
  517.    output.  */
  518. static int
  519. hol_cluster_cmp (const struct hol_cluster *cl1, const struct hol_cluster *cl2)
  520. {
  521.   /* If one cluster is deeper than the other, use its ancestor at the same
  522.      level, so that finding the common ancestor is straightforward.  */
  523.   while (cl1->depth < cl2->depth)
  524.     cl1 = cl1->parent;
  525.   while (cl2->depth < cl1->depth)
  526.     cl2 = cl2->parent;
  527.   /* Now reduce both clusters to their ancestors at the point where both have
  528.      a common parent; these can be directly compared.  */
  529.   while (cl1->parent != cl2->parent)
  530.     cl1 = cl1->parent, cl2 = cl2->parent;
  531.   return group_cmp (cl1->group, cl2->group, cl2->index - cl1->index);
  532. }
  533. /* Return the ancestor of CL that's just below the root (i.e., has a parent
  534.    of 0).  */
  535. static struct hol_cluster *
  536. hol_cluster_base (struct hol_cluster *cl)
  537. {
  538.   while (cl->parent)
  539.     cl = cl->parent;
  540.   return cl;
  541. }
  542. /* Return true if CL1 is a child of CL2.  */
  543. static int
  544. hol_cluster_is_child (const struct hol_cluster *cl1,
  545.       const struct hol_cluster *cl2)
  546. {
  547.   while (cl1 && cl1 != cl2)
  548.     cl1 = cl1->parent;
  549.   return cl1 == cl2;
  550. }
  551. /* Given the name of a OPTION_DOC option, modifies NAME to start at the tail
  552.    that should be used for comparisons, and returns true iff it should be
  553.    treated as a non-option.  */
  554. static int
  555. canon_doc_option (const char **name)
  556. {
  557.   int non_opt;
  558.   /* Skip initial whitespace.  */
  559.   while (isSpace (**name))
  560.     (*name)++;
  561.   /* Decide whether this looks like an option (leading `-') or not.  */
  562.   non_opt = (**name != '-');
  563.   /* Skip until part of name used for sorting.  */
  564.   while (**name && !isAlnum (**name))
  565.     (*name)++;
  566.   return non_opt;
  567. }
  568. /* Order ENTRY1 & ENTRY2 by the order which they should appear in a help
  569.    listing.  */
  570. static int
  571. hol_entry_cmp (const struct hol_entry *entry1, const struct hol_entry *entry2)
  572. {
  573.   /* The group numbers by which the entries should be ordered; if either is
  574.      in a cluster, then this is just the group within the cluster.  */
  575.   int group1 = entry1->group, group2 = entry2->group;
  576.   if (entry1->cluster != entry2->cluster)
  577.     {
  578.       /* The entries are not within the same cluster, so we can't compare them
  579.          directly, we have to use the appropiate clustering level too.  */
  580.       if (! entry1->cluster)
  581.         /* ENTRY1 is at the `base level', not in a cluster, so we have to
  582.            compare it's group number with that of the base cluster in which
  583.            ENTRY2 resides.  Note that if they're in the same group, the
  584.            clustered option always comes laster.  */
  585.         return group_cmp (group1, hol_cluster_base (entry2->cluster)->group, -1);
  586.       else if (! entry2->cluster)
  587.         /* Likewise, but ENTRY2's not in a cluster.  */
  588.         return group_cmp (hol_cluster_base (entry1->cluster)->group, group2, 1);
  589.       else
  590.         /* Both entries are in clusters, we can just compare the clusters.  */
  591.         return hol_cluster_cmp (entry1->cluster, entry2->cluster);
  592.     }
  593.   else if (group1 == group2)
  594.     /* The entries are both in the same cluster and group, so compare them
  595.        alphabetically.  */
  596.     {
  597.       int short1 = hol_entry_first_short (entry1);
  598.       int short2 = hol_entry_first_short (entry2);
  599.       int doc1 = odoc (entry1->opt);
  600.       int doc2 = odoc (entry2->opt);
  601.       const char *long1 = hol_entry_first_long (entry1);
  602.       const char *long2 = hol_entry_first_long (entry2);
  603.       if (doc1)
  604. doc1 = canon_doc_option (&long1);
  605.       if (doc2)
  606. doc2 = canon_doc_option (&long2);
  607.       if (doc1 != doc2)
  608. /* `documentation' options always follow normal options (or
  609.    documentation options that *look* like normal options).  */
  610. return doc1 - doc2;
  611.       else if (!short1 && !short2 && long1 && long2)
  612. /* Only long options.  */
  613. return __strcasecmp (long1, long2);
  614.       else
  615. /* Compare short/short, long/short, short/long, using the first
  616.    character of long options.  Entries without *any* valid
  617.    options (such as options with OPTION_HIDDEN set) will be put
  618.    first, but as they're not displayed, it doesn't matter where
  619.    they are.  */
  620. {
  621.   char first1 = short1 ? short1 : long1 ? *long1 : 0;
  622.   char first2 = short2 ? short2 : long2 ? *long2 : 0;
  623.   int lower_cmp;
  624.   if (isUpper (first1))
  625.     first1 = (first1 - 'A') + 'a';
  626.   if (isUpper (first2))
  627.     first2 = (first2 - 'A') + 'a';
  628.   lower_cmp = first1 - first2;
  629.   /* Compare ignoring case, except when the options are both the
  630.      same letter, in which case lower-case always comes first.  */
  631.   return lower_cmp ? lower_cmp : first2 - first1;
  632. }
  633.     }
  634.   else
  635.     /* Within the same cluster, but not the same group, so just compare
  636.        groups.  */
  637.     return group_cmp (group1, group2, 0);
  638. }
  639. /* Version of hol_entry_cmp with correct signature for qsort.  */
  640. static int
  641. hol_entry_qcmp (const void *entry1_v, const void *entry2_v)
  642. {
  643.   return hol_entry_cmp (entry1_v, entry2_v);
  644. }
  645. /* Sort HOL by group and alphabetically by option name (with short options
  646.    taking precedence over long).  Since the sorting is for display purposes
  647.    only, the shadowing of options isn't effected.  */
  648. static void
  649. hol_sort (struct hol *hol)
  650. {
  651.   if (hol->num_entries > 0)
  652.     qsort (hol->entries, hol->num_entries, sizeof (struct hol_entry),
  653.    hol_entry_qcmp);
  654. }
  655. /* Append MORE to HOL, destroying MORE in the process.  Options in HOL shadow
  656.    any in MORE with the same name.  */
  657. static void
  658. hol_append (struct hol *hol, struct hol *more)
  659. {
  660.   struct hol_cluster **cl_end = &hol->clusters;
  661.   /* Steal MORE's cluster list, and add it to the end of HOL's.  */
  662.   while (*cl_end)
  663.     cl_end = &(*cl_end)->next;
  664.   *cl_end = more->clusters;
  665.   more->clusters = 0;
  666.   /* Merge entries.  */
  667.   if (more->num_entries > 0)
  668.     {
  669.       if (hol->num_entries == 0)
  670.         {
  671.           hol->num_entries = more->num_entries;
  672.           hol->entries = more->entries;
  673.           hol->short_options = more->short_options;
  674.           more->num_entries = 0; /* Mark MORE's fields as invalid.  */
  675.         }
  676.       else
  677.         /* append the entries in MORE to those in HOL, taking care to only add
  678.            non-shadowed SHORT_OPTIONS values.  */
  679.         {
  680.           unsigned left;
  681.           char *so, *more_so;
  682.           struct hol_entry *e;
  683.           unsigned num_entries = hol->num_entries + more->num_entries;
  684.           struct hol_entry *entries =
  685.             xmalloc (num_entries * sizeof (struct hol_entry));
  686.           unsigned hol_so_len = strlen (hol->short_options);
  687.           char *short_options =
  688.             xmalloc_atomic (hol_so_len + strlen (more->short_options) + 1);
  689.           
  690.           memcpy (entries, hol->entries,
  691.                   hol->num_entries * sizeof (struct hol_entry));
  692.           memcpy (entries + hol->num_entries, more->entries,
  693.                   more->num_entries * sizeof (struct hol_entry));
  694.           
  695.           memcpy (short_options, hol->short_options, hol_so_len);
  696.           
  697.           /* Fix up the short options pointers from HOL.  */
  698.           for (e = entries, left = hol->num_entries; left > 0; e++, left--)
  699.             e->short_options += (short_options - hol->short_options);
  700.           
  701.           /* Now add the short options from MORE, fixing up its entries too.  */
  702.           so = short_options + hol_so_len;
  703.           more_so = more->short_options;
  704.           for (left = more->num_entries; left > 0; e++, left--)
  705.             {
  706.               int opts_left;
  707.               const struct argp_option *opt;
  708.               
  709.               e->short_options = so;
  710.               
  711.               for (opts_left = e->num, opt = e->opt; opts_left; opt++, opts_left--)
  712.                 {
  713.                   int ch = *more_so;
  714.                   if (oshort (opt) && ch == opt->key)
  715.                     /* The next short option in MORE_SO, CH, is from OPT.  */
  716.                     {
  717.                       if (! find_char (ch, short_options,
  718.                                        short_options + hol_so_len))
  719.                         /* The short option CH isn't shadowed by HOL's options,
  720.                            so add it to the sum.  */
  721.                         *so++ = ch;
  722.                       more_so++;
  723.                     }
  724.                 }
  725.             }
  726.           
  727.           *so = '';
  728.           
  729.           xfree (hol->entries);
  730.           xfree (hol->short_options);
  731.           
  732.           hol->entries = entries;
  733.           hol->num_entries = num_entries;
  734.           hol->short_options = short_options;
  735.         }
  736.     }
  737.   hol_free (more);
  738. }
  739. /* Inserts enough spaces to make sure STREAM is at column COL.  */
  740. static void
  741. indent_to (argp_fmtstream_t stream, unsigned col)
  742. {
  743.   int needed = col - __argp_fmtstream_point (stream);
  744.   while (needed-- > 0)
  745.     __argp_fmtstream_putc (stream, ' ');
  746. }
  747. /* Output to STREAM either a space, or a newline if there isn't room for at
  748.    least ENSURE characters before the right margin.  */
  749. static void
  750. space (argp_fmtstream_t stream, size_t ensure)
  751. {
  752.   if (__argp_fmtstream_point (stream) + ensure
  753.       >= __argp_fmtstream_rmargin (stream))
  754.     __argp_fmtstream_putc (stream, 'n');
  755.   else
  756.     __argp_fmtstream_putc (stream, ' ');
  757. }
  758. /* If the option REAL has an argument, we print it in using the printf
  759.    format REQ_FMT or OPT_FMT depending on whether it's a required or
  760.    optional argument.  */
  761. static void
  762. arg (const struct argp_option *real, const char *req_fmt, const char *opt_fmt,
  763.      argp_fmtstream_t stream)
  764. {
  765.   if (real->arg)
  766.     {
  767.       if (real->flags & OPTION_ARG_OPTIONAL)
  768.         __argp_fmtstream_printf (stream, opt_fmt, gettext (real->arg));
  769.       else
  770.         __argp_fmtstream_printf (stream, req_fmt, gettext (real->arg));
  771.     }
  772. }
  773. /* Helper functions for hol_entry_help.  */
  774. /* State used during the execution of hol_help.  */
  775. struct hol_help_state
  776. {
  777.   /* PREV_ENTRY should contain the previous entry printed, or 0.  */
  778.   struct hol_entry *prev_entry;
  779.   /* If an entry is in a different group from the previous one, and SEP_GROUPS
  780.      is true, then a blank line will be printed before any output. */
  781.   int sep_groups;
  782.   /* True if a duplicate option argument was suppressed (only ever set if
  783.      UPARAMS.dup_args is false).  */
  784.   int suppressed_dup_arg;
  785. };
  786. /* Some state used while printing a help entry (used to communicate with
  787.    helper functions).  See the doc for hol_entry_help for more info, as most
  788.    of the fields are copied from its arguments.  */
  789. struct pentry_state
  790. {
  791.   const struct hol_entry *entry;
  792.   argp_fmtstream_t stream;
  793.   struct hol_help_state *hhstate;
  794.   /* True if nothing's been printed so far.  */
  795.   int first;
  796.   /* If non-zero, the state that was used to print this help.  */
  797.   const struct argp_state *state;
  798. };
  799. /* If a user doc filter should be applied to DOC, do so.  */
  800. static const char *
  801. filter_doc (const char *doc, int key, const struct argp *argp,
  802.     const struct argp_state *state)
  803. {
  804.   if (argp->help_filter)
  805.     /* We must apply a user filter to this output.  */
  806.     {
  807.       void *input = __argp_input (argp, state);
  808.       return (*argp->help_filter) (key, doc, input);
  809.     }
  810.   else
  811.     /* No filter.  */
  812.     return (char *)doc;
  813. }
  814. /* Prints STR as a header line, with the margin lines set appropiately, and
  815.    notes the fact that groups should be separated with a blank line.  ARGP is
  816.    the argp that should dictate any user doc filtering to take place.  Note
  817.    that the previous wrap margin isn't restored, but the left margin is reset
  818.    to 0.  */
  819. static void
  820. print_header (const char *str, const struct argp *argp,
  821.       struct pentry_state *pest)
  822. {
  823.   const char *tstr = gettext (str);
  824.   const char *fstr = filter_doc (tstr, ARGP_KEY_HELP_HEADER, argp, pest->state);
  825.   if (fstr)
  826.     {
  827.       if (*fstr)
  828. {
  829.   if (pest->hhstate->prev_entry)
  830.     /* Precede with a blank line.  */
  831.     __argp_fmtstream_putc (pest->stream, 'n');
  832.   indent_to (pest->stream, uparams.header_col);
  833.   __argp_fmtstream_set_lmargin (pest->stream, uparams.header_col);
  834.   __argp_fmtstream_set_wmargin (pest->stream, uparams.header_col);
  835.   __argp_fmtstream_puts (pest->stream, fstr);
  836.   __argp_fmtstream_set_lmargin (pest->stream, 0);
  837.   __argp_fmtstream_putc (pest->stream, 'n');
  838. }
  839.       pest->hhstate->sep_groups = 1; /* Separate subsequent groups. */
  840.     }
  841.   if (fstr != tstr)
  842.     xfree ((char *) fstr);
  843. }
  844. /* Inserts a comma if this isn't the first item on the line, and then makes
  845.    sure we're at least to column COL.  If this *is* the first item on a line,
  846.    prints any pending whitespace/headers that should precede this line. Also
  847.    clears FIRST.  */
  848. static void
  849. comma (unsigned col, struct pentry_state *pest)
  850. {
  851.   if (pest->first)
  852.     {
  853.       const struct hol_entry *pe = pest->hhstate->prev_entry;
  854.       const struct hol_cluster *cl = pest->entry->cluster;
  855.       if (pest->hhstate->sep_groups && pe && pest->entry->group != pe->group)
  856. __argp_fmtstream_putc (pest->stream, 'n');
  857.       if (cl && cl->header && *cl->header
  858.   && (!pe
  859.       || (pe->cluster != cl
  860.   && !hol_cluster_is_child (pe->cluster, cl))))
  861. /* If we're changing clusters, then this must be the start of the
  862.    ENTRY's cluster unless that is an ancestor of the previous one
  863.    (in which case we had just popped into a sub-cluster for a bit).
  864.    If so, then print the cluster's header line.  */
  865. {
  866.   int old_wm = __argp_fmtstream_wmargin (pest->stream);
  867.   print_header (cl->header, cl->argp, pest);
  868.   __argp_fmtstream_set_wmargin (pest->stream, old_wm);
  869. }
  870.       pest->first = 0;
  871.     }
  872.   else
  873.     __argp_fmtstream_puts (pest->stream, ", ");
  874.   indent_to (pest->stream, col);
  875. }
  876. /* Print help for ENTRY to STREAM.  */
  877. static void
  878. hol_entry_help (struct hol_entry *entry, const struct argp_state *state,
  879. argp_fmtstream_t stream, struct hol_help_state *hhstate)
  880. {
  881.   unsigned num;
  882.   const struct argp_option *real = entry->opt, *opt;
  883.   char *so = entry->short_options;
  884.   int have_long_opt = 0; /* We have any long options.  */
  885.   /* Saved margins.  */
  886.   int old_lm = __argp_fmtstream_set_lmargin (stream, 0);
  887.   int old_wm = __argp_fmtstream_wmargin (stream);
  888.   /* PEST is a state block holding some of our variables that we'd like to
  889.      share with helper functions.  */
  890.   struct pentry_state pest = { entry, stream, hhstate, 1, state };
  891.   if (! odoc (real))
  892.     for (opt = real, num = entry->num; num > 0; opt++, num--)
  893.       if (opt->name && ovisible (opt))
  894. {
  895.   have_long_opt = 1;
  896.   break;
  897. }
  898.   /* First emit short options.  */
  899.   __argp_fmtstream_set_wmargin (stream, uparams.short_opt_col); /* For truly bizarre cases. */
  900.   for (opt = real, num = entry->num; num > 0; opt++, num--)
  901.     if (oshort (opt) && opt->key == *so)
  902.       /* OPT has a valid (non shadowed) short option.  */
  903.       {
  904. if (ovisible (opt))
  905.   {
  906.     comma (uparams.short_opt_col, &pest);
  907.     __argp_fmtstream_putc (stream, '-');
  908.     __argp_fmtstream_putc (stream, *so);
  909.     if (!have_long_opt || uparams.dup_args)
  910.       arg (real, " %s", "[%s]", stream);
  911.     else if (real->arg)
  912.       hhstate->suppressed_dup_arg = 1;
  913.   }
  914. so++;
  915.       }
  916.   /* Now, long options.  */
  917.   if (odoc (real))
  918.     /* A `documentation' option.  */
  919.     {
  920.       __argp_fmtstream_set_wmargin (stream, uparams.doc_opt_col);
  921.       for (opt = real, num = entry->num; num > 0; opt++, num--)
  922. if (opt->name && ovisible (opt))
  923.   {
  924.     comma (uparams.doc_opt_col, &pest);
  925.     /* Calling gettext here isn't quite right, since sorting will
  926.        have been done on the original; but documentation options
  927.        should be pretty rare anyway...  */
  928.     __argp_fmtstream_puts (stream, gettext (opt->name));
  929.   }
  930.     }
  931.   else
  932.     /* A real long option.  */
  933.     {
  934.       int first_long_opt = 1;
  935.       __argp_fmtstream_set_wmargin (stream, uparams.long_opt_col);
  936.       for (opt = real, num = entry->num; num > 0; opt++, num--)
  937. if (opt->name && ovisible (opt))
  938.   {
  939.     comma (uparams.long_opt_col, &pest);
  940.     __argp_fmtstream_printf (stream, "--%s", opt->name);
  941.     if (first_long_opt || uparams.dup_args)
  942.       arg (real, "=%s", "[=%s]", stream);
  943.     else if (real->arg)
  944.       hhstate->suppressed_dup_arg = 1;
  945.   }
  946.     }
  947.   /* Next, documentation strings.  */
  948.   __argp_fmtstream_set_lmargin (stream, 0);
  949.   if (pest.first)
  950.     {
  951.       /* Didn't print any switches, what's up?  */
  952.       if (!oshort (real) && !real->name)
  953.         /* This is a group header, print it nicely.  */
  954.         print_header (real->doc, entry->argp, &pest);
  955.       else
  956.         /* Just a totally shadowed option or null header; print nothing.  */
  957.         goto cleanup; /* Just return, after cleaning up.  */
  958.     }
  959.   else
  960.     {
  961.       const char *tstr = real->doc ? gettext (real->doc) : 0;
  962.       const char *fstr = filter_doc (tstr, real->key, entry->argp, state);
  963.       if (fstr && *fstr)
  964. {
  965.   unsigned int col = __argp_fmtstream_point (stream);
  966.   __argp_fmtstream_set_lmargin (stream, uparams.opt_doc_col);
  967.   __argp_fmtstream_set_wmargin (stream, uparams.opt_doc_col);
  968.   if (col > (unsigned int) (uparams.opt_doc_col + 3))
  969.     __argp_fmtstream_putc (stream, 'n');
  970.   else if (col >= (unsigned int) uparams.opt_doc_col)
  971.     __argp_fmtstream_puts (stream, "   ");
  972.   else
  973.     indent_to (stream, uparams.opt_doc_col);
  974.   __argp_fmtstream_puts (stream, fstr);
  975. }
  976.       if (fstr && fstr != tstr)
  977. xfree ((char *) fstr);
  978.       /* Reset the left margin.  */
  979.       __argp_fmtstream_set_lmargin (stream, 0);
  980.       __argp_fmtstream_putc (stream, 'n');
  981.     }
  982.   hhstate->prev_entry = entry;
  983. cleanup:
  984.   __argp_fmtstream_set_lmargin (stream, old_lm);
  985.   __argp_fmtstream_set_wmargin (stream, old_wm);
  986. }
  987. /* Output a long help message about the options in HOL to STREAM.  */
  988. static void
  989. hol_help (struct hol *hol, const struct argp_state *state,
  990.   argp_fmtstream_t stream)
  991. {
  992.   unsigned num;
  993.   struct hol_entry *entry;
  994.   struct hol_help_state hhstate = { 0, 0, 0 };
  995.   for (entry = hol->entries, num = hol->num_entries; num > 0; entry++, num--)
  996.     hol_entry_help (entry, state, stream, &hhstate);
  997.   if (hhstate.suppressed_dup_arg && uparams.dup_args_note)
  998.     {
  999.       const char *tstr = _("
  1000. Mandatory or optional arguments to long options are also mandatory or 
  1001. optional for any corresponding short options.");
  1002.       const char *fstr = filter_doc (tstr, ARGP_KEY_HELP_DUP_ARGS_NOTE,
  1003.      state ? state->root_argp : 0, state);
  1004.       if (fstr && *fstr)
  1005. {
  1006.   __argp_fmtstream_putc (stream, 'n');
  1007.   __argp_fmtstream_puts (stream, fstr);
  1008.   __argp_fmtstream_putc (stream, 'n');
  1009. }
  1010.       if (fstr && fstr != tstr)
  1011. xfree ((char *) fstr);
  1012.     }
  1013. }
  1014. /* Helper functions for hol_usage.  */
  1015. /* If OPT is a short option without an arg, append its key to the string
  1016.    pointer pointer to by COOKIE, and advance the pointer.  */
  1017. static int
  1018. add_argless_short_opt (const struct argp_option *opt,
  1019.        const struct argp_option *real,
  1020.        void *cookie)
  1021. {
  1022.   char **snao_end = cookie;
  1023.   if (!(opt->arg || real->arg)
  1024.       && !((opt->flags | real->flags) & OPTION_NO_USAGE))
  1025.     *(*snao_end)++ = opt->key;
  1026.   return 0;
  1027. }
  1028. /* If OPT is a short option with an arg, output a usage entry for it to the
  1029.    stream pointed at by COOKIE.  */
  1030. static int
  1031. usage_argful_short_opt (const struct argp_option *opt,
  1032. const struct argp_option *real,
  1033. void *cookie)
  1034. {
  1035.   argp_fmtstream_t stream = cookie;
  1036.   const char *arg = opt->arg;
  1037.   int flags = opt->flags | real->flags;
  1038.   if (! arg)
  1039.     arg = real->arg;
  1040.   if (arg && !(flags & OPTION_NO_USAGE))
  1041.     {
  1042.       arg = gettext (arg);
  1043.       if (flags & OPTION_ARG_OPTIONAL)
  1044. __argp_fmtstream_printf (stream, " [-%c[%s]]", opt->key, arg);
  1045.       else
  1046. {
  1047.   /* Manually do line wrapping so that it (probably) won't
  1048.      get wrapped at the embedded space.  */
  1049.   space (stream, 6 + strlen (arg));
  1050.   __argp_fmtstream_printf (stream, "[-%c %s]", opt->key, arg);
  1051. }
  1052.     }
  1053.   return 0;
  1054. }
  1055. /* Output a usage entry for the long option opt to the stream pointed at by
  1056.    COOKIE.  */
  1057. static int
  1058. usage_long_opt (const struct argp_option *opt,
  1059. const struct argp_option *real,
  1060. void *cookie)
  1061. {
  1062.   argp_fmtstream_t stream = cookie;
  1063.   const char *arg = opt->arg;
  1064.   int flags = opt->flags | real->flags;
  1065.   if (! arg)
  1066.     arg = real->arg;
  1067.   if (! (flags & OPTION_NO_USAGE))
  1068.     {
  1069.       if (arg)
  1070.         {
  1071.           arg = gettext (arg);
  1072.           if (flags & OPTION_ARG_OPTIONAL)
  1073.             __argp_fmtstream_printf (stream, " [--%s[=%s]]", opt->name, arg);
  1074.           else
  1075.             __argp_fmtstream_printf (stream, " [--%s=%s]", opt->name, arg);
  1076.         }
  1077.       else
  1078.         __argp_fmtstream_printf (stream, " [--%s]", opt->name);
  1079.     }
  1080.       
  1081.   return 0;
  1082. }
  1083. /* Print a short usage description for the arguments in HOL to STREAM.  */
  1084. static void
  1085. hol_usage (struct hol *hol, argp_fmtstream_t stream)
  1086. {
  1087.   if (hol->num_entries > 0)
  1088.     {
  1089.       unsigned nentries;
  1090.       struct hol_entry *entry;
  1091.       char *short_no_arg_opts = alloca (strlen (hol->short_options) + 1);
  1092.       char *snao_end = short_no_arg_opts;
  1093.       /* First we put a list of short options without arguments.  */
  1094.       for (entry = hol->entries, nentries = hol->num_entries
  1095.    ; nentries > 0
  1096.    ; entry++, nentries--)
  1097. hol_entry_short_iterate (entry, add_argless_short_opt, &snao_end);
  1098.       if (snao_end > short_no_arg_opts)
  1099. {
  1100.   *snao_end++ = 0;
  1101.   __argp_fmtstream_printf (stream, " [-%s]", short_no_arg_opts);
  1102. }
  1103.       /* Now a list of short options *with* arguments.  */
  1104.       for (entry = hol->entries, nentries = hol->num_entries
  1105.    ; nentries > 0
  1106.    ; entry++, nentries--)
  1107. hol_entry_short_iterate (entry, usage_argful_short_opt, stream);
  1108.       /* Finally, a list of long options (whew!).  */
  1109.       for (entry = hol->entries, nentries = hol->num_entries
  1110.    ; nentries > 0
  1111.    ; entry++, nentries--)
  1112. hol_entry_long_iterate (entry, usage_long_opt, stream);
  1113.     }
  1114. }
  1115. /* Make a HOL containing all levels of options in ARGP.  CLUSTER is the
  1116.    cluster in which ARGP's entries should be clustered, or 0.  */
  1117. static struct hol *
  1118. argp_hol (const struct argp *argp, struct hol_cluster *cluster)
  1119. {
  1120.   const struct argp_child *child = argp->children;
  1121.   struct hol *hol = make_hol (argp, cluster);
  1122.   if (child)
  1123.     while (child->argp)
  1124.       {
  1125. struct hol_cluster *child_cluster =
  1126.   ((child->group || child->header)
  1127.    /* Put CHILD->argp within its own cluster.  */
  1128.    ? hol_add_cluster (hol, child->group, child->header,
  1129.       child - argp->children, cluster, argp)
  1130.    /* Just merge it into the parent's cluster.  */
  1131.    : cluster);
  1132. hol_append (hol, argp_hol (child->argp, child_cluster)) ;
  1133. child++;
  1134.       }
  1135.   return hol;
  1136. }
  1137. /* Calculate how many different levels with alternative args strings exist in
  1138.    ARGP.  */
  1139. static size_t
  1140. argp_args_levels (const struct argp *argp)
  1141. {
  1142.   size_t levels = 0;
  1143.   const struct argp_child *child = argp->children;
  1144.   if (argp->args_doc && strchr (argp->args_doc, 'n'))
  1145.     levels++;
  1146.   if (child)
  1147.     while (child->argp)
  1148.       levels += argp_args_levels ((child++)->argp);
  1149.   return levels;
  1150. }
  1151. /* Print all the non-option args documented in ARGP to STREAM.  Any output is
  1152.    preceded by a space.  LEVELS is a pointer to a byte vector the length
  1153.    returned by argp_args_levels; it should be initialized to zero, and
  1154.    updated by this routine for the next call if ADVANCE is true.  True is
  1155.    returned as long as there are more patterns to output.  */
  1156. static int
  1157. argp_args_usage (const struct argp *argp, const struct argp_state *state,
  1158.  char **levels, int advance, argp_fmtstream_t stream)
  1159. {
  1160.   char *our_level = *levels;
  1161.   int multiple = 0;
  1162.   const struct argp_child *child = argp->children;
  1163.   const char *tdoc = gettext (argp->args_doc), *nl = 0;
  1164.   const char *fdoc = filter_doc (tdoc, ARGP_KEY_HELP_ARGS_DOC, argp, state);
  1165.   if (fdoc)
  1166.     {
  1167.       nl = strchr (fdoc, 'n');
  1168.       if (nl)
  1169. /* This is a `multi-level' args doc; advance to the correct position
  1170.    as determined by our state in LEVELS, and update LEVELS.  */
  1171. {
  1172.   int i;
  1173.   multiple = 1;
  1174.   for (i = 0; i < *our_level; i++)
  1175.     fdoc = nl + 1, nl = strchr (fdoc, 'n');
  1176.   (*levels)++;
  1177. }
  1178.       if (! nl)
  1179. nl = fdoc + strlen (fdoc);
  1180.       /* Manually do line wrapping so that it (probably) won't get wrapped at
  1181.  any embedded spaces.  */
  1182.       space (stream, 1 + nl - fdoc);
  1183.       __argp_fmtstream_write (stream, fdoc, nl - fdoc);
  1184.     }
  1185.   if (fdoc && fdoc != tdoc)
  1186.     xfree ((char *)fdoc); /* Free user's modified doc string.  */
  1187.   if (child)
  1188.     while (child->argp)
  1189.       advance = !argp_args_usage ((child++)->argp, state, levels, advance, stream);
  1190.   if (advance && multiple)
  1191.     {
  1192.       /* Need to increment our level.  */
  1193.       if (*nl)
  1194.         /* There's more we can do here.  */
  1195.         {
  1196.           (*our_level)++;
  1197.           advance = 0; /* Our parent shouldn't advance also. */
  1198.         }
  1199.       else if (*our_level > 0)
  1200.         /* We had multiple levels, but used them up; reset to zero.  */
  1201.         *our_level = 0;
  1202.     }
  1203.   return !advance;
  1204. }
  1205. /* Print the documentation for ARGP to STREAM; if POST is false, then
  1206.    everything preceeding a `v' character in the documentation strings (or
  1207.    the whole string, for those with none) is printed, otherwise, everything
  1208.    following the `v' character (nothing for strings without).  Each separate
  1209.    bit of documentation is separated a blank line, and if PRE_BLANK is true,
  1210.    then the first is as well.  If FIRST_ONLY is true, only the first
  1211.    occurance is output.  Returns true if anything was output.  */
  1212. static int
  1213. argp_doc (const struct argp *argp, const struct argp_state *state,
  1214.   int post, int pre_blank, int first_only,
  1215.   argp_fmtstream_t stream)
  1216. {
  1217.   const char *text;
  1218.   const char *inp_text;
  1219.   void *input = 0;
  1220.   int anything = 0;
  1221.   size_t inp_text_limit = 0;
  1222.   const char *doc = gettext (argp->doc);
  1223.   const struct argp_child *child = argp->children;
  1224.   if (doc)
  1225.     {
  1226.       const char *vt = strchr (doc, 'v');
  1227.       inp_text = post ? (vt ? vt + 1 : 0) : doc;
  1228.       inp_text_limit = (!post && vt) ? (vt - doc) : 0;
  1229.     }
  1230.   else
  1231.     inp_text = 0;
  1232.   if (argp->help_filter)
  1233.     /* We have to filter the doc strings.  */
  1234.     {
  1235.       if (inp_text_limit)
  1236. /* Copy INP_TEXT so that it's nul-terminated.  */
  1237. inp_text = strndup (inp_text, inp_text_limit);
  1238.       input = __argp_input (argp, state);
  1239.       text =
  1240. (*argp->help_filter) (post
  1241.       ? ARGP_KEY_HELP_POST_DOC
  1242.       : ARGP_KEY_HELP_PRE_DOC,
  1243.       inp_text, input);
  1244.     }
  1245.   else
  1246.     text = (const char *) inp_text;
  1247.   if (text)
  1248.     {
  1249.       if (pre_blank)
  1250. __argp_fmtstream_putc (stream, 'n');
  1251.       if (text == inp_text && inp_text_limit)
  1252. __argp_fmtstream_write (stream, inp_text, inp_text_limit);
  1253.       else
  1254. __argp_fmtstream_puts (stream, text);
  1255.       if (__argp_fmtstream_point (stream) > __argp_fmtstream_lmargin (stream))
  1256. __argp_fmtstream_putc (stream, 'n');
  1257.       anything = 1;
  1258.     }
  1259.   if (text && text != inp_text)
  1260.     xfree ((char *) text); /* Free TEXT returned from the help filter.  */
  1261.   if (inp_text && inp_text_limit && argp->help_filter)
  1262.     xfree ((char *) inp_text); /* We copied INP_TEXT, so free it now.  */
  1263.   if (post && argp->help_filter)
  1264.     /* Now see if we have to output a ARGP_KEY_HELP_EXTRA text.  */
  1265.     {
  1266.       text = (*argp->help_filter) (ARGP_KEY_HELP_EXTRA, 0, input);
  1267.       if (text)
  1268. {
  1269.   if (anything || pre_blank)
  1270.     __argp_fmtstream_putc (stream, 'n');
  1271.   __argp_fmtstream_puts (stream, text);
  1272.   xfree ((char *) text);
  1273.   if (__argp_fmtstream_point (stream)
  1274.       > __argp_fmtstream_lmargin (stream))
  1275.     __argp_fmtstream_putc (stream, 'n');
  1276.   anything = 1;
  1277. }
  1278.     }
  1279.   if (child)
  1280.     while (child->argp && !(first_only && anything))
  1281.       anything |=
  1282. argp_doc ((child++)->argp, state,
  1283.   post, anything || pre_blank, first_only,
  1284.   stream);
  1285.   return anything;
  1286. }
  1287. /* Output a usage message for ARGP to STREAM.  If called from
  1288.    argp_state_help, STATE is the relevent parsing state.  FLAGS are from the
  1289.    set ARGP_HELP_*.  NAME is what to use wherever a `program name' is
  1290.    needed. */
  1291. static void
  1292. _help (const struct argp *argp, const struct argp_state *state, FILE *stream,
  1293.        unsigned flags, const char *name)
  1294. {
  1295.   int anything = 0; /* Whether we've output anything.  */
  1296.   struct hol *hol = 0;
  1297.   argp_fmtstream_t fs;
  1298.   if (! stream)
  1299.     return;
  1300.   if (! uparams.valid)
  1301.     fill_in_uparams (state);
  1302.   fs = __argp_make_fmtstream (stream, 0, uparams.rmargin, 0);
  1303.   if (! fs)
  1304.     return;
  1305.   if (flags & (ARGP_HELP_USAGE | ARGP_HELP_SHORT_USAGE | ARGP_HELP_LONG))
  1306.     {
  1307.       hol = argp_hol (argp, 0);
  1308.       /* If present, these options always come last.  */
  1309.       hol_set_group (hol, "help", -1);
  1310.       hol_set_group (hol, "version", -1);
  1311.       hol_sort (hol);
  1312.     }
  1313.   if (flags & (ARGP_HELP_USAGE | ARGP_HELP_SHORT_USAGE))
  1314.     /* Print a short `Usage:' message.  */
  1315.     {
  1316.       int first_pattern = 1, more_patterns;
  1317.       size_t num_pattern_levels = argp_args_levels (argp);
  1318.       char *pattern_levels = alloca (num_pattern_levels);
  1319.       memset (pattern_levels, 0, num_pattern_levels);
  1320.       do
  1321. {
  1322.   int old_lm;
  1323.   int old_wm = __argp_fmtstream_set_wmargin (fs, uparams.usage_indent);
  1324.   char *levels = pattern_levels;
  1325.   __argp_fmtstream_printf (fs, "%s %s",
  1326.    _(first_pattern ? "Usage:" : "  or: "),
  1327.    name);
  1328.   /* We set the lmargin as well as the wmargin, because hol_usage
  1329.      manually wraps options with newline to avoid annoying breaks.  */
  1330.   old_lm = __argp_fmtstream_set_lmargin (fs, uparams.usage_indent);
  1331.   if (flags & ARGP_HELP_SHORT_USAGE)
  1332.     /* Just show where the options go.  */
  1333.     {
  1334.       if (hol->num_entries > 0)
  1335. __argp_fmtstream_puts (fs, _(" [OPTION...]"));
  1336.     }
  1337.   else
  1338.     /* Actually print the options.  */
  1339.     {
  1340.       hol_usage (hol, fs);
  1341.       flags |= ARGP_HELP_SHORT_USAGE; /* But only do so once.  */
  1342.     }
  1343.   more_patterns = argp_args_usage (argp, state, &levels, 1, fs);
  1344.   __argp_fmtstream_set_wmargin (fs, old_wm);
  1345.   __argp_fmtstream_set_lmargin (fs, old_lm);
  1346.   __argp_fmtstream_putc (fs, 'n');
  1347.   anything = 1;
  1348.   first_pattern = 0;
  1349. }
  1350.       while (more_patterns);
  1351.     }
  1352.   if (flags & ARGP_HELP_PRE_DOC)
  1353.     anything |= argp_doc (argp, state, 0, 0, 1, fs);
  1354.   if (flags & ARGP_HELP_SEE)
  1355.     {
  1356.       __argp_fmtstream_printf (fs, _("
  1357. Try `%s --help' or `%s --usage' for more information.n"),
  1358.        name, name);
  1359.       anything = 1;
  1360.     }
  1361.   if (flags & ARGP_HELP_LONG)
  1362.     /* Print a long, detailed help message.  */
  1363.     {
  1364.       /* Print info about all the options.  */
  1365.       if (hol->num_entries > 0)
  1366. {
  1367.   if (anything)
  1368.     __argp_fmtstream_putc (fs, 'n');
  1369.   hol_help (hol, state, fs);
  1370.   anything = 1;
  1371. }
  1372.     }
  1373.   if (flags & ARGP_HELP_POST_DOC)
  1374.     /* Print any documentation strings at the end.  */
  1375.     anything |= argp_doc (argp, state, 1, anything, 0, fs);
  1376.   if ((flags & ARGP_HELP_BUG_ADDR) && argp_program_bug_address)
  1377.     {
  1378.       if (anything)
  1379. __argp_fmtstream_putc (fs, 'n');
  1380.       __argp_fmtstream_printf (fs, _("Report bugs to %s.n"),
  1381.          argp_program_bug_address);
  1382.       anything = 1;
  1383.     }
  1384.   if (hol)
  1385.     hol_free (hol);
  1386.   __argp_fmtstream_free (fs);
  1387. }
  1388. /* Output a usage message for ARGP to STREAM.  FLAGS are from the set
  1389.    ARGP_HELP_*.  NAME is what to use wherever a `program name' is needed. */
  1390. void __argp_help (const struct argp *argp, FILE *stream,
  1391.   unsigned flags, char *name)
  1392. {
  1393.   _help (argp, 0, stream, flags, name);
  1394. }
  1395. #ifdef weak_alias
  1396. weak_alias (__argp_help, argp_help)
  1397. #endif
  1398. /* Output, if appropriate, a usage message for STATE to STREAM.  FLAGS are
  1399.    from the set ARGP_HELP_*.  */
  1400. void
  1401. __argp_state_help (const struct argp_state *state, FILE *stream, unsigned flags)
  1402. {
  1403.   if ((!state || ! (state->flags & ARGP_NO_ERRS)) && stream)
  1404.     {
  1405.       if (state && (state->flags & ARGP_LONG_ONLY))
  1406. flags |= ARGP_HELP_LONG_ONLY;
  1407.       _help (state ? state->root_argp : 0, state, stream, flags,
  1408.      state ? state->name : program_invocation_short_name);
  1409.       if (!state || ! (state->flags & ARGP_NO_EXIT))
  1410. {
  1411.   if (flags & ARGP_HELP_EXIT_ERR)
  1412.     exit (argp_err_exit_status);
  1413.   if (flags & ARGP_HELP_EXIT_OK)
  1414.     exit (0);
  1415. }
  1416.   }
  1417. }
  1418. #ifdef weak_alias
  1419. weak_alias (__argp_state_help, argp_state_help)
  1420. #endif
  1421. /* If appropriate, print the printf string FMT and following args, preceded
  1422.    by the program name and `:', to stderr, and followed by a `Try ... --help'
  1423.    message, then exit (1).  */
  1424. void
  1425. __argp_error (const struct argp_state *state, const char *fmt, ...)
  1426. {
  1427.   if (!state || !(state->flags & ARGP_NO_ERRS))
  1428.     {
  1429.       FILE *stream = state ? state->err_stream : stderr;
  1430.       if (stream)
  1431. {
  1432.   va_list ap;
  1433.   fputs (state ? state->name : program_invocation_short_name, stream);
  1434.   putc (':', stream);
  1435.   putc (' ', stream);
  1436.   va_start (ap, fmt);
  1437.   vfprintf (stream, fmt, ap);
  1438.   va_end (ap);
  1439.   putc ('n', stream);
  1440.   __argp_state_help (state, stream, ARGP_HELP_STD_ERR);
  1441. }
  1442.     }
  1443. }
  1444. #ifdef weak_alias
  1445. weak_alias (__argp_error, argp_error)
  1446. #endif
  1447. /* Similar to the standard gnu error-reporting function error(), but will
  1448.    respect the ARGP_NO_EXIT and ARGP_NO_ERRS flags in STATE, and will print
  1449.    to STATE->err_stream.  This is useful for argument parsing code that is
  1450.    shared between program startup (when exiting is desired) and runtime
  1451.    option parsing (when typically an error code is returned instead).  The
  1452.    difference between this function and argp_error is that the latter is for
  1453.    *parsing errors*, and the former is for other problems that occur during
  1454.    parsing but don't reflect a (syntactic) problem with the input.  */
  1455. void
  1456. __argp_failure (const struct argp_state *state, int status, int errnum,
  1457. const char *fmt, ...)
  1458. {
  1459.   if (!state || !(state->flags & ARGP_NO_ERRS))
  1460.     {
  1461.       FILE *stream = state ? state->err_stream : stderr;
  1462.       if (stream)
  1463. {
  1464.   fputs (state ? state->name : program_invocation_short_name, stream);
  1465.   if (fmt)
  1466.     {
  1467.       va_list ap;
  1468.       putc (':', stream);
  1469.       putc (' ', stream);
  1470.       va_start (ap, fmt);
  1471.       vfprintf (stream, fmt, ap);
  1472.       va_end (ap);
  1473.     }
  1474.   if (errnum)
  1475.     {
  1476.       putc (':', stream);
  1477.       putc (' ', stream);
  1478.       fputs (strerror (errnum), stream);
  1479.     }
  1480.   putc ('n', stream);
  1481.   if (status && (!state || !(state->flags & ARGP_NO_EXIT)))
  1482.     exit (status);
  1483. }
  1484.     }
  1485. }
  1486. #ifdef weak_alias
  1487. weak_alias (__argp_failure, argp_failure)
  1488. #endif