goption.c 78.3 KB
Newer Older
Anders Carlsson's avatar
Anders Carlsson committed
1
2
3
4
5
6
/* 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
7
 * modify it under the terms of the GNU Lesser General Public
Anders Carlsson's avatar
Anders Carlsson committed
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
Anders Carlsson's avatar
Anders Carlsson committed
10
11
12
 *
 * 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
14
 * Lesser General Public License for more details.
Anders Carlsson's avatar
Anders Carlsson committed
15
 *
16
17
 * You should have received a copy of the GNU Lesser General Public 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
 *
Matthias Clasen's avatar
Matthias Clasen committed
123
 *   ...
124
 *
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
 * 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
 *
Matthias Clasen's avatar
Matthias Clasen committed
164
 *   // set up context
165
166
167
 *
 *   if (!g_option_context_parse_strv (context, &args, &error))
 *     {
Matthias Clasen's avatar
Matthias Clasen committed
168
 *       // error happened
169
170
 *     }
 *
Matthias Clasen's avatar
Matthias Clasen committed
171
 *   ...
172
173
174
 *
 *   g_strfreev (args);
 *
Matthias Clasen's avatar
Matthias Clasen committed
175
 *   ...
176
177
 * }
 * ]|
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
#if defined __OpenBSD__
#include <unistd.h>
#include <sys/sysctl.h>
#endif

192
193
194
195
196
#include "goption.h"

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

197
198
199
200
#if defined G_OS_WIN32
#include <windows.h>
#endif

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

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

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

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

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

struct _GOptionContext
{
242
  GList           *groups;
Anders Carlsson's avatar
Anders Carlsson committed
243

244
  gchar           *parameter_string;  /* (nullable) */
245
246
  gchar           *summary;
  gchar           *description;
Anders Carlsson's avatar
Anders Carlsson committed
247

248
249
  GTranslateFunc   translate_func;
  GDestroyNotify   translate_notify;
250
  gpointer         translate_data;
251
252
253

  guint            help_enabled   : 1;
  guint            ignore_unknown : 1;
254
  guint            strv_mode      : 1;
255
  guint            strict_posix   : 1;
256

257
  GOptionGroup    *main_group;
Anders Carlsson's avatar
Anders Carlsson committed
258
259

  /* We keep a list of change so we can revert them */
260
  GList           *changes;
261
262

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

struct _GOptionGroup
{
270
271
272
  gchar           *name;
  gchar           *description;
  gchar           *help_description;
Anders Carlsson's avatar
Anders Carlsson committed
273

274
275
  gint             ref_count;

276
277
  GDestroyNotify   destroy_notify;
  gpointer         user_data;
Anders Carlsson's avatar
Anders Carlsson committed
278

279
280
  GTranslateFunc   translate_func;
  GDestroyNotify   translate_notify;
281
  gpointer         translate_data;
Anders Carlsson's avatar
Anders Carlsson committed
282

283
  GOptionEntry    *entries;
284
  gsize            n_entries;
Anders Carlsson's avatar
Anders Carlsson committed
285
286
287
288
289
290
291

  GOptionParseFunc pre_parse_func;
  GOptionParseFunc post_parse_func;
  GOptionErrorFunc error_func;
};

static void free_changes_list (GOptionContext *context,
292
                               gboolean        revert);
Anders Carlsson's avatar
Anders Carlsson committed
293
static void free_pending_nulls (GOptionContext *context,
294
                                gboolean        perform_nulls);
Anders Carlsson's avatar
Anders Carlsson committed
295

296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311

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
312
_g_utf8_strwidth (const gchar *p)
313
314
{
  glong len = 0;
Matthias Clasen's avatar
Matthias Clasen committed
315
  g_return_val_if_fail (p != NULL, 0);
316

Matthias Clasen's avatar
Matthias Clasen committed
317
  while (*p)
318
319
    {
      len += _g_unichar_get_width (g_utf8_get_char (p));
320
      p = g_utf8_next_char (p);
321
322
323
324
325
    }

  return len;
}

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

