goption.c 72.9 KB
Newer Older
Anders Carlsson's avatar
Anders Carlsson committed
1 2 3 4 5 6 7 8 9 10 11 12
/* goption.c - Option parser
 *
 *  Copyright (C) 1999, 2003 Red Hat Software
 *  Copyright (C) 2004       Anders Carlsson <andersca@gnome.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Anders Carlsson's avatar
Anders Carlsson committed
14 15 16
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
17
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
Anders Carlsson's avatar
Anders Carlsson committed
18
 */
19

20 21 22 23
/**
 * SECTION:option
 * @Short_description: parses commandline options
 * @Title: Commandline option parser
24 25 26 27 28
 *
 * The GOption commandline parser is intended to be a simpler replacement
 * for the popt library. It supports short and long commandline options,
 * as shown in the following example:
 *
Matthias Clasen's avatar
Matthias Clasen committed
29
 * `testtreemodel -r 1 --max-size 20 --rand --display=:1.0 -vb -- file1 file2`
30
 *
31
 * The example demonstrates a number of features of the GOption
32 33 34 35 36 37 38 39 40
 * commandline parser:
 *
 * - Options can be single letters, prefixed by a single dash.
 *
 * - Multiple short options can be grouped behind a single dash.
 *
 * - Long options are prefixed by two consecutive dashes.
 *
 * - Options can have an extra argument, which can be a number, a string or
41 42 43 44
 *   a filename. For long options, the extra argument can be appended with
 *   an equals sign after the option name, which is useful if the extra
 *   argument starts with a dash, which would otherwise cause it to be
 *   interpreted as another option.
45 46 47 48
 *
 * - Non-option arguments are returned to the application as rest arguments.
 *
 * - An argument consisting solely of two dashes turns off further parsing,
49
 *   any remaining arguments (even those starting with a dash) are returned
50
 *   to the application as rest arguments.
51
 *
52 53 54
 * Another important feature of GOption is that it can automatically
 * generate nicely formatted help output. Unless it is explicitly turned
 * off with g_option_context_set_help_enabled(), GOption will recognize
Matthias Clasen's avatar
Matthias Clasen committed
55 56 57
 * the `--help`, `-?`, `--help-all` and `--help-groupname` options
 * (where `groupname` is the name of a #GOptionGroup) and write a text
 * similar to the one shown in the following example to stdout.
58
 *
59
 * |[
60 61
 * Usage:
 *   testtreemodel [OPTION...] - test tree model performance
62
 *  
63
 * Help Options:
64
 *   -h, --help               Show help options
65 66
 *   --help-all               Show all help options
 *   --help-gtk               Show GTK+ Options
67
 *  
68 69 70 71 72
 * Application Options:
 *   -r, --repeats=N          Average over N repetitions
 *   -m, --max-size=M         Test up to 2^M items
 *   --display=DISPLAY        X display to use
 *   -v, --verbose            Be verbose
73
 *   -b, --beep               Beep when done
74
 *   --rand                   Randomize the data
75
 * ]|
76
 *
Matthias Clasen's avatar
Matthias Clasen committed
77
 * GOption groups options in #GOptionGroups, which makes it easy to
78 79 80 81
 * incorporate options from multiple sources. The intended use for this is
 * to let applications collect option groups from the libraries it uses,
 * add them to their #GOptionContext, and parse all options by a single call
 * to g_option_context_parse(). See gtk_get_option_group() for an example.
82
 *
83
 * If an option is declared to be of type string or filename, GOption takes
84 85 86 87 88
 * care of converting it to the right encoding; strings are returned in
 * UTF-8, filenames are returned in the GLib filename encoding. Note that
 * this only works if setlocale() has been called before
 * g_option_context_parse().
 *
89 90
 * Here is a complete example of setting up GOption to parse the example
 * commandline above and produce the example help output.
91
 * |[<!-- language="C" --> 
92 93 94 95
 * static gint repeats = 2;
 * static gint max_size = 8;
 * static gboolean verbose = FALSE;
 * static gboolean beep = FALSE;
96
 * static gboolean randomize = FALSE;
97 98
 *
 * static GOptionEntry entries[] =
99 100 101 102 103
 * {
 *   { "repeats", 'r', 0, G_OPTION_ARG_INT, &repeats, "Average over N repetitions", "N" },
 *   { "max-size", 'm', 0, G_OPTION_ARG_INT, &max_size, "Test up to 2^M items", "M" },
 *   { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Be verbose", NULL },
 *   { "beep", 'b', 0, G_OPTION_ARG_NONE, &beep, "Beep when done", NULL },
104
 *   { "rand", 0, 0, G_OPTION_ARG_NONE, &randomize, "Randomize the data", NULL },
105 106
 *   { NULL }
 * };
107 108
 *
 * int
109 110 111 112
 * main (int argc, char *argv[])
 * {
 *   GError *error = NULL;
 *   GOptionContext *context;
113
 *
114 115 116 117 118 119 120 121
 *   context = g_option_context_new ("- test tree model performance");
 *   g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
 *   g_option_context_add_group (context, gtk_get_option_group (TRUE));
 *   if (!g_option_context_parse (context, &argc, &argv, &error))
 *     {
 *       g_print ("option parsing failed: %s\n", error->message);
 *       exit (1);
 *     }
122 123 124
 *
 *   /&ast; ... &ast;/
 *
125
 * }
126
 * ]|
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
 *
 * On UNIX systems, the argv that is passed to main() has no particular
 * encoding, even to the extent that different parts of it may have
 * different encodings.  In general, normal arguments and flags will be
 * in the current locale and filenames should be considered to be opaque
 * byte strings.  Proper use of %G_OPTION_ARG_FILENAME vs
 * %G_OPTION_ARG_STRING is therefore important.
 *
 * Note that on Windows, filenames do have an encoding, but using
 * #GOptionContext with the argv as passed to main() will result in a
 * program that can only accept commandline arguments with characters
 * from the system codepage.  This can cause problems when attempting to
 * deal with filenames containing Unicode characters that fall outside
 * of the codepage.
 *
 * A solution to this is to use g_win32_get_command_line() and
 * g_option_context_parse_strv() which will properly handle full Unicode
 * filenames.  If you are using #GApplication, this is done
 * automatically for you.
 *
 * The following example shows how you can use #GOptionContext directly
 * in order to correctly deal with Unicode filenames on Windows:
 *
150
 * |[<!-- language="C" --> 
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
 * int
 * main (int argc, char **argv)
 * {
 *   GError *error = NULL;
 *   GOptionContext *context;
 *   gchar **args;
 *
 * #ifdef G_OS_WIN32
 *   args = g_win32_get_command_line ();
 * #else
 *   args = g_strdupv (argv);
 * #endif
 *
 *   /&ast; ... setup context ... &ast;/
 *
 *   if (!g_option_context_parse_strv (context, &args, &error))
 *     {
 *       /&ast; ... error ... &ast;/
 *     }
 *
 *   /&ast; ... &ast;/
 *
 *   g_strfreev (args);
 *
 *   /&ast; ... &ast;/
 * }
 * ]|
178
 */
