argp-help.c 62.4 KB
Newer Older
Paul Eggert's avatar
Paul Eggert committed
1
/* Hierarchical argument parsing help output
Paul Eggert's avatar
Paul Eggert committed
2
   Copyright (C) 1995-2005, 2007, 2009-2016 Free Software Foundation, Inc.
3 4 5
   This file is part of the GNU C Library.
   Written by Miles Bader <miles@gnu.ai.mit.edu>.

6
   This program is free software: you can redistribute it and/or modify
Paul Eggert's avatar
Paul Eggert committed
7
   it under the terms of the GNU General Public License as published by
8 9
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.
10

Paul Eggert's avatar
Paul Eggert committed
11
   This program is distributed in the hope that it will be useful,
12
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Paul Eggert's avatar
Paul Eggert committed
13 14
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
15

16 17
   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18 19

#ifndef _GNU_SOURCE
20
# define _GNU_SOURCE    1
21 22 23
#endif

#ifdef HAVE_CONFIG_H
24
# include <config.h>
25 26
#endif

27
#include <alloca.h>
28
#include <errno.h>
29 30 31
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
32
#include <strings.h>
33 34 35
#include <assert.h>
#include <stdarg.h>
#include <ctype.h>
Karl Berry's avatar
Karl Berry committed
36
#include <limits.h>
37 38 39 40
#ifdef USE_IN_LIBIO
# include <wchar.h>
#endif

41 42 43 44 45 46 47
#ifdef _LIBC
# include <libintl.h>
# undef dgettext
# define dgettext(domain, msgid) \
   INTUSE(__dcgettext) (domain, msgid, LC_MESSAGES)
#else
# include "gettext.h"
Karl Berry's avatar
Karl Berry committed
48 49
#endif

50 51 52
#include "argp.h"
#include "argp-fmtstream.h"
#include "argp-namefrob.h"
Karl Berry's avatar
Karl Berry committed
53 54 55

#ifndef SIZE_MAX
# define SIZE_MAX ((size_t) -1)
Karl Berry's avatar
Karl Berry committed
56
#endif
57 58 59

/* User-selectable (using an environment variable) formatting parameters.

60
   These may be specified in an environment variable called 'ARGP_HELP_FMT',
61 62 63 64 65
   with a contents like:  VAR1=VAL1,VAR2=VAL2,BOOLVAR2,no-BOOLVAR2
   Where VALn must be a positive integer.  The list of variables is in the
   UPARAM_NAMES vector, below.  */

/* Default parameters.  */
66 67 68 69 70 71 72 73 74
#define DUP_ARGS      0         /* True if option argument can be duplicated. */
#define DUP_ARGS_NOTE 1         /* True to print a note about duplicate args. */
#define SHORT_OPT_COL 2         /* column in which short options start */
#define LONG_OPT_COL  6         /* column in which long options start */
#define DOC_OPT_COL   2         /* column in which doc options start */
#define OPT_DOC_COL  29         /* column in which option text starts */
#define HEADER_COL    1         /* column in which group headers are printed */
#define USAGE_INDENT 12         /* indentation of wrapped usage lines */
#define RMARGIN      79         /* right margin used for wrapping */
75 76

/* User-selectable (using an environment variable) formatting parameters.
77
   They must all be of type 'int' for the parsing code to work.  */
78 79 80
struct uparams
{
  /* If true, arguments for an option are shown with both short and long
81
     options, even when a given option has both, e.g. '-x ARG, --longx=ARG'.
82
     If false, then if an option has both, the argument is only shown with
83
     the long one, e.g., '-x, --longx=ARG', and a message indicating that
84 85 86 87 88 89 90 91
     this really means both is printed below the options.  */
  int dup_args;

  /* This is true if when DUP_ARGS is false, and some duplicate arguments have
     been suppressed, an explanatory message should be printed.  */
  int dup_args_note;

  /* Various output columns.  */
Jim Meyering's avatar
Jim Meyering committed
92 93
  int short_opt_col;      /* column in which short options start */
  int long_opt_col;       /* column in which long options start */
94 95
  int doc_opt_col;        /* column in which doc options start */
  int opt_doc_col;        /* column in which option text starts */
Jim Meyering's avatar
Jim Meyering committed
96
  int header_col;         /* column in which group headers are printed */
97 98 99
  int usage_indent;       /* indentation of wrapped usage lines */
  int rmargin;            /* right margin used for wrapping */

100
  int valid;              /* True when the values in here are valid.  */
101 102 103 104 105 106 107 108 109 110 111 112 113
};

/* This is a global variable, as user options are only ever read once.  */
static struct uparams uparams = {
  DUP_ARGS, DUP_ARGS_NOTE,
  SHORT_OPT_COL, LONG_OPT_COL, DOC_OPT_COL, OPT_DOC_COL, HEADER_COL,
  USAGE_INDENT, RMARGIN,
  0
};

/* A particular uparam, and what the user name is.  */
struct uparam_name
{
114
  const char *name;             /* User name.  */
115
  int is_bool;                  /* Whether it's 'boolean'.  */
116
  size_t uparams_offs;          /* Location of the (int) field in UPARAMS.  */
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
};

/* The name-field mappings we know about.  */
static const struct uparam_name uparam_names[] =
{
  { "dup-args",       1, offsetof (struct uparams, dup_args) },
  { "dup-args-note",  1, offsetof (struct uparams, dup_args_note) },
  { "short-opt-col",  0, offsetof (struct uparams, short_opt_col) },
  { "long-opt-col",   0, offsetof (struct uparams, long_opt_col) },
  { "doc-opt-col",    0, offsetof (struct uparams, doc_opt_col) },
  { "opt-doc-col",    0, offsetof (struct uparams, opt_doc_col) },
  { "header-col",     0, offsetof (struct uparams, header_col) },
  { "usage-indent",   0, offsetof (struct uparams, usage_indent) },
  { "rmargin",        0, offsetof (struct uparams, rmargin) },
  { 0 }
};