Matthias Clasen's avatar
Matthias Clasen committed
328
329
/**
 * g_option_context_new:
330
 * @parameter_string: (nullable): a string which is displayed in
Matthias Clasen's avatar
Matthias Clasen committed
331
332
 *    the first line of `--help` output, after the usage summary
 *    `programname [OPTION...]`
Matthias Clasen's avatar
Matthias Clasen committed
333
 *
334
 * Creates a new option context.
Matthias Clasen's avatar
Matthias Clasen committed
335
 *
336
 * The @parameter_string can serve multiple purposes. It can be used
337
338
 * to add descriptions for "rest" arguments, which are not parsed by
 * the #GOptionContext, typically something like "FILES" or
339
 * "FILE1 FILE2...". If you are using #G_OPTION_REMAINING for
340
341
 * collecting "rest" arguments, GLib handles this automatically by
 * using the @arg_description of the corresponding #GOptionEntry in
342
343
344
345
346
347
348
 * 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().
349
 *
350
351
352
 * 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.
353
 *
Matthias Clasen's avatar
Matthias Clasen committed
354
355
356
357
358
 * 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
359
360
361
362
363
364
365
366
GOptionContext *
g_option_context_new (const gchar *parameter_string)

{
  GOptionContext *context;

  context = g_new0 (GOptionContext, 1);

367
368
369
370
371
  /* Clear the empty string to NULL, otherwise we end up calling gettext(""),
   * which returns the translation header. */
  if (parameter_string != NULL && *parameter_string == '\0')
    parameter_string = NULL;

Anders Carlsson's avatar
Anders Carlsson committed
372
  context->parameter_string = g_strdup (parameter_string);
373
  context->strict_posix = FALSE;
Anders Carlsson's avatar
Anders Carlsson committed
374
  context->help_enabled = TRUE;
Matthias Clasen's avatar
Matthias Clasen committed
375
  context->ignore_unknown = FALSE;
Anders Carlsson's avatar
Anders Carlsson committed
376
377
378
379

  return context;
}

Matthias Clasen's avatar
Matthias Clasen committed
380
381
/**
 * g_option_context_free:
382
 * @context: a #GOptionContext
Matthias Clasen's avatar
Matthias Clasen committed
383
 *
384
 * Frees context and all the groups which have been
Matthias Clasen's avatar
Matthias Clasen committed
385
386
 * added to it.
 *
387
388
389
 * Please note that parsed arguments need to be freed separately (see
 * #GOptionEntry).
 *
Matthias Clasen's avatar
Matthias Clasen committed
390
391
 * Since: 2.6
 */
392
void g_option_context_free (GOptionContext *context)
393
394
{
  g_return_if_fail (context != NULL);
Anders Carlsson's avatar
Anders Carlsson committed
395

396
  g_list_free_full (context->groups, (GDestroyNotify) g_option_group_unref);
Anders Carlsson's avatar
Anders Carlsson committed
397

398
  if (context->main_group)
399
    g_option_group_unref (context->main_group);
Anders Carlsson's avatar
Anders Carlsson committed
400
401
402

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

Anders Carlsson's avatar
Anders Carlsson committed
404
  g_free (context->parameter_string);
405
406
  g_free (context->summary);
  g_free (context->description);
407

408
409
410
  if (context->translate_notify)
    (* context->translate_notify) (context->translate_data);

Anders Carlsson's avatar
Anders Carlsson committed
411
412
413
  g_free (context);
}

Matthias Clasen's avatar
Matthias Clasen committed
414
415
416
417

/**
 * g_option_context_set_help_enabled:
 * @context: a #GOptionContext
Matthias Clasen's avatar
Matthias Clasen committed
418
 * @help_enabled: %TRUE to enable `--help`, %FALSE to disable it
Matthias Clasen's avatar
Matthias Clasen committed
419
 *
Matthias Clasen's avatar
Matthias Clasen committed
420
421
422
423
 * 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
424
425
426
427
428
 *
 * Since: 2.6
 */
void g_option_context_set_help_enabled (GOptionContext *context,
                                        gboolean        help_enabled)
Anders Carlsson's avatar
Anders Carlsson committed
429
430
431
432
433
434
435

{
  g_return_if_fail (context != NULL);

  context->help_enabled = help_enabled;
}