Anders Carlsson's avatar
Anders Carlsson committed
179

180
#include "config.h"
Anders Carlsson's avatar
Anders Carlsson committed
181 182 183

#include <string.h>
#include <stdlib.h>
184
#include <stdio.h>
Anders Carlsson's avatar
Anders Carlsson committed
185 186
#include <errno.h>

187 188 189 190 191 192 193
#if defined __OpenBSD__
#include <sys/types.h>
#include <unistd.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#endif

194 195 196 197 198
#include "goption.h"

#include "gprintf.h"
#include "glibintl.h"

Anders Carlsson's avatar
Anders Carlsson committed
199 200
#define TRANSLATE(group, str) (((group)->translate_func ? (* (group)->translate_func) ((str), (group)->translate_data) : (str)))

201 202 203 204
#define NO_ARG(entry) ((entry)->arg == G_OPTION_ARG_NONE ||       \
                       ((entry)->arg == G_OPTION_ARG_CALLBACK &&  \
                        ((entry)->flags & G_OPTION_FLAG_NO_ARG)))

205 206 207
#define OPTIONAL_ARG(entry) ((entry)->arg == G_OPTION_ARG_CALLBACK &&  \
                       (entry)->flags & G_OPTION_FLAG_OPTIONAL_ARG)

208
typedef struct
209
{
Anders Carlsson's avatar
Anders Carlsson committed
210
  GOptionArg arg_type;
211 212
  gpointer arg_data;
  union
213
  {
Anders Carlsson's avatar
Anders Carlsson committed
214 215 216 217
    gboolean bool;
    gint integer;
    gchar *str;
    gchar **array;
218
    gdouble dbl;
219
    gint64 int64;
Anders Carlsson's avatar
Anders Carlsson committed
220
  } prev;
221
  union
222
  {
Anders Carlsson's avatar
Anders Carlsson committed
223
    gchar *str;
224
    struct
225
    {
226
      gint len;
Anders Carlsson's avatar
Anders Carlsson committed
227 228 229 230 231 232 233 234 235 236 237 238 239
      gchar **data;
    } array;
  } allocated;
} Change;

typedef struct
{
  gchar **ptr;
  gchar *value;
} PendingNull;

struct _GOptionContext
{
240
  GList           *groups;
Anders Carlsson's avatar
Anders Carlsson committed
241

242 243 244
  gchar           *parameter_string;
  gchar           *summary;
  gchar           *description;
Anders Carlsson's avatar
Anders Carlsson committed
245

246 247
  GTranslateFunc   translate_func;
  GDestroyNotify   translate_notify;
248
  gpointer         translate_data;
249 250 251