134 135 136 137 138 139 140 141
static void
validate_uparams (const struct argp_state *state, struct uparams *upptr)
{
  const struct uparam_name *up;

  for (up = uparam_names; up->name; up++)
    {
      if (up->is_bool
142 143
          || up->uparams_offs == offsetof (struct uparams, rmargin))
        continue;
144
      if (*(int *)((char *)upptr + up->uparams_offs) >= upptr->rmargin)
145 146 147 148
        {
          __argp_failure (state, 0, 0,
                          dgettext (state->root_argp->argp_domain,
                                    "\
149
ARGP_HELP_FMT: %s value is less than or equal to %s"),
150 151 152
                          "rmargin", up->name);
          return;
        }
153 154 155 156 157
    }
  uparams = *upptr;
  uparams.valid = 1;
}

Paul Eggert's avatar
Paul Eggert committed
158
/* Read user options from the environment, and fill in UPARAMS appropriately. */
159 160 161 162
static void
fill_in_uparams (const struct argp_state *state)
{
  const char *var = getenv ("ARGP_HELP_FMT");
163
  struct uparams new_params = uparams;
Jim Meyering's avatar
Jim Meyering committed
164

165
#define SKIPWS(p) do { while (isspace ((unsigned char) *p)) p++; } while (0);
166 167

  if (var)
168 169 170
    {
      /* Parse var. */
      while (*var)
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
        {
          SKIPWS (var);

          if (isalpha ((unsigned char) *var))
            {
              size_t var_len;
              const struct uparam_name *un;
              int unspec = 0, val = 0;
              const char *arg = var;

              while (isalnum ((unsigned char) *arg) || *arg == '-' || *arg == '_')
                arg++;
              var_len = arg - var;

              SKIPWS (arg);

              if (*arg == '\0' || *arg == ',')
                unspec = 1;
              else if (*arg == '=')
                {
                  arg++;
                  SKIPWS (arg);
                }

              if (unspec)
                {
                  if (var[0] == 'n' && var[1] == 'o' && var[2] == '-')
                    {
                      val = 0;
                      var += 3;
                      var_len -= 3;
                    }
                  else
                    val = 1;
                }
              else if (isdigit ((unsigned char) *arg))
                {
                  val = atoi (arg);
                  while (isdigit ((unsigned char) *arg))
                    arg++;
                  SKIPWS (arg);
                }

              for (un = uparam_names; un->name; un++)
                if (strlen (un->name) == var_len
                    && strncmp (var, un->name, var_len) == 0)
                  {
                    if (unspec && !un->is_bool)
                      __argp_failure (state, 0, 0,
                                      dgettext (state->root_argp->argp_domain,
                                                "\
222
%.*s: ARGP_HELP_FMT parameter requires a value"),
223 224 225 226 227
                                      (int) var_len, var);
                    else if (val < 0)
                      __argp_failure (state, 0, 0,
                                      dgettext (state->root_argp->argp_domain,
                                                "\
228
%.*s: ARGP_HELP_FMT parameter must be positive"),
229 230 231 232 233 234 235 236
                                      (int) var_len, var);
                    else
                      *(int *)((char *)&new_params + un->uparams_offs) = val;
                    break;
                  }
              if (! un->name)
                __argp_failure (state, 0, 0,
                                dgettext (state->root_argp->argp_domain, "\
237
%.*s: Unknown ARGP_HELP_FMT parameter"),
238 239 240 241 242 243 244 245 246 247 248 249 250 251
                                (int) var_len, var);

              var = arg;
              if (*var == ',')
                var++;
            }
          else if (*var)
            {
              __argp_failure (state, 0, 0,
                              dgettext (state->root_argp->argp_domain,
                                        "Garbage in ARGP_HELP_FMT: %s"), var);
              break;
            }
        }
252 253
      validate_uparams (state, &new_params);
    }
254 255 256 257 258 259 260 261 262
}

/* Returns true if OPT hasn't been marked invisible.  Visibility only affects
   whether OPT is displayed or used in sorting, not option shadowing.  */
#define ovisible(opt) (! ((opt)->flags & OPTION_HIDDEN))

/* Returns true if OPT is an alias for an earlier option.  */
#define oalias(opt) ((opt)->flags & OPTION_ALIAS)

263
/* Returns true if OPT is a documentation-only entry.  */
264 265
#define odoc(opt) ((opt)->flags & OPTION_DOC)

266 267 268
/* Returns true if OPT should not be translated */
#define onotrans(opt) ((opt)->flags & OPTION_NO_TRANS)

269 270 271 272 273 274 275 276 277 278 279 280
/* Returns true if OPT is the end-of-list marker for a list of options.  */
#define oend(opt) __option_is_end (opt)

/* Returns true if OPT has a short option.  */
#define oshort(opt) __option_is_short (opt)

/*
   The help format for a particular option is like:

     -xARG, -yARG, --long1=ARG, --long2=ARG        Documentation...

   Where ARG will be omitted if there's no argument, for this option, or
Paul Eggert's avatar
Paul Eggert committed
281 282
   will be surrounded by "[" and "]" appropriately if the argument is
   optional.  The documentation string is word-wrapped appropriately, and if
283 284
   the list of options is long enough, it will be started on a separate line.
   If there are no short options for a given option, the first long option is
Paul Eggert's avatar
Paul Eggert committed
285
   indented slightly in a way that's supposed to make most long options appear
286 287 288 289 290
   to be in a separate column.

   For example, the following output (from ps):

     -p PID, --pid=PID          List the process PID
291
         --pgrp=PGRP            List processes in the process group PGRP
292 293
     -P, -x, --no-parent        Include processes without parents
     -Q, --all-fields           Don't elide unusable fields (normally if there's
294 295
                                some reason ps can't print a field for any
                                process, it's removed from the output entirely)
296
     -r, --reverse, --gratuitously-long-reverse-option
297 298 299
                                Reverse the order of any sort
         --session[=SID]        Add the processes from the session SID (which
                                defaults to the sid of the current process)
300 301 302 303 304 305

    Here are some more options:
     -f ZOT, --foonly=ZOT       Glork a foonly
     -z, --zaza                 Snit a zar

     -?, --help                 Give this help list
306
         --usage                Give a short usage message
307 308 309 310 311 312 313
     -V, --version              Print program version

   The struct argp_option array for the above could look like:

   {
     {"pid",       'p',      "PID",  0, "List the process PID"},
     {"pgrp",      OPT_PGRP, "PGRP", 0, "List processes in the process group PGRP"},
314
     {"no-parent", 'P',       0,     0, "Include processes without parents"},
315 316
     {0,           'x',       0,     OPTION_ALIAS},
     {"all-fields",'Q',       0,     0, "Don't elide unusable fields (normally"
317
                                        " if there's some reason ps can't"
318
                                        " print a field for any process, it's"
319
                                        " removed from the output entirely)" },
320 321 322
     {"reverse",   'r',       0,     0, "Reverse the order of any sort"},
     {"gratuitously-long-reverse-option", 0, 0, OPTION_ALIAS},
     {"session",   OPT_SESS,  "SID", OPTION_ARG_OPTIONAL,
323
                                        "Add the processes from the session"
324 325
                                        " SID (which defaults to the sid of"
                                        " the current process)" },
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350

     {0,0,0,0, "Here are some more options:"},
     {"foonly", 'f', "ZOT", 0, "Glork a foonly"},
     {"zaza", 'z', 0, 0, "Snit a zar"},

     {0}
   }

   Note that the last three options are automatically supplied by argp_parse,
   unless you tell it not to with ARGP_NO_HELP.

*/

/* Returns true if CH occurs between BEG and END.  */
static int
find_char (char ch, char *beg, char *end)
{
  while (beg < end)
    if (*beg == ch)
      return 1;
    else
      beg++;
  return 0;
}

351
struct hol_cluster;             /* fwd decl */
352 353 354 355 356 357 358 359 360 361 362

struct hol_entry
{
  /* First option.  */
  const struct argp_option *opt;
  /* Number of options (including aliases).  */
  unsigned num;

  /* A pointers into the HOL's short_options field, to the first short option
     letter for this entry.  The order of the characters following this point
     corresponds to the order of options pointed to by OPT, and there are at
363
     most NUM.  A short option recorded in an option following OPT is only
364 365 366 367 368 369 370 371 372 373 374 375 376 377
     valid if it occurs in the right place in SHORT_OPTIONS (otherwise it's
     probably been shadowed by some other entry).  */
  char *short_options;

  /* Entries are sorted by their group first, in the order:
       1, 2, ..., n, 0, -m, ..., -2, -1
     and then alphabetically within each group.  The default is 0.  */
  int group;

  /* The cluster of options this entry belongs to, or 0 if none.  */
  struct hol_cluster *cluster;

  /* The argp from which this option came.  */
  const struct argp *argp;
378 379 380

  /* Position in the array */
  unsigned ord;
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
};

/* A cluster of entries to reflect the argp tree structure.  */
struct hol_cluster
{
  /* A descriptive header printed before options in this cluster.  */
  const char *header;

  /* Used to order clusters within the same group with the same parent,
     according to the order in which they occurred in the parent argp's child
     list.  */
  int index;

  /* How to sort this cluster with respect to options and other clusters at the
     same depth (clusters always follow options in the same group).  */
  int group;

  /* The cluster to which this cluster belongs, or 0 if it's at the base
     level.  */
  struct hol_cluster *parent;

  /* The argp from which this cluster is (eventually) derived.  */
  const struct argp *argp;

  /* The distance this cluster is from the root.  */
  int depth;

  /* Clusters in a given hol are kept in a linked list, to make freeing them
     possible.  */
  struct hol_cluster *next;
};

/* A list of options for help.  */
struct hol
{
  /* An array of hol_entry's.  */
  struct hol_entry *entries;
  /* The number of entries in this hol.  If this field is zero, the others
     are undefined.  */
  unsigned num_entries;

  /* A string containing all short options in this HOL.  Each entry contains
     pointers into this string, so the order can't be messed with blindly.  */
  char *short_options;

  /* Clusters of entries in this hol.  */
  struct hol_cluster *clusters;
};

/* Create a struct hol from the options in ARGP.  CLUSTER is the
   hol_cluster in which these entries occur, or 0, if at the root.  */
static struct hol *
make_hol (const struct argp *argp, struct hol_cluster *cluster)
{
  char *so;
  const struct argp_option *o;
  const struct argp_option *opts = argp->options;
  struct hol_entry *entry;
  unsigned num_short_options = 0;
  struct hol *hol = malloc (sizeof (struct hol));

  assert (hol);

  hol->num_entries = 0;
  hol->clusters = 0;

  if (opts)
    {
      int cur_group = 0;

      /* The first option must not be an alias.  */
      assert (! oalias (opts));

      /* Calculate the space needed.  */
      for (o = opts; ! oend (o); o++)
456 457 458 459 460 461
        {
          if (! oalias (o))
            hol->num_entries++;
          if (oshort (o))
            num_short_options++;        /* This is an upper bound.  */
        }
462 463 464 465

      hol->entries = malloc (sizeof (struct hol_entry) * hol->num_entries);
      hol->short_options = malloc (num_short_options + 1);

Karl Berry's avatar
Karl Berry committed
466
      assert (hol->entries && hol->short_options);
467
      if (SIZE_MAX <= UINT_MAX)
468
        assert (hol->num_entries <= SIZE_MAX / sizeof (struct hol_entry));
469 470 471 472

      /* Fill in the entries.  */
      so = hol->short_options;
      for (o = opts, entry = hol->entries; ! oend (o); entry++)
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
        {
          entry->opt = o;
          entry->num = 0;
          entry->short_options = so;
          entry->group = cur_group =
            o->group
            ? o->group
            : ((!o->name && !o->key)
               ? cur_group + 1
               : cur_group);
          entry->cluster = cluster;
          entry->argp = argp;

          do
            {
              entry->num++;
              if (oshort (o) && ! find_char (o->key, hol->short_options, so))
                /* O has a valid short option which hasn't already been used.*/
                *so++ = o->key;
              o++;
            }
          while (! oend (o) && oalias (o));
        }
      *so = '\0';               /* null terminated so we can find the length */
497 498 499 500 501 502 503 504 505 506
    }

  return hol;
}

/* Add a new cluster to HOL, with the given GROUP and HEADER (taken from the
   associated argp child list entry), INDEX, and PARENT, and return a pointer
   to it.  ARGP is the argp that this cluster results from.  */
static struct hol_cluster *
hol_add_cluster (struct hol *hol, int group, const char *header, int index,
507
                 struct hol_cluster *parent, const struct argp *argp)
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
{
  struct hol_cluster *cl = malloc (sizeof (struct hol_cluster));
  if (cl)
    {
      cl->group = group;
      cl->header = header;

      cl->index = index;
      cl->parent = parent;
      cl->argp = argp;
      cl->depth = parent ? parent->depth + 1 : 0;

      cl->next = hol->clusters;
      hol->clusters = cl;
    }
  return cl;
}

/* Free HOL and any resources it uses.  */
static void
hol_free (struct hol *hol)
{
  struct hol_cluster *cl = hol->clusters;

  while (cl)
    {
      struct hol_cluster *next = cl->next;
      free (cl);
      cl = next;
    }

  if (hol->num_entries > 0)
    {
      free (hol->entries);
      free (hol->short_options);
    }

  free (hol);
}

Paul Eggert's avatar
Paul Eggert committed
548
static int
549
hol_entry_short_iterate (const struct hol_entry *entry,
550 551 552 553
                         int (*func)(const struct argp_option *opt,
                                     const struct argp_option *real,
                                     const char *domain, void *cookie),
                         const char *domain, void *cookie)
554 555 556 557 558 559 560 561 562
{
  unsigned nopts;
  int val = 0;
  const struct argp_option *opt, *real = entry->opt;
  char *so = entry->short_options;

  for (opt = real, nopts = entry->num; nopts > 0 && !val; opt++, nopts--)
    if (oshort (opt) && *so == opt->key)
      {
563 564 565 566 567
        if (!oalias (opt))
          real = opt;
        if (ovisible (opt))
          val = (*func)(opt, real, domain, cookie);
        so++;
568 569 570 571 572 573
      }

  return val;
}

static inline int
574
#if __GNUC__ >= 3
Karl Berry's avatar
Karl Berry committed
575
__attribute__ ((always_inline))
576
#endif
577
hol_entry_long_iterate (const struct hol_entry *entry,
578 579 580 581
                        int (*func)(const struct argp_option *opt,
                                    const struct argp_option *real,
                                    const char *domain, void *cookie),
                        const char *domain, void *cookie)
582 583 584 585 586 587 588 589
{
  unsigned nopts;
  int val = 0;
  const struct argp_option *opt, *real = entry->opt;

  for (opt = real, nopts = entry->num; nopts > 0 && !val; opt++, nopts--)
    if (opt->name)
      {
590 591 592 593
        if (!oalias (opt))
          real = opt;
        if (ovisible (opt))
          val = (*func)(opt, real, domain, cookie);
594 595 596 597 598 599
      }

  return val;
}

/* Iterator that returns true for the first short option.  */
600
static int
601
until_short (const struct argp_option *opt, const struct argp_option *real,
602
             const char *domain, void *cookie)
603 604 605 606 607 608 609 610 611
{
  return oshort (opt) ? opt->key : 0;
}

/* Returns the first valid short option in ENTRY, or 0 if there is none.  */
static char
hol_entry_first_short (const struct hol_entry *entry)
{
  return hol_entry_short_iterate (entry, until_short,
612
                                  entry->argp->argp_domain, 0);
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
}

/* Returns the first valid long option in ENTRY, or 0 if there is none.  */
static const char *
hol_entry_first_long (const struct hol_entry *entry)
{
  const struct argp_option *opt;
  unsigned num;
  for (opt = entry->opt, num = entry->num; num > 0; opt++, num--)
    if (opt->name && ovisible (opt))
      return opt->name;
  return 0;
}

/* Returns the entry in HOL with the long option name NAME, or 0 if there is
   none.  */
static struct hol_entry *
hol_find_entry (struct hol *hol, const char *name)
{
  struct hol_entry *entry = hol->entries;
  unsigned num_entries = hol->num_entries;

  while (num_entries-- > 0)
    {
      const struct argp_option *opt = entry->opt;
      unsigned num_opts = entry->num;

      while (num_opts-- > 0)
641 642 643 644
        if (opt->name && ovisible (opt) && strcmp (opt->name, name) == 0)
          return entry;
        else
          opt++;
645 646 647 648 649 650 651

      entry++;
    }

  return 0;
}

Alexandre Duret-Lutz's avatar
Alexandre Duret-Lutz committed
652
/* If an entry with the long option NAME occurs in HOL, set its special
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
   sort position to GROUP.  */
static void
hol_set_group (struct hol *hol, const char *name, int group)
{
  struct hol_entry *entry = hol_find_entry (hol, name);
  if (entry)
    entry->group = group;
}

/* Order by group:  0, 1, 2, ..., n, -m, ..., -2, -1.
   EQ is what to return if GROUP1 and GROUP2 are the same.  */
static int
group_cmp (int group1, int group2, int eq)
{
  if (group1 == group2)
    return eq;
  else if ((group1 < 0 && group2 < 0) || (group1 >= 0 && group2 >= 0))
    return group1 - group2;
  else
    return group2 - group1;
}

/* Compare clusters CL1 & CL2 by the order that they should appear in
   output.  */
static int
hol_cluster_cmp (const struct hol_cluster *cl1, const struct hol_cluster *cl2)
{
  /* If one cluster is deeper than the other, use its ancestor at the same
681
     level, so that finding the common ancestor is straightforward.
Jim Meyering's avatar
Jim Meyering committed
682

683 684
     clN->depth > 0 means that clN->parent != NULL (see hol_add_cluster) */
  while (cl1->depth > cl2->depth)
685
    cl1 = cl1->parent;
686
  while (cl2->depth > cl1->depth)
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
    cl2 = cl2->parent;

  /* Now reduce both clusters to their ancestors at the point where both have
     a common parent; these can be directly compared.  */
  while (cl1->parent != cl2->parent)
    cl1 = cl1->parent, cl2 = cl2->parent;

  return group_cmp (cl1->group, cl2->group, cl2->index - cl1->index);
}

/* Return the ancestor of CL that's just below the root (i.e., has a parent
   of 0).  */
static struct hol_cluster *
hol_cluster_base (struct hol_cluster *cl)
{
  while (cl->parent)
    cl = cl->parent;
  return cl;
}

/* Return true if CL1 is a child of CL2.  */
static int
hol_cluster_is_child (const struct hol_cluster *cl1,
710
                      const struct hol_cluster *cl2)
711 712 713 714 715 716
{
  while (cl1 && cl1 != cl2)
    cl1 = cl1->parent;
  return cl1 == cl2;
}

717
/* Given the name of an OPTION_DOC option, modifies NAME to start at the tail
718 719 720 721 722 723
   that should be used for comparisons, and returns true iff it should be
   treated as a non-option.  */
static int
canon_doc_option (const char **name)
{
  int non_opt;
724 725 726 727 728 729

  if (!*name)
    non_opt = 1;
  else
    {
      /* Skip initial whitespace.  */
730
      while (isspace ((unsigned char) **name))
731
        (*name)++;
732
      /* Decide whether this looks like an option (leading '-') or not.  */
733 734
      non_opt = (**name != '-');
      /* Skip until part of name used for sorting.  */
735
      while (**name && !isalnum ((unsigned char) **name))
736
        (*name)++;
737
    }
738 739 740
  return non_opt;
}

741
#define HOL_ENTRY_PTRCMP(a,b) ((a)->ord < (b)->ord ? -1 : 1)
742

743 744 745 746
/* Order ENTRY1 & ENTRY2 by the order which they should appear in a help
   listing.  */
static int
hol_entry_cmp (const struct hol_entry *entry1,
747
               const struct hol_entry *entry2)
748 749 750 751
{
  /* The group numbers by which the entries should be ordered; if either is
     in a cluster, then this is just the group within the cluster.  */
  int group1 = entry1->group, group2 = entry2->group;
752
  int rc;
753 754 755 756

  if (entry1->cluster != entry2->cluster)
    {
      /* The entries are not within the same cluster, so we can't compare them
Paul Eggert's avatar
Paul Eggert committed
757
         directly, we have to use the appropriate clustering level too.  */
758
      if (! entry1->cluster)
759
        /* ENTRY1 is at the "base level", not in a cluster, so we have to
760 761 762 763
           compare it's group number with that of the base cluster in which
           ENTRY2 resides.  Note that if they're in the same group, the
           clustered option always comes laster.  */
        return group_cmp (group1, hol_cluster_base (entry2->cluster)->group, -1);
764
      else if (! entry2->cluster)
765 766
        /* Likewise, but ENTRY2's not in a cluster.  */
        return group_cmp (hol_cluster_base (entry1->cluster)->group, group2, 1);
767
      else
768 769
        /* Both entries are in clusters, we can just compare the clusters.  */
        return (rc = hol_cluster_cmp (entry1->cluster, entry2->cluster)) ?
Bruno Haible's avatar
Bruno Haible committed
770
               rc : HOL_ENTRY_PTRCMP (entry1, entry2);
771 772 773 774 775 776 777 778 779 780 781 782 783
    }
  else if (group1 == group2)
    /* The entries are both in the same cluster and group, so compare them
       alphabetically.  */
    {
      int short1 = hol_entry_first_short (entry1);
      int short2 = hol_entry_first_short (entry2);
      int doc1 = odoc (entry1->opt);
      int doc2 = odoc (entry2->opt);
      const char *long1 = hol_entry_first_long (entry1);
      const char *long2 = hol_entry_first_long (entry2);

      if (doc1)
784
        doc1 = canon_doc_option (&long1);
785
      if (doc2)
786
        doc2 = canon_doc_option (&long2);
787 788

      if (doc1 != doc2)
789
        /* "documentation" options always follow normal options (or
790 791
           documentation options that *look* like normal options).  */
        return doc1 - doc2;
792
      else if (!short1 && !short2 && long1 && long2)
793 794
        /* Only long options.  */
        return (rc = __strcasecmp (long1, long2)) ?
Bruno Haible's avatar
Bruno Haible committed
795
               rc : HOL_ENTRY_PTRCMP (entry1, entry2);
796
      else
797 798 799 800 801 802 803 804 805 806 807 808 809 810
        /* Compare short/short, long/short, short/long, using the first
           character of long options.  Entries without *any* valid
           options (such as options with OPTION_HIDDEN set) will be put
           first, but as they're not displayed, it doesn't matter where
           they are.  */
        {
          unsigned char first1 = short1 ? short1 : long1 ? *long1 : 0;
          unsigned char first2 = short2 ? short2 : long2 ? *long2 : 0;
          /* Use tolower, not _tolower, since only the former is
             guaranteed to work on something already lower case.  */
          int lower_cmp = tolower (first1) - tolower (first2);
          /* Compare ignoring case, except when the options are both the
             same letter, in which case lower-case always comes first.  */
          return lower_cmp ? lower_cmp :
Bruno Haible's avatar
Bruno Haible committed
811 812
                 (rc = first2 - first1) ?
                 rc : HOL_ENTRY_PTRCMP (entry1, entry2);
813
        }
814 815 816 817
    }
  else
    /* Within the same cluster, but not the same group, so just compare
       groups.  */
Bruno Haible's avatar
Bruno Haible committed
818
    return group_cmp (group1, group2, HOL_ENTRY_PTRCMP (entry1, entry2));
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
}

/* Version of hol_entry_cmp with correct signature for qsort.  */
static int
hol_entry_qcmp (const void *entry1_v, const void *entry2_v)
{
  return hol_entry_cmp (entry1_v, entry2_v);
}

/* Sort HOL by group and alphabetically by option name (with short options
   taking precedence over long).  Since the sorting is for display purposes
   only, the shadowing of options isn't effected.  */
static void
hol_sort (struct hol *hol)
{
  if (hol->num_entries > 0)
835 836 837 838
    {
      unsigned i;
      struct hol_entry *e;
      for (i = 0, e = hol->entries; i < hol->num_entries; i++, e++)
839
        e->ord = i;
840
      qsort (hol->entries, hol->num_entries, sizeof (struct hol_entry),
841
             hol_entry_qcmp);
842
    }
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
}

/* Append MORE to HOL, destroying MORE in the process.  Options in HOL shadow
   any in MORE with the same name.  */
static void
hol_append (struct hol *hol, struct hol *more)
{
  struct hol_cluster **cl_end = &hol->clusters;

  /* Steal MORE's cluster list, and add it to the end of HOL's.  */
  while (*cl_end)
    cl_end = &(*cl_end)->next;
  *cl_end = more->clusters;
  more->clusters = 0;

  /* Merge entries.  */
  if (more->num_entries > 0)
    {
      if (hol->num_entries == 0)
862 863 864 865 866 867
        {
          hol->num_entries = more->num_entries;
          hol->entries = more->entries;
          hol->short_options = more->short_options;
          more->num_entries = 0;        /* Mark MORE's fields as invalid.  */
        }
868
      else
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
        /* Append the entries in MORE to those in HOL, taking care to only add
           non-shadowed SHORT_OPTIONS values.  */
        {
          unsigned left;
          char *so, *more_so;
          struct hol_entry *e;
          unsigned num_entries = hol->num_entries + more->num_entries;
          struct hol_entry *entries =
            malloc (num_entries * sizeof (struct hol_entry));
          unsigned hol_so_len = strlen (hol->short_options);
          char *short_options =
            malloc (hol_so_len + strlen (more->short_options) + 1);

          assert (entries && short_options);
          if (SIZE_MAX <= UINT_MAX)
            assert (num_entries <= SIZE_MAX / sizeof (struct hol_entry));

          __mempcpy (__mempcpy (entries, hol->entries,
                                hol->num_entries * sizeof (struct hol_entry)),
                     more->entries,
                     more->num_entries * sizeof (struct hol_entry));

          __mempcpy (short_options, hol->short_options, hol_so_len);

          /* Fix up the short options pointers from HOL.  */
          for (e = entries, left = hol->num_entries; left > 0; e++, left--)
895 896
            e->short_options =
              short_options + (e->short_options - hol->short_options);
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933

          /* Now add the short options from MORE, fixing up its entries
             too.  */
          so = short_options + hol_so_len;
          more_so = more->short_options;
          for (left = more->num_entries; left > 0; e++, left--)
            {
              int opts_left;
              const struct argp_option *opt;

              e->short_options = so;

              for (opts_left = e->num, opt = e->opt; opts_left; opt++, opts_left--)
                {
                  int ch = *more_so;
                  if (oshort (opt) && ch == opt->key)
                    /* The next short option in MORE_SO, CH, is from OPT.  */
                    {
                      if (! find_char (ch, short_options,
                                       short_options + hol_so_len))
                        /* The short option CH isn't shadowed by HOL's options,
                           so add it to the sum.  */
                        *so++ = ch;
                      more_so++;
                    }
                }
            }

          *so = '\0';

          free (hol->entries);
          free (hol->short_options);

          hol->entries = entries;
          hol->num_entries = num_entries;
          hol->short_options = short_options;
        }
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
    }

  hol_free (more);
}

/* Inserts enough spaces to make sure STREAM is at column COL.  */
static void
indent_to (argp_fmtstream_t stream, unsigned col)
{
  int needed = col - __argp_fmtstream_point (stream);
  while (needed-- > 0)
    __argp_fmtstream_putc (stream, ' ');
}

/* Output to STREAM either a space, or a newline if there isn't room for at
   least ENSURE characters before the right margin.  */
static void
space (argp_fmtstream_t stream, size_t ensure)
{
  if (__argp_fmtstream_point (stream) + ensure
      >= __argp_fmtstream_rmargin (stream))
    __argp_fmtstream_putc (stream, '\n');
  else
    __argp_fmtstream_putc (stream, ' ');
}

/* If the option REAL has an argument, we print it in using the printf
   format REQ_FMT or OPT_FMT depending on whether it's a required or
   optional argument.  */
static void
arg (const struct argp_option *real, const char *req_fmt, const char *opt_fmt,
     const char *domain, argp_fmtstream_t stream)
{
  if (real->arg)
    {
      if (real->flags & OPTION_ARG_OPTIONAL)
970 971
        __argp_fmtstream_printf (stream, opt_fmt,
                                 dgettext (domain, real->arg));
972
      else
973 974
        __argp_fmtstream_printf (stream, req_fmt,
                                 dgettext (domain, real->arg));
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
    }
}

/* Helper functions for hol_entry_help.  */

/* State used during the execution of hol_help.  */
struct hol_help_state
{
  /* PREV_ENTRY should contain the previous entry printed, or 0.  */
  struct hol_entry *prev_entry;

  /* If an entry is in a different group from the previous one, and SEP_GROUPS
     is true, then a blank line will be printed before any output. */
  int sep_groups;

  /* True if a duplicate option argument was suppressed (only ever set if
     UPARAMS.dup_args is false).  */
  int suppressed_dup_arg;
};

/* Some state used while printing a help entry (used to communicate with
   helper functions).  See the doc for hol_entry_help for more info, as most
   of the fields are copied from its arguments.  */
struct pentry_state
{
  const struct hol_entry *entry;
  argp_fmtstream_t stream;
  struct hol_help_state *hhstate;

  /* True if nothing's been printed so far.  */
  int first;

  /* If non-zero, the state that was used to print this help.  */
  const struct argp_state *state;
};

/* If a user doc filter should be applied to DOC, do so.  */
static const char *
filter_doc (const char *doc, int key, const struct argp *argp,
1014
            const struct argp_state *state)
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
{
  if (argp->help_filter)
    /* We must apply a user filter to this output.  */
    {
      void *input = __argp_input (argp, state);
      return (*argp->help_filter) (key, doc, input);
    }
  else
    /* No filter.  */
    return doc;
}

Paul Eggert's avatar
Paul Eggert committed
1027
/* Prints STR as a header line, with the margin lines set appropriately, and
1028 1029 1030 1031 1032 1033
   notes the fact that groups should be separated with a blank line.  ARGP is
   the argp that should dictate any user doc filtering to take place.  Note
   that the previous wrap margin isn't restored, but the left margin is reset
   to 0.  */
static void
print_header (const char *str, const struct argp *argp,
1034
              struct pentry_state *pest)
1035 1036 1037 1038 1039 1040 1041
{
  const char *tstr = dgettext (argp->argp_domain, str);
  const char *fstr = filter_doc (tstr, ARGP_KEY_HELP_HEADER, argp, pest->state);

  if (fstr)
    {
      if (*fstr)
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
        {
          if (pest->hhstate->prev_entry)
            /* Precede with a blank line.  */
            __argp_fmtstream_putc (pest->stream, '\n');
          indent_to (pest->stream, uparams.header_col);
          __argp_fmtstream_set_lmargin (pest->stream, uparams.header_col);
          __argp_fmtstream_set_wmargin (pest->stream, uparams.header_col);
          __argp_fmtstream_puts (pest->stream, fstr);
          __argp_fmtstream_set_lmargin (pest->stream, 0);
          __argp_fmtstream_putc (pest->stream, '\n');
        }
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073

      pest->hhstate->sep_groups = 1; /* Separate subsequent groups. */
    }

  if (fstr != tstr)
    free ((char *) fstr);
}

/* Inserts a comma if this isn't the first item on the line, and then makes
   sure we're at least to column COL.  If this *is* the first item on a line,
   prints any pending whitespace/headers that should precede this line. Also
   clears FIRST.  */
static void
comma (unsigned col, struct pentry_state *pest)
{
  if (pest->first)
    {
      const struct hol_entry *pe = pest->hhstate->prev_entry;
      const struct hol_cluster *cl = pest->entry->cluster;

      if (pest->hhstate->sep_groups && pe && pest->entry->group != pe->group)
1074
        __argp_fmtstream_putc (pest->stream, '\n');
1075 1076

      if (cl && cl->header && *cl->header
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
          && (!pe
              || (pe->cluster != cl
                  && !hol_cluster_is_child (pe->cluster, cl))))
        /* If we're changing clusters, then this must be the start of the
           ENTRY's cluster unless that is an ancestor of the previous one
           (in which case we had just popped into a sub-cluster for a bit).
           If so, then print the cluster's header line.  */
        {
          int old_wm = __argp_fmtstream_wmargin (pest->stream);
          print_header (cl->header, cl->argp, pest);
          __argp_fmtstream_set_wmargin (pest->stream, old_wm);
        }
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100

      pest->first = 0;
    }
  else
    __argp_fmtstream_puts (pest->stream, ", ");

  indent_to (pest->stream, col);
}

/* Print help for ENTRY to STREAM.  */
static void
hol_entry_help (struct hol_entry *entry, const struct argp_state *state,
1101
                argp_fmtstream_t stream, struct hol_help_state *hhstate)
1102 1103 1104 1105
{
  unsigned num;
  const struct argp_option *real = entry->opt, *opt;
  char *so = entry->short_options;
1106
  int have_long_opt = 0;        /* We have any long options.  */
1107 1108 1109 1110 1111
  /* Saved margins.  */
  int old_lm = __argp_fmtstream_set_lmargin (stream, 0);
  int old_wm = __argp_fmtstream_wmargin (stream);
  /* PEST is a state block holding some of our variables that we'd like to
     share with helper functions.  */
1112 1113 1114 1115 1116 1117 1118
  struct pentry_state pest;

  pest.entry = entry;
  pest.stream = stream;
  pest.hhstate = hhstate;
  pest.first = 1;
  pest.state = state;
1119 1120 1121 1122

  if (! odoc (real))
    for (opt = real, num = entry->num; num > 0; opt++, num--)
      if (opt->name && ovisible (opt))
1123 1124 1125 1126
        {
          have_long_opt = 1;
          break;
        }
1127 1128 1129 1130 1131 1132 1133

  /* First emit short options.  */
  __argp_fmtstream_set_wmargin (stream, uparams.short_opt_col); /* For truly bizarre cases. */
  for (opt = real, num = entry->num; num > 0; opt++, num--)
    if (oshort (opt) && opt->key == *so)
      /* OPT has a valid (non shadowed) short option.  */
      {
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
        if (ovisible (opt))
          {
            comma (uparams.short_opt_col, &pest);
            __argp_fmtstream_putc (stream, '-');
            __argp_fmtstream_putc (stream, *so);
            if (!have_long_opt || uparams.dup_args)
              arg (real, " %s", "[%s]", state->root_argp->argp_domain, stream);
            else if (real->arg)
              hhstate->suppressed_dup_arg = 1;
          }
        so++;
1145 1146 1147 1148
      }

  /* Now, long options.  */
  if (odoc (real))
1149
    /* A "documentation" option.  */
1150 1151 1152
    {
      __argp_fmtstream_set_wmargin (stream, uparams.doc_opt_col);
      for (opt = real, num = entry->num; num > 0; opt++, num--)
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
        if (opt->name && *opt->name && ovisible (opt))
          {
            comma (uparams.doc_opt_col, &pest);
            /* Calling dgettext here isn't quite right, since sorting will
               have been done on the original; but documentation options
               should be pretty rare anyway...  */
            __argp_fmtstream_puts (stream,
                                   onotrans (opt) ?
                                             opt->name :
                                   dgettext (state->root_argp->argp_domain,
                                             opt->name));
          }
1165 1166 1167 1168 1169 1170 1171 1172
    }
  else
    /* A real long option.  */
    {
      int first_long_opt = 1;

      __argp_fmtstream_set_wmargin (stream, uparams.long_opt_col);
      for (opt = real, num = entry->num; num > 0; opt++, num--)
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
        if (opt->name && ovisible (opt))
          {
            comma (uparams.long_opt_col, &pest);
            __argp_fmtstream_printf (stream, "--%s", opt->name);
            if (first_long_opt || uparams.dup_args)
              arg (real, "=%s", "[=%s]", state->root_argp->argp_domain,
                   stream);
            else if (real->arg)
              hhstate->suppressed_dup_arg = 1;
          }
1183 1184 1185 1186 1187 1188 1189 1190 1191
    }

  /* Next, documentation strings.  */
  __argp_fmtstream_set_lmargin (stream, 0);

  if (pest.first)
    {
      /* Didn't print any switches, what's up?  */
      if (!oshort (real) && !real->name)
1192 1193
        /* This is a group header, print it nicely.  */
        print_header (real->doc, entry->argp, &pest);
1194
      else
1195 1196
        /* Just a totally shadowed option or null header; print nothing.  */
        goto cleanup;           /* Just return, after cleaning up.  */
1197 1198 1199 1200
    }
  else
    {
      const char *tstr = real->doc ? dgettext (state->root_argp->argp_domain,
1201
                                               real->doc) : 0;
1202 1203
      const char *fstr = filter_doc (tstr, real->key, entry->argp, state);
      if (fstr && *fstr)
1204 1205
        {
          unsigned int col = __argp_fmtstream_point (stream);
1206

1207 1208
          __argp_fmtstream_set_lmargin (stream, uparams.opt_doc_col);
          __argp_fmtstream_set_wmargin (stream, uparams.opt_doc_col);
1209

1210 1211 1212 1213 1214 1215
          if (col > (unsigned int) (uparams.opt_doc_col + 3))
            __argp_fmtstream_putc (stream, '\n');
          else if (col >= (unsigned int) uparams.opt_doc_col)
            __argp_fmtstream_puts (stream, "   ");
          else
            indent_to (stream, uparams.opt_doc_col);
1216

1217 1218
          __argp_fmtstream_puts (stream, fstr);
        }
1219
      if (fstr && fstr != tstr)
1220
        free ((char *) fstr);
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236

      /* Reset the left margin.  */
      __argp_fmtstream_set_lmargin (stream, 0);
      __argp_fmtstream_putc (stream, '\n');
    }

  hhstate->prev_entry = entry;

cleanup:
  __argp_fmtstream_set_lmargin (stream, old_lm);
  __argp_fmtstream_set_wmargin (stream, old_wm);
}

/* Output a long help message about the options in HOL to STREAM.  */
static void
hol_help (struct hol *hol, const struct argp_state *state,
1237
          argp_fmtstream_t stream)
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
{
  unsigned num;
  struct hol_entry *entry;
  struct hol_help_state hhstate = { 0, 0, 0 };

  for (entry = hol->entries, num = hol->num_entries; num > 0; entry++, num--)
    hol_entry_help (entry, state, stream, &hhstate);

  if (hhstate.suppressed_dup_arg && uparams.dup_args_note)
    {
      const char *tstr = dgettext (state->root_argp->argp_domain, "\
Mandatory or optional arguments to long options are also mandatory or \
optional for any corresponding short options.");
      const char *fstr = filter_doc (tstr, ARGP_KEY_HELP_DUP_ARGS_NOTE,
1252
                                     state ? state->root_argp : 0, state);
1253
      if (fstr && *fstr)
1254 1255 1256 1257 1258
        {
          __argp_fmtstream_putc (stream, '\n');
          __argp_fmtstream_puts (stream, fstr);
          __argp_fmtstream_putc (stream, '\n');
        }
1259
      if (fstr && fstr != tstr)
1260
        free ((char *) fstr);
1261 1262 1263 1264 1265 1266 1267 1268 1269
    }
}

/* Helper functions for hol_usage.  */

/* If OPT is a short option without an arg, append its key to the string
   pointer pointer to by COOKIE, and advance the pointer.  */
static int
add_argless_short_opt (const struct argp_option *opt,
1270 1271
                       const struct argp_option *real,
                       const char *domain, void *cookie)
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
{
  char **snao_end = cookie;
  if (!(opt->arg || real->arg)
      && !((opt->flags | real->flags) & OPTION_NO_USAGE))
    *(*snao_end)++ = opt->key;
  return 0;
}

/* If OPT is a short option with an arg, output a usage entry for it to the
   stream pointed at by COOKIE.  */
static int
usage_argful_short_opt (const struct argp_option *opt,
1284 1285
                        const struct argp_option *real,
                        const char *domain, void *cookie)
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
{
  argp_fmtstream_t stream = cookie;
  const char *arg = opt->arg;
  int flags = opt->flags | real->flags;

  if (! arg)
    arg = real->arg;

  if (arg && !(flags & OPTION_NO_USAGE))
    {
      arg = dgettext (domain, arg);

      if (flags & OPTION_ARG_OPTIONAL)
1299
        __argp_fmtstream_printf (stream, " [-%c[%s]]", opt->key, arg);
1300
      else
1301 1302 1303 1304 1305 1306
        {
          /* Manually do line wrapping so that it (probably) won't
             get wrapped at the embedded space.  */
          space (stream, 6 + strlen (arg));
          __argp_fmtstream_printf (stream, "[-%c %s]", opt->key, arg);
        }
1307 1308 1309 1310 1311 1312 1313 1314 1315
    }

  return 0;
}

/* Output a usage entry for the long option opt to the stream pointed at by
   COOKIE.  */
static int
usage_long_opt (const struct argp_option *opt,
1316 1317
                const struct argp_option *real,
                const char *domain, void *cookie)
1318 1319 1320 1321 1322 1323 1324 1325
{
  argp_fmtstream_t stream = cookie;
  const char *arg = opt->arg;
  int flags = opt->flags | real->flags;

  if (! arg)
    arg = real->arg;

1326
  if (! (flags & OPTION_NO_USAGE) && !odoc (opt))
1327 1328
    {
      if (arg)
1329 1330 1331 1332 1333 1334 1335
        {
          arg = dgettext (domain, arg);
          if (flags & OPTION_ARG_OPTIONAL)
            __argp_fmtstream_printf (stream, " [--%s[=%s]]", opt->name, arg);
          else
            __argp_fmtstream_printf (stream, " [--%s=%s]", opt->name, arg);
        }
1336
      else
1337
        __argp_fmtstream_printf (stream, " [--%s]", opt->name);
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
    }

  return 0;
}

/* Print a short usage description for the arguments in HOL to STREAM.  */
static void
hol_usage (struct hol *hol, argp_fmtstream_t stream)
{
  if (hol->num_entries > 0)
    {
      unsigned nentries;
      struct hol_entry *entry;
      char *short_no_arg_opts = alloca (strlen (hol->short_options) + 1);
      char *snao_end = short_no_arg_opts;

      /* First we put a list of short options without arguments.  */
      for (entry = hol->entries, nentries = hol->num_entries
1356 1357 1358 1359
           ; nentries > 0
           ; entry++, nentries--)
        hol_entry_short_iterate (entry, add_argless_short_opt,
                                 entry->argp->argp_domain, &snao_end);
1360
      if (snao_end > short_no_arg_opts)
1361 1362 1363 1364
        {
          *snao_end++ = 0;
          __argp_fmtstream_printf (stream, " [-%s]", short_no_arg_opts);
        }
1365 1366 1367

      /* Now a list of short options *with* arguments.  */
      for (entry = hol->entries, nentries = hol->num_entries
1368 1369 1370 1371
           ; nentries > 0
           ; entry++, nentries--)
        hol_entry_short_iterate (entry, usage_argful_short_opt,
                                 entry->argp->argp_domain, stream);
1372 1373 1374

      /* Finally, a list of long options (whew!).  */
      for (entry = hol->entries, nentries = hol->num_entries
1375 1376 1377 1378
           ; nentries > 0
           ; entry++, nentries--)
        hol_entry_long_iterate (entry, usage_long_opt,
                                entry->argp->argp_domain, stream);
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
    }
}

/* Make a HOL containing all levels of options in ARGP.  CLUSTER is the
   cluster in which ARGP's entries should be clustered, or 0.  */
static struct hol *
argp_hol (const struct argp *argp, struct hol_cluster *cluster)
{
  const struct argp_child *child = argp->children;
  struct hol *hol = make_hol (argp, cluster);
  if (child)
    while (child->argp)
      {
1392 1393 1394 1395 1396 1397 1398 1399 1400
        struct hol_cluster *child_cluster =
          ((child->group || child->header)
           /* Put CHILD->argp within its own cluster.  */
           ? hol_add_cluster (hol, child->group, child->header,
                              child - argp->children, cluster, argp)
           /* Just merge it into the parent's cluster.  */
           : cluster);
        hol_append (hol, argp_hol (child->argp, child_cluster)) ;
        child++;
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
      }
  return hol;
}

/* Calculate how many different levels with alternative args strings exist in
   ARGP.  */
static size_t
argp_args_levels (const struct argp *argp)
{
  size_t levels = 0;
  const struct argp_child *child = argp->children;

  if (argp->args_doc && strchr (argp->args_doc, '\n'))
    levels++;

  if (child)
    while (child->argp)
      levels += argp_args_levels ((child++)->argp);

  return levels;
}

/* Print all the non-option args documented in ARGP to STREAM.  Any output is
   preceded by a space.  LEVELS is a pointer to a byte vector the length
   returned by argp_args_levels; it should be initialized to zero, and
   updated by this routine for the next call if ADVANCE is true.  True is
   returned as long as there are more patterns to output.  */
static int
argp_args_usage (const struct argp *argp, const struct argp_state *state,
1430
                 char **levels, int advance, argp_fmtstream_t stream)
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
{
  char *our_level = *levels;
  int multiple = 0;
  const struct argp_child *child = argp->children;
  const char *tdoc = dgettext (argp->argp_domain, argp->args_doc), *nl = 0;
  const char *fdoc = filter_doc (tdoc, ARGP_KEY_HELP_ARGS_DOC, argp, state);

  if (fdoc)
    {
      const char *cp = fdoc;
      nl = __strchrnul (cp, '\n');
      if (*nl != '\0')
1443
        /* This is a "multi-level" args doc; advance to the correct position
1444 1445 1446 1447 1448 1449 1450 1451
           as determined by our state in LEVELS, and update LEVELS.  */
        {
          int i;
          multiple = 1;
          for (i = 0; i < *our_level; i++)
            cp = nl + 1, nl = __strchrnul (cp, '\n');
          (*levels)++;
        }
1452 1453

      /* Manually do line wrapping so that it (probably) won't get wrapped at
1454
         any embedded spaces.  */
1455 1456 1457 1458 1459
      space (stream, 1 + nl - cp);

      __argp_fmtstream_write (stream, cp, nl - cp);
    }
  if (fdoc && fdoc != tdoc)
1460
    free ((char *)fdoc);        /* Free user's modified doc string.  */
1461 1462 1463 1464 1465 1466 1467 1468 1469

  if (child)
    while (child->argp)
      advance = !argp_args_usage ((child++)->argp, state, levels, advance, stream);

  if (advance && multiple)
    {
      /* Need to increment our level.  */
      if (*nl)
1470 1471 1472 1473 1474
        /* There's more we can do here.  */
        {
          (*our_level)++;
          advance = 0;          /* Our parent shouldn't advance also. */
        }
1475
      else if (*our_level > 0)
1476 1477
        /* We had multiple levels, but used them up; reset to zero.  */
        *our_level = 0;
1478 1479 1480 1481 1482 1483
    }

  return !advance;
}

/* Print the documentation for ARGP to STREAM; if POST is false, then
Paul Eggert's avatar
Paul Eggert committed
1484
   everything preceding a '\v' character in the documentation strings (or
1485
   the whole string, for those with none) is printed, otherwise, everything
1486
   following the '\v' character (nothing for strings without).  Each separate
1487 1488 1489 1490 1491
   bit of documentation is separated a blank line, and if PRE_BLANK is true,
   then the first is as well.  If FIRST_ONLY is true, only the first
   occurrence is output.  Returns true if anything was output.  */
static int
argp_doc (const struct argp *argp, const struct argp_state *state,
1492 1493
          int post, int pre_blank, int first_only,
          argp_fmtstream_t stream)
1494 1495 1496
{
  const char *text;
  const char *inp_text;
1497
  size_t inp_text_len = 0;
1498
  const char *trans_text;
1499 1500 1501 1502
  void *input = 0;
  int anything = 0;
  const struct argp_child *child = argp->children;

1503
  if (argp->doc)
1504
    {
1505 1506
      char *vt = strchr (argp->doc, '\v');
      if (vt)
1507 1508
        {
          if (post)
1509 1510 1511 1512 1513
            {
              inp_text = vt + 1;
              if (! *inp_text)
                inp_text = 0;
            }
1514 1515 1516
          else
            {
              inp_text_len = vt - argp->doc;
1517
              inp_text = inp_text_len ? __strndup (argp->doc, inp_text_len) : 0;
1518 1519
            }
        }
1520
      else
1521
        inp_text = post ? 0 : argp->doc;
1522
      trans_text = inp_text ? dgettext (argp->argp_domain, inp_text) : NULL;
1523 1524
    }
  else
1525
    trans_text = inp_text = 0;
1526 1527 1528 1529 1530 1531

  if (argp->help_filter)
    /* We have to filter the doc strings.  */
    {
      input = __argp_input (argp, state);
      text =
1532 1533 1534 1535
        (*argp->help_filter) (post
                              ? ARGP_KEY_HELP_POST_DOC
                              : ARGP_KEY_HELP_PRE_DOC,
                              trans_text, input);
1536 1537
    }
  else
1538
    text = (const char *) trans_text;
1539 1540 1541 1542

  if (text)
    {
      if (pre_blank)
1543
        __argp_fmtstream_putc (stream, '\n');
1544

1545
      __argp_fmtstream_puts (stream, text);
1546 1547

      if (__argp_fmtstream_point (stream) > __argp_fmtstream_lmargin (stream))
1548
        __argp_fmtstream_putc (stream, '\n');
1549 1550 1551 1552

      anything = 1;
    }

1553
  if (text && text != trans_text)
1554
    free ((char *) text);       /* Free TEXT returned from the help filter.  */
1555 1556

  if (inp_text && inp_text_len)
1557
    free ((char *) inp_text);   /* We copied INP_TEXT, so free it now.  */
1558 1559

  if (post && argp->help_filter)
1560
    /* Now see if we have to output an ARGP_KEY_HELP_EXTRA text.  */
1561 1562 1563
    {
      text = (*argp->help_filter) (ARGP_KEY_HELP_EXTRA, 0, input);
      if (text)
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
        {
          if (anything || pre_blank)
            __argp_fmtstream_putc (stream, '\n');
          __argp_fmtstream_puts (stream, text);
          free ((char *) text);
          if (__argp_fmtstream_point (stream)
              > __argp_fmtstream_lmargin (stream))
            __argp_fmtstream_putc (stream, '\n');
          anything = 1;
        }
1574 1575 1576 1577 1578
    }

  if (child)
    while (child->argp && !(first_only && anything))
      anything |=
1579 1580 1581
        argp_doc ((child++)->argp, state,
                  post, anything || pre_blank, first_only,
                  stream);
1582 1583 1584 1585 1586

  return anything;
}

/* Output a usage message for ARGP to STREAM.  If called from
Paul Eggert's avatar
Paul Eggert committed
1587
   argp_state_help, STATE is the relevant parsing state.  FLAGS are from the
1588
   set ARGP_HELP_*.  NAME is what to use wherever a "program name" is
1589 1590 1591 1592 1593
   needed. */
static void
_help (const struct argp *argp, const struct argp_state *state, FILE *stream,
       unsigned flags, char *name)
{
1594
  int anything = 0;             /* Whether we've output anything.  */
1595 1596 1597 1598 1599 1600
  struct hol *hol = 0;
  argp_fmtstream_t fs;

  if (! stream)
    return;

Karl Berry's avatar
Karl Berry committed
1601
#if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
1602
  __flockfile (stream);
Karl Berry's avatar
Karl Berry committed
1603
#endif
1604 1605 1606 1607 1608 1609 1610

  if (! uparams.valid)
    fill_in_uparams (state);

  fs = __argp_make_fmtstream (stream, 0, uparams.rmargin, 0);
  if (! fs)
    {
Karl Berry's avatar
Karl Berry committed
1611
#if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
1612
      __funlockfile (stream);
Karl Berry's avatar
Karl Berry committed
1613
#endif
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
      return;
    }

  if (flags & (ARGP_HELP_USAGE | ARGP_HELP_SHORT_USAGE | ARGP_HELP_LONG))
    {
      hol = argp_hol (argp, 0);

      /* If present, these options always come last.  */
      hol_set_group (hol, "help", -1);
      hol_set_group (hol, "version", -1);

      hol_sort (hol);
    }

  if (flags & (ARGP_HELP_USAGE | ARGP_HELP_SHORT_USAGE))
1629
    /* Print a short "Usage:" message.  */
1630 1631 1632 1633 1634 1635 1636 1637
    {
      int first_pattern = 1, more_patterns;
      size_t num_pattern_levels = argp_args_levels (argp);
      char *pattern_levels = alloca (num_pattern_levels);

      memset (pattern_levels, 0, num_pattern_levels);

      do
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
        {
          int old_lm;
          int old_wm = __argp_fmtstream_set_wmargin (fs, uparams.usage_indent);
          char *levels = pattern_levels;

          if (first_pattern)
            __argp_fmtstream_printf (fs, "%s %s",
                                     dgettext (argp->argp_domain, "Usage:"),
                                     name);
          else
            __argp_fmtstream_printf (fs, "%s %s",
                                     dgettext (argp->argp_domain, "  or: "),
                                     name);

          /* We set the lmargin as well as the wmargin, because hol_usage
             manually wraps options with newline to avoid annoying breaks.  */
          old_lm = __argp_fmtstream_set_lmargin (fs, uparams.usage_indent);

          if (flags & ARGP_HELP_SHORT_USAGE)
            /* Just show where the options go.  */
            {
              if (hol->num_entries > 0)
                __argp_fmtstream_puts (fs, dgettext (argp->argp_domain,
                                                     " [OPTION...]"));
            }
          else
            /* Actually print the options.  */
            {
              hol_usage (hol, fs);
              flags |= ARGP_HELP_SHORT_USAGE; /* But only do so once.  */
            }

          more_patterns = argp_args_usage (argp, state, &levels, 1, fs);

          __argp_fmtstream_set_wmargin (fs, old_wm);
          __argp_fmtstream_set_lmargin (fs, old_lm);

          __argp_fmtstream_putc (fs, '\n');
          anything = 1;

          first_pattern = 0;
        }
1680 1681 1682 1683 1684 1685 1686 1687 1688
      while (more_patterns);
    }

  if (flags & ARGP_HELP_PRE_DOC)
    anything |= argp_doc (argp, state, 0, 0, 1, fs);

  if (flags & ARGP_HELP_SEE)
    {
      __argp_fmtstream_printf (fs, dgettext (argp->argp_domain, "\
1689
Try '%s --help' or '%s --usage' for more information.\n"),
1690
                               name, name);
1691 1692 1693 1694 1695 1696 1697 1698
      anything = 1;
    }

  if (flags & ARGP_HELP_LONG)
    /* Print a long, detailed help message.  */
    {
      /* Print info about all the options.  */
      if (hol->num_entries > 0)
1699 1700 1701 1702 1703 1704
        {
          if (anything)
            __argp_fmtstream_putc (fs, '\n');
          hol_help (hol, state, fs);
          anything = 1;
        }
1705 1706 1707 1708 1709 1710 1711 1712 1713
    }

  if (flags & ARGP_HELP_POST_DOC)
    /* Print any documentation strings at the end.  */
    anything |= argp_doc (argp, state, 1, anything, 0, fs);

  if ((flags & ARGP_HELP_BUG_ADDR) && argp_program_bug_address)
    {
      if (anything)
1714
        __argp_fmtstream_putc (fs, '\n');
1715
      __argp_fmtstream_printf (fs, dgettext (argp->argp_domain,
1716 1717
                                             "Report bugs to %s.\n"),
                               argp_program_bug_address);
1718 1719 1720
      anything = 1;
    }

Karl Berry's avatar
Karl Berry committed
1721
#if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
1722
  __funlockfile (stream);
Karl Berry's avatar
Karl Berry committed
1723
#endif
1724 1725 1726 1727 1728 1729 1730 1731

  if (hol)
    hol_free (hol);

  __argp_fmtstream_free (fs);
}

/* Output a usage message for ARGP to STREAM.  FLAGS are from the set
1732
   ARGP_HELP_*.  NAME is what to use wherever a "program name" is needed. */
1733
void __argp_help (const struct argp *argp, FILE *stream,
1734
                  unsigned flags, char *name)
1735
{
1736 1737 1738 1739
  struct argp_state state;
  memset (&state, 0, sizeof state);
  state.root_argp = argp;
  _help (argp, &state, stream, flags, name);
1740 1741 1742 1743 1744
}
#ifdef weak_alias
weak_alias (__argp_help, argp_help)
#endif

1745
#if ! (defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME)
Karl Berry's avatar
Karl Berry committed
1746 1747 1748
char *
__argp_short_program_name (void)
{
1749
# if HAVE_DECL_PROGRAM_INVOCATION_NAME
1750
  return __argp_base_name (program_invocation_name);
Karl Berry's avatar
Karl Berry committed
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
# else
  /* FIXME: What now? Miles suggests that it is better to use NULL,
     but currently the value is passed on directly to fputs_unlocked,
     so that requires more changes. */
# if __GNUC__
#  warning No reasonable value to return
# endif /* __GNUC__ */
  return "";
# endif
}
#endif

1763 1764 1765 1766 1767 1768 1769 1770
/* Output, if appropriate, a usage message for STATE to STREAM.  FLAGS are
   from the set ARGP_HELP_*.  */
void
__argp_state_help (const struct argp_state *state, FILE *stream, unsigned flags)
{
  if ((!state || ! (state->flags & ARGP_NO_ERRS)) && stream)
    {
      if (state && (state->flags & ARGP_LONG_ONLY))
1771
        flags |= ARGP_HELP_LONG_ONLY;
1772 1773

      _help (state ? state->root_argp : 0, state, stream, flags,
1774
             state ? state->name : __argp_short_program_name ());
1775 1776

      if (!state || ! (state->flags & ARGP_NO_EXIT))
1777 1778 1779 1780 1781 1782
        {
          if (flags & ARGP_HELP_EXIT_ERR)
            exit (argp_err_exit_status);
          if (flags & ARGP_HELP_EXIT_OK)
            exit (0);
        }
1783 1784 1785 1786 1787 1788 1789
  }
}
#ifdef weak_alias
weak_alias (__argp_state_help, argp_state_help)
#endif

/* If appropriate, print the printf string FMT and following args, preceded
1790
   by the program name and ':', to stderr, and followed by a "Try ... --help"
1791 1792 1793 1794 1795 1796 1797 1798 1799
   message, then exit (1).  */
void
__argp_error (const struct argp_state *state, const char *fmt, ...)
{
  if (!state || !(state->flags & ARGP_NO_ERRS))
    {
      FILE *stream = state ? state->err_stream : stderr;

      if (stream)
1800 1801
        {
          va_list ap;