Matthias Clasen's avatar
Matthias Clasen committed
436
437
438
/**
 * g_option_context_get_help_enabled:
 * @context: a #GOptionContext
439
 *
Matthias Clasen's avatar
Matthias Clasen committed
440
 * Returns whether automatic `--help` generation
Matthias Clasen's avatar
Matthias Clasen committed
441
 * is turned on for @context. See g_option_context_set_help_enabled().
442
 *
Matthias Clasen's avatar
Matthias Clasen committed
443
444
445
446
 * Returns: %TRUE if automatic help generation is turned on.
 *
 * Since: 2.6
 */
447
448
gboolean
g_option_context_get_help_enabled (GOptionContext *context)
Anders Carlsson's avatar
Anders Carlsson committed
449
450
{
  g_return_val_if_fail (context != NULL, FALSE);
451

Anders Carlsson's avatar
Anders Carlsson committed
452
453
454
  return context->help_enabled;
}

Matthias Clasen's avatar
Matthias Clasen committed
455
456
457
458
459
/**
 * 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
460
461
462
 *
 * 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
463
 * g_option_context_parse() treats unknown options as error.
464
465
 *
 * This setting does not affect non-option arguments (i.e. arguments
Matthias Clasen's avatar
Matthias Clasen committed
466
467
 * 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
468
469
470
 *
 * Since: 2.6
 **/
Anders Carlsson's avatar
Anders Carlsson committed
471
472
void
g_option_context_set_ignore_unknown_options (GOptionContext *context,
473
                                             gboolean        ignore_unknown)
Anders Carlsson's avatar
Anders Carlsson committed
474
475
476
477
478
479
{
  g_return_if_fail (context != NULL);

  context->ignore_unknown = ignore_unknown;
}

Matthias Clasen's avatar
Matthias Clasen committed
480
481
482
/**
 * g_option_context_get_ignore_unknown_options:
 * @context: a #GOptionContext
483
 *
Matthias Clasen's avatar
Matthias Clasen committed
484
485
 * Returns whether unknown options are ignored or not. See
 * g_option_context_set_ignore_unknown_options().
486
 *
Matthias Clasen's avatar
Matthias Clasen committed
487
 * Returns: %TRUE if unknown options are ignored.
488
 *
Matthias Clasen's avatar
Matthias Clasen committed
489
490
 * Since: 2.6
 **/
Anders Carlsson's avatar
Anders Carlsson committed
491
492
493
494
495
496
497
498
gboolean
g_option_context_get_ignore_unknown_options (GOptionContext *context)
{
  g_return_val_if_fail (context != NULL, FALSE);

  return context->ignore_unknown;
}

499
500
/**
 * g_option_context_set_strict_posix:
501
 * @context: a #GOptionContext
502
 * @strict_posix: the new value
503
504
505
 *
 * Sets strict POSIX mode.
 *
506
507
 * By default, this mode is disabled.
 *
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
 * In strict POSIX mode, the first non-argument parameter encountered
 * (eg: filename) terminates argument processing.  Remaining arguments
 * are treated as non-options and are not attempted to be parsed.
 *
 * If strict POSIX mode is disabled then parsing is done in the GNU way
 * where option arguments can be freely mixed with non-options.
 *
 * As an example, consider "ls foo -l".  With GNU style parsing, this
 * will list "foo" in long mode.  In strict POSIX style, this will list
 * the files named "foo" and "-l".
 *
 * It may be useful to force strict POSIX mode when creating "verb
 * style" command line tools.  For example, the "gsettings" command line
 * tool supports the global option "--schemadir" as well as many
 * subcommands ("get", "set", etc.) which each have their own set of
 * arguments.  Using strict POSIX mode will allow parsing the global
 * options up to the verb name while leaving the remaining options to be
 * parsed by the relevant subcommand (which can be determined by
 * examining the verb name, which should be present in argv[1] after
 * parsing).
 *
 * Since: 2.44
 **/
void
g_option_context_set_strict_posix (GOptionContext *context,
                                   gboolean        strict_posix)
{
  g_return_if_fail (context != NULL);

  context->strict_posix = strict_posix;
}

/**
 * g_option_context_get_strict_posix:
542
 * @context: a #GOptionContext
543
544
545
546
547
 *
 * Returns whether strict POSIX code is enabled.
 *
 * See g_option_context_set_strict_posix() for more information.
 *
548
549
 * Returns: %TRUE if strict POSIX is enabled, %FALSE otherwise.
 *
550
551
552
553
554
555
556
557
558
559
 * Since: 2.44
 **/