  guint            help_enabled   : 1;
  guint            ignore_unknown : 1;
252
  guint            strv_mode      : 1;
253

254
  GOptionGroup    *main_group;
Anders Carlsson's avatar
Anders Carlsson committed
255 256

  /* We keep a list of change so we can revert them */
257
  GList           *changes;
258 259

  /* We also keep track of all argv elements
260
   * that should be NULLed or modified.
Anders Carlsson's avatar
Anders Carlsson committed
261
   */
262
  GList           *pending_nulls;
Anders Carlsson's avatar
Anders Carlsson committed
263 264 265 266
};

struct _GOptionGroup
{
267 268 269
  gchar           *name;
  gchar           *description;
  gchar           *help_description;
Anders Carlsson's avatar
Anders Carlsson committed
270

271 272
  GDestroyNotify   destroy_notify;
  gpointer         user_data;
Anders Carlsson's avatar
Anders Carlsson committed
273

274 275
  GTranslateFunc   translate_func;
  GDestroyNotify   translate_notify;
276
  gpointer         translate_data;
Anders Carlsson's avatar
Anders Carlsson committed
277

278 279
  GOptionEntry    *entries;
  gint             n_entries;
Anders Carlsson's avatar
Anders Carlsson committed
280 281 282 283 284 285 286

  GOptionParseFunc pre_parse_func;
  GOptionParseFunc post_parse_func;
  GOptionErrorFunc error_func;
};

static void free_changes_list (GOptionContext *context,
287
                               gboolean        revert);
Anders Carlsson's avatar
Anders Carlsson committed
288
static void free_pending_nulls (GOptionContext *context,
289
                                gboolean        perform_nulls);
Anders Carlsson's avatar
Anders Carlsson committed
290

291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306

static int
_g_unichar_get_width (gunichar c)
{
  if (G_UNLIKELY (g_unichar_iszerowidth (c)))
    return 0;

  /* we ignore the fact that we should call g_unichar_iswide_cjk() under
   * some locales (legacy East Asian ones) */
  if (g_unichar_iswide (c))
    return 2;

  return 1;
}

static glong
Matthias Clasen's avatar
Matthias Clasen committed
307
_g_utf8_strwidth (const gchar *p)
308 309
{
  glong len = 0;
Matthias Clasen's avatar
Matthias Clasen committed
310
  g_return_val_if_fail (p != NULL, 0);
311

Matthias Clasen's avatar
Matthias Clasen committed
312
  while (*p)
313 314
    {
      len += _g_unichar_get_width (g_utf8_get_char (p));
315
      p = g_utf8_next_char (p);
316 317 318 319 320
    }

  return len;
}

321
G_DEFINE_QUARK (g-option-context-error-quark, g_option_error)
Anders Carlsson's avatar
Anders Carlsson committed
322

Matthias Clasen's avatar
Matthias Clasen committed
323 324
/**
 * g_option_context_new:
325
 * @parameter_string: (allow-none): a string which is displayed in
Matthias Clasen's avatar
Matthias Clasen committed
326 327
 *    the first line of `--help` output, after the usage summary
 *    `programname [OPTION...]`
Matthias Clasen's avatar
Matthias Clasen committed
328
 *
329
 * Creates a new option context.
Matthias Clasen's avatar
Matthias Clasen committed
330
 *
331
 * The @parameter_string can serve multiple purposes. It can be used
332 333
 * to add descriptions for "rest" arguments, which are not parsed by
 * the #GOptionContext, typically something like "FILES" or
334
 * "FILE1 FILE2...". If you are using #G_OPTION_REMAINING for
335 336
 * collecting "rest" arguments, GLib handles this automatically by
 * using the @arg_description of the corresponding #GOptionEntry in
337 338 339 340 341 342 343
 * the usage summary.
 *
 * Another usage is to give a short summary of the program
 * functionality, like " - frob the strings", which will be displayed
 * in the same line as the usage. For a longer description of the
 * program functionality that should be displayed as a paragraph
 * below the usage line, use g_option_context_set_summary().
344
 *
345 346 347
 * Note that the @parameter_string is translated using the
 * function set with g_option_context_set_translate_func(), so
 * it should normally be passed untranslated.
348
 *
Matthias Clasen's avatar
Matthias Clasen committed
349 350 351 352 353
 * Returns: a newly created #GOptionContext, which must be
 *    freed with g_option_context_free() after use.
 *
 * Since: 2.6
 */
Anders Carlsson's avatar
Anders Carlsson committed
354 355 356 357 358 359 360 361 362 363
GOptionContext *
g_option_context_new (const gchar *parameter_string)

{
  GOptionContext *context;

  context = g_new0 (GOptionContext, 1);

  context->parameter_string = g_strdup (parameter_string);
  context->help_enabled = TRUE;
Matthias Clasen's avatar
Matthias Clasen committed
364
  context->ignore_unknown = FALSE;
Anders Carlsson's avatar
Anders Carlsson committed
365 366 367 368

  return context;
}