gboolean
g_option_context_get_strict_posix (GOptionContext *context)
{
  g_return_val_if_fail (context != NULL, FALSE);

  return context->strict_posix;
}

Matthias Clasen's avatar
Matthias Clasen committed
560
561
562
/**
 * g_option_context_add_group:
 * @context: a #GOptionContext
563
 * @group: (transfer full): the group to add
564
 *
Matthias Clasen's avatar
Matthias Clasen committed
565
 * Adds a #GOptionGroup to the @context, so that parsing with @context
566
567
 * will recognize the options in the group. Note that this will take
 * ownership of the @group and thus the @group should not be freed.
Matthias Clasen's avatar
Matthias Clasen committed
568
569
570
 *
 * Since: 2.6
 **/
Anders Carlsson's avatar
Anders Carlsson committed
571
572
void
g_option_context_add_group (GOptionContext *context,
573
                            GOptionGroup   *group)
Anders Carlsson's avatar
Anders Carlsson committed
574
{
575
576
  GList *list;

Anders Carlsson's avatar
Anders Carlsson committed
577
578
579
580
581
582
  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);

583
584
585
586
587
  for (list = context->groups; list; list = list->next)
    {
      GOptionGroup *g = (GOptionGroup *)list->data;

      if ((group->name == NULL && g->name == NULL) ||
588
589
590
          (group->name && g->name && strcmp (group->name, g->name) == 0))
        g_warning ("A group named \"%s\" is already part of this GOptionContext",
                   group->name);
591
592
593
    }

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

Matthias Clasen's avatar
Matthias Clasen committed
596
597
598
/**
 * g_option_context_set_main_group:
 * @context: a #GOptionContext
599
 * @group: (transfer full): the group to set as main group
600
601
602
603
 *
 * 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
604
 * treated differently when generating `--help` output.
Matthias Clasen's avatar
Matthias Clasen committed
605
606
607
 *
 * Since: 2.6
 **/
Anders Carlsson's avatar
Anders Carlsson committed
608
609
void
g_option_context_set_main_group (GOptionContext *context,
610
                                 GOptionGroup   *group)
Anders Carlsson's avatar
Anders Carlsson committed
611
612
613
614
{
  g_return_if_fail (context != NULL);
  g_return_if_fail (group != NULL);

615
616
617
618
619
620
  if (context->main_group)
    {
      g_warning ("This GOptionContext already has a main group");

      return;
    }
621

Anders Carlsson's avatar
Anders Carlsson committed
622
623
624
  context->main_group = group;
}

Matthias Clasen's avatar
Matthias Clasen committed
625
626
627
/**
 * g_option_context_get_main_group:
 * @context: a #GOptionContext
628
 *
Matthias Clasen's avatar
Matthias Clasen committed
629
 * Returns a pointer to the main group of @context.
630
 *
631
632
633
 * Returns: (transfer none): 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.
Matthias Clasen's avatar
Matthias Clasen committed
634
635
636
 *
 * Since: 2.6
 **/
Anders Carlsson's avatar
Anders Carlsson committed
637
638
639
640
641
642
643
644
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
645
646
647
/**
 * g_option_context_add_main_entries:
 * @context: a #GOptionContext
648
 * @entries: (array zero-terminated=1): a %NULL-terminated array of #GOptionEntrys
649
 * @translation_domain: (nullable): a translation domain to use for translating
Matthias Clasen's avatar
Matthias Clasen committed
650
 *    the `--help` output for the options in @entries
Matthias Clasen's avatar
Matthias Clasen committed
651
 *    with gettext(), or %NULL
652
653
 *
 * A convenience function which creates a main group if it doesn't
Matthias Clasen's avatar
Matthias Clasen committed
654
 * exist, adds the @entries to it and sets the translation domain.
655
 *
Matthias Clasen's avatar
Matthias Clasen committed
656
657
 * Since: 2.6
 **/
Anders Carlsson's avatar
Anders Carlsson committed
658
659
void
g_option_context_add_main_entries (GOptionContext      *context,
660
661
                                   const GOptionEntry  *entries,
                                   const gchar         *translation_domain)
Anders Carlsson's avatar
Anders Carlsson committed
662
{
663
  g_return_if_fail (context != NULL);
Anders Carlsson's avatar
Anders Carlsson committed
664
665
666
667
  g_return_if_fail (entries != NULL);

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

Anders Carlsson's avatar
Anders Carlsson committed
669
670
671
672
  g_option_group_add_entries (context->main_group, entries);
  g_option_group_set_translation_domain (context->main_group, translation_domain);
}

673
static gint
674
675
calculate_max_length (GOptionGroup *group,
                      GHashTable   *aliases)
676
677
{
  GOptionEntry *entry;
678
  gsize i, len, max_length;
679
  const gchar *long_name;
680
681
682
683
684
685
686
687

  max_length = 0;

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

      if (entry->flags & G_OPTION_FLAG_HIDDEN)
688
        continue;
689

690
691
692
693
      long_name = g_hash_table_lookup (aliases, &entry->long_name);
      if (!long_name)
        long_name = entry->long_name;
      len = _g_utf8_strwidth (long_name);
694

695
      if (entry->short_name)
696
697
        len += 4;

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

701
702
703
704
705
706
      max_length = MAX (max_length, len);
    }

  return max_length;
}

Anders Carlsson's avatar
Anders Carlsson committed
707
708
static void
print_entry (GOptionGroup       *group,
709
710
             gint                max_length,
             const GOptionEntry *entry,
711
712
             GString            *string,
             GHashTable         *aliases)
Anders Carlsson's avatar
Anders Carlsson committed
713
714
{
  GString *str;
715
  const gchar *long_name;
716

Anders Carlsson's avatar
Anders Carlsson committed
717
718
  if (entry->flags & G_OPTION_FLAG_HIDDEN)
    return;
719

720
721
722
  if (entry->long_name[0] == 0)
    return;

723
724
725
726
  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
727
  str = g_string_new (NULL);
728

Anders Carlsson's avatar
Anders Carlsson committed
729
  if (entry->short_name)
730
    g_string_append_printf (str, "  -%c, --%s", entry->short_name, long_name);
Anders Carlsson's avatar
Anders Carlsson committed
731
  else
732
    g_string_append_printf (str, "  --%s", long_name);
733

Anders Carlsson's avatar
Anders Carlsson committed
734
735
  if (entry->arg_description)
    g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
736

737
  g_string_append_printf (string, "%s%*s %s\n", str->str,
Matthias Clasen's avatar
Matthias Clasen committed
738
                          (int) (max_length + 4 - _g_utf8_strwidth (str->str)), "",
739
740
                          entry->description ? TRANSLATE (group, entry->description) : "");
  g_string_free (str, TRUE);
Anders Carlsson's avatar
Anders Carlsson committed
741
742
}

743
static gboolean
744
745
group_has_visible_entries (GOptionContext *context,
                           GOptionGroup *group,
746
747
748
749
750
                           gboolean      main_entries)
{
  GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
  GOptionEntry *entry;
  gint i, l;
751
  gboolean main_group = group == context->main_group;
752
753
754
755
756
757
758
759

  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];

760
      if (main_entries && !main_group && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
761
        continue;
762
763
      if (entry->long_name[0] == 0) /* ignore rest entry */
        continue;
764
765
766
767
768
769
770
771
      if (!(entry->flags & reject_filter))
        return TRUE;
    }

  return FALSE;
}

static gboolean
Matthias Clasen's avatar
Matthias Clasen committed
772
group_list_has_visible_entries (GOptionContext *context,
773
774
                                GList          *group_list,
                                gboolean       main_entries)
775
776
777
{
  while (group_list)
    {
778
      if (group_has_visible_entries (context, group_list->data, main_entries))
779
780
781
782
783
784
785
786
        return TRUE;

      group_list = group_list->next;
    }

  return FALSE;
}

787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
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;
}

816
/**
817
 * g_option_context_get_help:
818
 * @context: a #GOptionContext
819
 * @main_help: if %TRUE, only include the main group
820
 * @group: (nullable): the #GOptionGroup to create help for, or %NULL
821
822
 *
 * Returns a formatted, translated help text for the given context.
Matthias Clasen's avatar
Matthias Clasen committed
823
 * To obtain the text produced by `--help`, call
Matthias Clasen's avatar
Matthias Clasen committed
824
 * `g_option_context_get_help (context, TRUE, NULL)`.
Matthias Clasen's avatar
Matthias Clasen committed
825
 * To obtain the text produced by `--help-all`, call
Matthias Clasen's avatar
Matthias Clasen committed
826
 * `g_option_context_get_help (context, FALSE, NULL)`.
827
 * To obtain the help text for an option group, call
Matthias Clasen's avatar
Matthias Clasen committed
828
 * `g_option_context_get_help (context, FALSE, group)`.
829
830
831
832
833
834
835
 *
 * Returns: A newly allocated string containing the help text
 *
 * Since: 2.14
 */