Matthias Clasen's avatar
Matthias Clasen committed
369 370
/**
 * g_option_context_free:
371
 * @context: a #GOptionContext
Matthias Clasen's avatar
Matthias Clasen committed
372
 *
373
 * Frees context and all the groups which have been
Matthias Clasen's avatar
Matthias Clasen committed
374 375
 * added to it.
 *
376 377 378
 * Please note that parsed arguments need to be freed separately (see
 * #GOptionEntry).
 *
Matthias Clasen's avatar
Matthias Clasen committed
379 380
 * Since: 2.6
 */
381
void g_option_context_free (GOptionContext *context)
382 383
{
  g_return_if_fail (context != NULL);
Anders Carlsson's avatar
Anders Carlsson committed
384

385
  g_list_free_full (context->groups, (GDestroyNotify) g_option_group_free);
Anders Carlsson's avatar
Anders Carlsson committed
386

387
  if (context->main_group)
388
    g_option_group_free (context->main_group);
Anders Carlsson's avatar
Anders Carlsson committed
389 390 391

  free_changes_list (context, FALSE);
  free_pending_nulls (context, FALSE);
392

Anders Carlsson's avatar
Anders Carlsson committed
393
  g_free (context->parameter_string);
394 395
  g_free (context->summary);
  g_free (context->description);
396

397 398 399
  if (context->translate_notify)
    (* context->translate_notify) (context->translate_data);

Anders Carlsson's avatar
Anders Carlsson committed
400 401 402
  g_free (context);
}

Matthias Clasen's avatar
Matthias Clasen committed
403 404 405 406

/**
 * g_option_context_set_help_enabled:
 * @context: a #GOptionContext
Matthias Clasen's avatar
Matthias Clasen committed
407
 * @help_enabled: %TRUE to enable `--help`, %FALSE to disable it
Matthias Clasen's avatar
Matthias Clasen committed
408
 *
Matthias Clasen's avatar
Matthias Clasen committed
409 410 411 412
 * Enables or disables automatic generation of `--help` output.
 * By default, g_option_context_parse() recognizes `--help`, `-h`,
 * `-?`, `--help-all` and `--help-groupname` and creates suitable
 * output to stdout.
Matthias Clasen's avatar
Matthias Clasen committed
413 414 415 416 417
 *
 * Since: 2.6
 */
void g_option_context_set_help_enabled (GOptionContext *context,
                                        gboolean        help_enabled)
Anders Carlsson's avatar
Anders Carlsson committed
418 419 420 421 422 423 424

{
  g_return_if_fail (context != NULL);

  context->help_enabled = help_enabled;
}

Matthias Clasen's avatar
Matthias Clasen committed
425 426 427
/**
 * g_option_context_get_help_enabled:
 * @context: a #GOptionContext
428
 *
Matthias Clasen's avatar
Matthias Clasen committed
429
 * Returns whether automatic `--help` generation
Matthias Clasen's avatar
Matthias Clasen committed
430
 * is turned on for @context. See g_option_context_set_help_enabled().
431
 *
Matthias Clasen's avatar
Matthias Clasen committed
432 433 434 435
 * Returns: %TRUE if automatic help generation is turned on.
 *
 * Since: 2.6
 */
436 437
gboolean
g_option_context_get_help_enabled (GOptionContext *context)
Anders Carlsson's avatar
Anders Carlsson committed
438 439
{
  g_return_val_if_fail (context != NULL, FALSE);
440

Anders Carlsson's avatar
Anders Carlsson committed
441 442 443
  return context->help_enabled;
}

Matthias Clasen's avatar
Matthias Clasen committed
444 445 446 447 448
/**
 * g_option_context_set_ignore_unknown_options:
 * @context: a #GOptionContext
 * @ignore_unknown: %TRUE to ignore unknown options, %FALSE to produce
 *    an error when unknown options are met
449 450 451
 *
 * Sets whether to ignore unknown options or not. If an argument is
 * ignored, it is left in the @argv array after parsing. By default,
Matthias Clasen's avatar
Matthias Clasen committed
452
 * g_option_context_parse() treats unknown options as error.
453 454
 *
 * This setting does not affect non-option arguments (i.e. arguments
Matthias Clasen's avatar
Matthias Clasen committed
455 456
 * which don't start with a dash). But note that GOption cannot reliably
 * determine whether a non-option belongs to a preceding unknown option.
Matthias Clasen's avatar
Matthias Clasen committed
457 458 459
 *
 * Since: 2.6
 **/
Anders Carlsson's avatar
Anders Carlsson committed
460 461
void
g_option_context_set_ignore_unknown_options (GOptionContext *context,
462
                                             gboolean        ignore_unknown)