gchar *
g_option_context_get_help (GOptionContext *context,
836
837
                           gboolean        main_help,
                           GOptionGroup   *group)
Anders Carlsson's avatar
Anders Carlsson committed
838
839
{
  GList *list;
840
  gint max_length = 0, len;
841
  gsize i;
842
  GOptionEntry *entry;
843
  GHashTable *shadow_map;
844
  GHashTable *aliases;
845
  gboolean seen[256];
846
  const gchar *rest_description;
847
  GString *string;
848
  guchar token;
849

850
851
  g_return_val_if_fail (context != NULL, NULL);

852
853
  string = g_string_sized_new (1024);

854
855
856
  rest_description = NULL;
  if (context->main_group)
    {
857

858
      for (i = 0; i < context->main_group->n_entries; i++)
859
860
861
862
863
864
865
866
        {
          entry = &context->main_group->entries[i];
          if (entry->long_name[0] == 0)
            {
              rest_description = TRANSLATE (context->main_group, entry->arg_description);
              break;
            }
        }
867
    }
868

869
  g_string_append_printf (string, "%s\n  %s", _("Usage:"), g_get_prgname ());
870
  if (context->help_enabled ||
871
      (context->main_group && context->main_group->n_entries > 0) ||
872
      context->groups != NULL)
873
    g_string_append_printf (string, " %s", _("[OPTION…]"));
874
875
876

  if (rest_description)
    {
877
878
      g_string_append (string, " ");
      g_string_append (string, rest_description);
879
880
881
882
    }

  if (context->parameter_string)
    {
883
884
      g_string_append (string, " ");
      g_string_append (string, TRANSLATE (context, context->parameter_string));
885
886
887
    }

  g_string_append (string, "\n\n");
888
889

  if (context->summary)
890
891
892
893
    {
      g_string_append (string, TRANSLATE (context, context->summary));
      g_string_append (string, "\n\n");
    }
Anders Carlsson's avatar
Anders Carlsson committed
894

895
896
  memset (seen, 0, sizeof (gboolean) * 256);
  shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
897
  aliases = g_hash_table_new_full (NULL, NULL, NULL, g_free);
898
899
900
901

  if (context->main_group)
    {
      for (i = 0; i < context->main_group->n_entries; i++)
902
903
904
905
906
907
908
909
910
911
912
        {
          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;
        }
913
914
915
916
917
    }

  list = context->groups;
  while (list != NULL)
    {
Matthias Clasen's avatar
Matthias Clasen committed
918
919
      GOptionGroup *g = list->data;
      for (i = 0; i < g->n_entries; i++)
920
921
922
923
        {
          entry = &g->entries[i];
          if (g_hash_table_lookup (shadow_map, entry->long_name) &&
              !(entry->flags & G_OPTION_FLAG_NOALIAS))
924
925
926
927
            {
              g_hash_table_insert (aliases, &entry->long_name,
                                   g_strdup_printf ("%s-%s", g->name, entry->long_name));
            }
928
929
930
931
932
933
934
935
936
          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;
        }
937
938
939
940
941
      list = list->next;
    }

  g_hash_table_destroy (shadow_map);

Anders Carlsson's avatar
Anders Carlsson committed
942
943
  list = context->groups;

944
  if (context->help_enabled)
Anders Carlsson's avatar
Anders Carlsson committed
945
    {
946
947
948
949
950
951
952
      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
953
954
    }

955
956
  if (context->main_group)
    {
957
      len = calculate_max_length (context->main_group, aliases);
958
959
960
      max_length = MAX (max_length, len);
    }

Anders Carlsson's avatar
Anders Carlsson committed
961
962
  while (list != NULL)
    {
Matthias Clasen's avatar
Matthias Clasen committed
963
      GOptionGroup *g = list->data;
964

965
966
967
968
969
970
      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
971
972

      /* Then we go through the entries */
973
      len = calculate_max_length (g, aliases);
974
      max_length = MAX (max_length, len);
975

Anders Carlsson's avatar
Anders Carlsson committed
976
977
978
979
980
981
      list = list->next;
    }

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

982
  if (!group && context->help_enabled)
Anders Carlsson's avatar
Anders Carlsson committed
983
    {
984
      list = context->groups;
985
986
987

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

988
989
990
991
      g_string_append_printf (string, "%s\n  -%c, --%-*s %s\n",
                              _("Help Options:"), token, max_length - 4, "help",
                              _("Show help options"));

992
993
      /* We only want --help-all when there are groups */
      if (list)
994
995
        g_string_append_printf (string, "  --%-*s %s\n",
                                max_length, "help-all",
996
                                _("Show all help options"));
997

998
      while (list)
999
1000
1001
1002
1003
1004
1005
        {
          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));
1006

1007
1008
          list = list->next;
        }