Anders Carlsson's avatar
Anders Carlsson committed
463 464 465 466 467 468
{
  g_return_if_fail (context != NULL);

  context->ignore_unknown = ignore_unknown;
}

Matthias Clasen's avatar
Matthias Clasen committed
469 470 471
/**
 * g_option_context_get_ignore_unknown_options:
 * @context: a #GOptionContext
472
 *
Matthias Clasen's avatar
Matthias Clasen committed
473 474
 * Returns whether unknown options are ignored or not. See
 * g_option_context_set_ignore_unknown_options().
475
 *
Matthias Clasen's avatar
Matthias Clasen committed
476
 * Returns: %TRUE if unknown options are ignored.
477
 *
Matthias Clasen's avatar
Matthias Clasen committed
478 479
 * Since: 2.6
 **/
Anders Carlsson's avatar
Anders Carlsson committed
480 481 482 483 484 485 486 487
gboolean
g_option_context_get_ignore_unknown_options (GOptionContext *context)
{
  g_return_val_if_fail (context != NULL, FALSE);

  return context->ignore_unknown;
}

Matthias Clasen's avatar
Matthias Clasen committed
488 489 490 491
/**
 * g_option_context_add_group:
 * @context: a #GOptionContext
 * @group: the group to add
492
 *
Matthias Clasen's avatar
Matthias Clasen committed
493 494 495 496 497 498 499 500
 * Adds a #GOptionGroup to the @context, so that parsing with @context
 * will recognize the options in the group. Note that the group will
 * be freed together with the context when g_option_context_free() is
 * called, so you must not free the group yourself after adding it
 * to a context.
 *
 * Since: 2.6
 **/
Anders Carlsson's avatar
Anders Carlsson committed
501 502
void
g_option_context_add_group (GOptionContext *context,
503
                            GOptionGroup   *group)
Anders Carlsson's avatar
Anders Carlsson committed
504
{
505 506
  GList *list;

Anders Carlsson's avatar
Anders Carlsson committed
507 508 509 510 511 512
  g_return_if_fail (context != NULL);
  g_return_if_fail (group != NULL);
  g_return_if_fail (group->name != NULL);
  g_return_if_fail (group->description != NULL);
  g_return_if_fail (group->help_description != NULL);

513 514 515 516 517
  for (list = context->groups; list; list = list->next)
    {
      GOptionGroup *g = (GOptionGroup *)list->data;

      if ((group->name == NULL && g->name == NULL) ||
518 519 520
          (group->name && g->name && strcmp (group->name, g->name) == 0))
        g_warning ("A group named \"%s\" is already part of this GOptionContext",
                   group->name);
521 522 523
    }

  context->groups = g_list_append (context->groups, group);
Anders Carlsson's avatar
Anders Carlsson committed
524 525
}

Matthias Clasen's avatar
Matthias Clasen committed
526 527 528 529
/**
 * g_option_context_set_main_group:
 * @context: a #GOptionContext
 * @group: the group to set as main group
530 531 532 533
 *
 * Sets a #GOptionGroup as main group of the @context.
 * This has the same effect as calling g_option_context_add_group(),
 * the only difference is that the options in the main group are
Matthias Clasen's avatar
Matthias Clasen committed
534
 * treated differently when generating `--help` output.
Matthias Clasen's avatar
Matthias Clasen committed
535 536 537
 *
 * Since: 2.6
 **/
Anders Carlsson's avatar
Anders Carlsson committed
538 539
void
g_option_context_set_main_group (GOptionContext *context,
540
                                 GOptionGroup   *group)
Anders Carlsson's avatar
Anders Carlsson committed
541 542 543 544
{
  g_return_if_fail (context != NULL);
  g_return_if_fail (group != NULL);

545 546 547 548 549 550
  if (context->main_group)
    {
      g_warning ("This GOptionContext already has a main group");

      return;
    }
551

Anders Carlsson's avatar
Anders Carlsson committed
552 553 554
  context->main_group = group;
}

Matthias Clasen's avatar
Matthias Clasen committed
555 556 557
/**
 * g_option_context_get_main_group:
 * @context: a #GOptionContext
558
 *
Matthias Clasen's avatar
Matthias Clasen committed
559
 * Returns a pointer to the main group of @context.
560
 *
Matthias Clasen's avatar
Matthias Clasen committed
561 562 563 564 565 566
 * Return value: the main group of @context, or %NULL if @context doesn't
 *  have a main group. Note that group belongs to @context and should
 *  not be modified or freed.
 *
 * Since: 2.6
 **/
Anders Carlsson's avatar
Anders Carlsson committed
567 568 569 570 571 572 573 574
GOptionGroup *
g_option_context_get_main_group (GOptionContext *context)
{
  g_return_val_if_fail (context != NULL, NULL);

  return context->main_group;
}