1009

1010
      g_string_append (string, "\n");
1011
    }
Anders Carlsson's avatar
Anders Carlsson committed
1012
1013
1014
1015

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

1017
      if (group_has_visible_entries (context, group, FALSE))
1018
1019
1020
1021
        {
          g_string_append (string, TRANSLATE (group, group->description));
          g_string_append (string, "\n");
          for (i = 0; i < group->n_entries; i++)
1022
            print_entry (group, max_length, &group->entries[i], string, aliases);
1023
1024
          g_string_append (string, "\n");
        }
Anders Carlsson's avatar
Anders Carlsson committed
1025
1026
1027
1028
1029
1030
1031
1032
    }
  else if (!main_help)
    {
      /* Print all groups */

      list = context->groups;

      while (list)
1033
1034
1035
1036
1037
1038
1039
1040
1041
        {
          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))
1042
                  print_entry (g, max_length, &g->entries[i], string, aliases);
1043
1044
1045
1046
1047
1048

              g_string_append (string, "\n");
            }

          list = list->next;
        }
Anders Carlsson's avatar
Anders Carlsson committed
1049
    }
1050

Anders Carlsson's avatar
Anders Carlsson committed
1051
  /* Print application options if --help or --help-all has been specified */
1052
  if ((main_help || !group) &&
1053
      (group_has_visible_entries (context, context->main_group, TRUE) ||
Matthias Clasen's avatar
Matthias Clasen committed
1054
       group_list_has_visible_entries (context, context->groups, TRUE)))
Anders Carlsson's avatar
Anders Carlsson committed
1055
1056
1057
    {
      list = context->groups;

1058
1059
1060
1061
      if (context->help_enabled || list)
        g_string_append (string,  _("Application Options:"));
      else
        g_string_append (string, _("Options:"));
1062
      g_string_append (string, "\n");
1063
      if (context->main_group)
1064
1065
        for (i = 0; i < context->main_group->n_entries; i++)
          print_entry (context->main_group, max_length,
1066
                       &context->main_group->entries[i], string, aliases);
Anders Carlsson's avatar
Anders Carlsson committed
1067
1068

      while (list != NULL)
1069
1070
1071
1072
1073
1074
        {
          GOptionGroup *g = list->data;

          /* Print main entries from other groups */
          for (i = 0; i < g->n_entries; i++)
            if (g->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
1075
              print_entry (g, max_length, &g->entries[i], string, aliases);
Anders Carlsson's avatar
Anders Carlsson committed
1076

1077
1078
          list = list->next;
        }
Anders Carlsson's avatar
Anders Carlsson committed
1079

1080
      g_string_append (string, "\n");
Anders Carlsson's avatar
Anders Carlsson committed
1081
    }
1082

1083
  if (context->description)
1084
1085
1086
1087
1088
    {
      g_string_append (string, TRANSLATE (context, context->description));
      g_string_append (string, "\n");
    }

1089
1090
  g_hash_table_destroy (aliases);

1091
1092
1093
  return g_string_free (string, FALSE);
}

Matthias Clasen's avatar
Matthias Clasen committed
1094
G_GNUC_NORETURN
1095
1096
static void
print_help (GOptionContext *context,
1097
1098
            gboolean        main_help,
            GOptionGroup   *group)
1099
1100
1101
1102
{
  gchar *help;

  help = g_option_context_get_help (context, main_help, group);