Matthias Clasen's avatar
Matthias Clasen committed
575 576 577
/**
 * g_option_context_add_main_entries:
 * @context: a #GOptionContext
Matthias Clasen's avatar
Matthias Clasen committed
578
 * @entries: a %NULL-terminated array of #GOptionEntrys
579
 * @translation_domain: (allow-none): a translation domain to use for translating
Matthias Clasen's avatar
Matthias Clasen committed
580
 *    the `--help` output for the options in @entries
Matthias Clasen's avatar
Matthias Clasen committed
581
 *    with gettext(), or %NULL
582 583
 *
 * A convenience function which creates a main group if it doesn't
Matthias Clasen's avatar
Matthias Clasen committed
584
 * exist, adds the @entries to it and sets the translation domain.
585
 *
Matthias Clasen's avatar
Matthias Clasen committed
586 587
 * Since: 2.6
 **/
Anders Carlsson's avatar
Anders Carlsson committed
588 589
void
g_option_context_add_main_entries (GOptionContext      *context,
590 591
                                   const GOptionEntry  *entries,
                                   const gchar         *translation_domain)
Anders Carlsson's avatar
Anders Carlsson committed
592 593 594 595 596
{
  g_return_if_fail (entries != NULL);

  if (!context->main_group)
    context->main_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
597

Anders Carlsson's avatar
Anders Carlsson committed
598 599 600 601
  g_option_group_add_entries (context->main_group, entries);
  g_option_group_set_translation_domain (context->main_group, translation_domain);
}

602
static gint
603 604
calculate_max_length (GOptionGroup *group,
                      GHashTable   *aliases)
605 606 607
{
  GOptionEntry *entry;
  gint i, len, max_length;
608
  const gchar *long_name;
609 610 611 612 613 614 615 616

  max_length = 0;

  for (i = 0; i < group->n_entries; i++)
    {
      entry = &group->entries[i];

      if (entry->flags & G_OPTION_FLAG_HIDDEN)
617
        continue;
618

619 620 621 622
      long_name = g_hash_table_lookup (aliases, &entry->long_name);
      if (!long_name)
        long_name = entry->long_name;
      len = _g_utf8_strwidth (long_name);
623

624
      if (entry->short_name)
625 626
        len += 4;

627
      if (!NO_ARG (entry) && entry->arg_description)
Matthias Clasen's avatar
Matthias Clasen committed
628
        len += 1 + _g_utf8_strwidth (TRANSLATE (group, entry->arg_description));
629

630 631 632 633 634 635
      max_length = MAX (max_length, len);
    }

  return max_length;
}

Anders Carlsson's avatar
Anders Carlsson committed
636 637
static void
print_entry (GOptionGroup       *group,
638 639
             gint                max_length,
             const GOptionEntry *entry,
640 641
             GString            *string,
             GHashTable         *aliases)
Anders Carlsson's avatar
Anders Carlsson committed
642 643
{
  GString *str;
644
  const gchar *long_name;
645

Anders Carlsson's avatar
Anders Carlsson committed
646 647
  if (entry->flags & G_OPTION_FLAG_HIDDEN)
    return;
648

649 650 651
  if (entry->long_name[0] == 0)
    return;

652 653 654 655
  long_name = g_hash_table_lookup (aliases, &entry->long_name);
  if (!long_name)
    long_name = entry->long_name;

Anders Carlsson's avatar
Anders Carlsson committed
656
  str = g_string_new (NULL);
657

Anders Carlsson's avatar
Anders Carlsson committed
658
  if (entry->short_name)
659
    g_string_append_printf (str, "  -%c, --%s", entry->short_name, long_name);
Anders Carlsson's avatar
Anders Carlsson committed
660
  else
661
    g_string_append_printf (str, "  --%s", long_name);
662

Anders Carlsson's avatar
Anders Carlsson committed
663 664
  if (entry->arg_description)
    g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
665

666
  g_string_append_printf (string, "%s%*s %s\n", str->str,
Matthias Clasen's avatar
Matthias Clasen committed
667
                          (int) (max_length + 4 - _g_utf8_strwidth (str->str)), "",
668 669
                          entry->description ? TRANSLATE (group, entry->description) : "");
  g_string_free (str, TRUE);
Anders Carlsson's avatar
Anders Carlsson committed
670 671
}

672
static gboolean
673 674
group_has_visible_entries (GOptionContext *context,
                           GOptionGroup *group,
675 676 677 678 679
                           gboolean      main_entries)
{
  GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
  GOptionEntry *entry;
  gint i, l;
680
  gboolean main_group = group == context->main_group;
681 682 683 684 685 686 687 688

  if (!main_entries)
    reject_filter |= G_OPTION_FLAG_IN_MAIN;

  for (i = 0, l = (group ? group->n_entries : 0); i < l; i++)
    {
      entry = &group->entries[i];

689
      if (main_entries && !main_group && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
690
        continue;
691 692
      if (entry->long_name[0] == 0) /* ignore rest entry */
        continue;
693 694 695 696 697 698 699 700
      if (!(entry->flags & reject_filter))
        return TRUE;
    }

  return FALSE;
}

static gboolean
Matthias Clasen's avatar
Matthias Clasen committed
701
group_list_has_visible_entries (GOptionContext *context,
702 703
                                GList          *group_list,
                                gboolean       main_entries)
704 705 706
{
  while (group_list)
    {
707
      if (group_has_visible_entries (context, group_list->data, main_entries))
708 709 710 711 712 713 714 715
        return TRUE;

      group_list = group_list->next;
    }

  return FALSE;
}

716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
static gboolean
context_has_h_entry (GOptionContext *context)
{
  gsize i;
  GList *list;

  if (context->main_group)
    {
      for (i = 0; i < context->main_group->n_entries; i++)
        {
          if (context->main_group->entries[i].short_name == 'h')
            return TRUE;
        }
    }

  for (list = context->groups; list != NULL; list = g_list_next (list))
    {
     GOptionGroup *group;

      group = (GOptionGroup*)list->data;
      for (i = 0; i < group->n_entries; i++)
        {
          if (group->entries[i].short_name == 'h')
            return TRUE;
        }
    }
  return FALSE;
}

745
/**
746
 * g_option_context_get_help:
747
 * @context: a #GOptionContext
748
 * @main_help: if %TRUE, only include the main group
749
 * @group: (allow-none): the #GOptionGroup to create help for, or %NULL
750 751
 *
 * Returns a formatted, translated help text for the given context.
Matthias Clasen's avatar
Matthias Clasen committed
752
 * To obtain the text produced by `--help`, call
Matthias Clasen's avatar
Matthias Clasen committed
753
 * `g_option_context_get_help (context, TRUE, NULL)`.
Matthias Clasen's avatar
Matthias Clasen committed
754
 * To obtain the text produced by `--help-all`, call
Matthias Clasen's avatar
Matthias Clasen committed
755
 * `g_option_context_get_help (context, FALSE, NULL)`.
756
 * To obtain the help text for an option group, call
Matthias Clasen's avatar
Matthias Clasen committed
757
 * `g_option_context_get_help (context, FALSE, group)`.
758 759 760 761 762 763 764
 *
 * Returns: A newly allocated string containing the help text
 *
 * Since: 2.14
 */
gchar *
g_option_context_get_help (GOptionContext *context,
765 766
                           gboolean        main_help,
                           GOptionGroup   *group)
Anders Carlsson's avatar
Anders Carlsson committed
767 768
{
  GList *list;
769
  gint max_length = 0, len;
Anders Carlsson's avatar
Anders Carlsson committed
770
  gint i;
771
  GOptionEntry *entry;
772
  GHashTable *shadow_map;
773
  GHashTable *aliases;
774
  gboolean seen[256];
775
  const gchar *rest_description;
776
  GString *string;
777
  guchar token;
778 779 780

  string = g_string_sized_new (1024);

781 782 783
  rest_description = NULL;
  if (context->main_group)
    {
784

785
      for (i = 0; i < context->main_group->n_entries; i++)
786 787 788 789 790 791 792 793
        {
          entry = &context->main_group->entries[i];
          if (entry->long_name[0] == 0)
            {
              rest_description = TRANSLATE (context->main_group, entry->arg_description);
              break;
            }
        }
794
    }
795

796 797
  g_string_append_printf (string, "%s\n  %s %s",
                          _("Usage:"), g_get_prgname(), _("[OPTION...]"));
798 799 800

  if (rest_description)
    {
801 802
      g_string_append (string, " ");
      g_string_append (string, rest_description);
803 804 805 806
    }

  if (context->parameter_string)
    {
807 808
      g_string_append (string, " ");
      g_string_append (string, TRANSLATE (context, context->parameter_string));
809 810 811
    }

  g_string_append (string, "\n\n");
812 813

  if (context->summary)
814 815 816 817
    {
      g_string_append (string, TRANSLATE (context, context->summary));
      g_string_append (string, "\n\n");
    }
Anders Carlsson's avatar
Anders Carlsson committed
818

819 820
  memset (seen, 0, sizeof (gboolean) * 256);
  shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
821
  aliases = g_hash_table_new_full (NULL, NULL, NULL, g_free);
822 823 824 825

  if (context->main_group)
    {
      for (i = 0; i < context->main_group->n_entries; i++)
826 827 828 829 830 831 832 833 834 835 836
        {
          entry = &context->main_group->entries[i];
          g_hash_table_insert (shadow_map,
                               (gpointer)entry->long_name,
                               entry);

          if (seen[(guchar)entry->short_name])
            entry->short_name = 0;
          else
            seen[(guchar)entry->short_name] = TRUE;
        }
837 838 839 840 841
    }

  list = context->groups;
  while (list != NULL)
    {
Matthias Clasen's avatar
Matthias Clasen committed
842 843
      GOptionGroup *g = list->data;
      for (i = 0; i < g->n_entries; i++)
844 845 846 847
        {
          entry = &g->entries[i];
          if (g_hash_table_lookup (shadow_map, entry->long_name) &&
              !(entry->flags & G_OPTION_FLAG_NOALIAS))
848 849 850 851
            {
              g_hash_table_insert (aliases, &entry->long_name,
                                   g_strdup_printf ("%s-%s", g->name, entry->long_name));
            }
852 853 854 855 856 857 858 859 860
          else
            g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);

          if (seen[(guchar)entry->short_name] &&
              !(entry->flags & G_OPTION_FLAG_NOALIAS))
            entry->short_name = 0;
          else
            seen[(guchar)entry->short_name] = TRUE;
        }
861 862 863 864 865
      list = list->next;
    }

  g_hash_table_destroy (shadow_map);

Anders Carlsson's avatar
Anders Carlsson committed
866 867
  list = context->groups;

868
  if (context->help_enabled)
Anders Carlsson's avatar
Anders Carlsson committed
869
    {
870 871 872 873 874 875 876
      max_length = _g_utf8_strwidth ("-?, --help");

      if (list)
        {
          len = _g_utf8_strwidth ("--help-all");
          max_length = MAX (max_length, len);
        }
Anders Carlsson's avatar
Anders Carlsson committed
877 878
    }

879 880
  if (context->main_group)
    {
881
      len = calculate_max_length (context->main_group, aliases);
882 883 884
      max_length = MAX (max_length, len);
    }

Anders Carlsson's avatar
Anders Carlsson committed
885 886
  while (list != NULL)
    {
Matthias Clasen's avatar
Matthias Clasen committed
887
      GOptionGroup *g = list->data;
888

889 890 891 892 893 894
      if (context->help_enabled)
        {
          /* First, we check the --help-<groupname> options */
          len = _g_utf8_strwidth ("--help-") + _g_utf8_strwidth (g->name);
          max_length = MAX (max_length, len);
        }
Anders Carlsson's avatar
Anders Carlsson committed
895 896

      /* Then we go through the entries */
897
      len = calculate_max_length (g, aliases);
898
      max_length = MAX (max_length, len);
899

Anders Carlsson's avatar
Anders Carlsson committed
900 901 902 903 904 905
      list = list->next;
    }

  /* Add a bit of padding */
  max_length += 4;

906
  if (!group && context->help_enabled)
Anders Carlsson's avatar
Anders Carlsson committed
907
    {
908
      list = context->groups;
909 910 911

      token = context_has_h_entry (context) ? '?' : 'h';

912 913 914 915
      g_string_append_printf (string, "%s\n  -%c, --%-*s %s\n",
                              _("Help Options:"), token, max_length - 4, "help",
                              _("Show help options"));

916 917
      /* We only want --help-all when there are groups */
      if (list)
918 919
        g_string_append_printf (string, "  --%-*s %s\n",
                                max_length, "help-all",
920
                                _("Show all help options"));
921

922
      while (list)
923 924 925 926 927 928 929
        {
          GOptionGroup *g = list->data;

          if (group_has_visible_entries (context, g, FALSE))
            g_string_append_printf (string, "  --help-%-*s %s\n",
                                    max_length - 5, g->name,
                                    TRANSLATE (g, g->help_description));
930

931 932
          list = list->next;
        }
933

934
      g_string_append (string, "\n");
935
    }
Anders Carlsson's avatar
Anders Carlsson committed
936 937 938 939

  if (group)
    {
      /* Print a certain group */
940

941
      if (group_has_visible_entries (context, group, FALSE))
942 943 944 945
        {
          g_string_append (string, TRANSLATE (group, group->description));
          g_string_append (string, "\n");
          for (i = 0; i < group->n_entries; i++)
946
            print_entry (group, max_length, &group->entries[i], string, aliases);
947 948
          g_string_append (string, "\n");
        }
Anders Carlsson's avatar
Anders Carlsson committed
949 950 951 952 953 954 955 956
    }
  else if (!main_help)
    {
      /* Print all groups */

      list = context->groups;

      while (list)
957 958 959 960 961 962 963 964 965
        {
          GOptionGroup *g = list->data;

          if (group_has_visible_entries (context, g, FALSE))
            {
              g_string_append (string, g->description);
              g_string_append (string, "\n");
              for (i = 0; i < g->n_entries; i++)
                if (!(g->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
966
                  print_entry (g, max_length, &g->entries[i], string, aliases);
967 968 969 970 971 972

              g_string_append (string, "\n");
            }

          list = list->next;
        }
Anders Carlsson's avatar
Anders Carlsson committed
973
    }
974

Anders Carlsson's avatar
Anders Carlsson committed
975
  /* Print application options if --help or --help-all has been specified */
976
  if ((main_help || !group) &&
977
      (group_has_visible_entries (context, context->main_group, TRUE) ||