Don't show help options when help is disabled
[platform/upstream/glib.git] / glib / goption.c
1 /* goption.c - Option parser
2  *
3  *  Copyright (C) 1999, 2003 Red Hat Software
4  *  Copyright (C) 2004       Anders Carlsson <andersca@gnome.org>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 /**
23  * SECTION:option
24  * @Short_description: parses commandline options
25  * @Title: Commandline option parser
26  *
27  * The GOption commandline parser is intended to be a simpler replacement
28  * for the popt library. It supports short and long commandline options,
29  * as shown in the following example:
30  *
31  * <literal>testtreemodel -r 1 --max-size 20 --rand --display=:1.0 -vb -- file1 file2</literal>
32  *
33  * The example demonstrates a number of features of the GOption
34  * commandline parser
35  * <itemizedlist><listitem><para>
36  *   Options can be single letters, prefixed by a single dash. Multiple
37  *   short options can be grouped behind a single dash.
38  * </para></listitem><listitem><para>
39  *   Long options are prefixed by two consecutive dashes.
40  * </para></listitem><listitem><para>
41  *   Options can have an extra argument, which can be a number, a string or
42  *   a filename. For long options, the extra argument can be appended with
43  *   an equals sign after the option name, which is useful if the extra
44  *   argument starts with a dash, which would otherwise cause it to be
45  *   interpreted as another option.
46  * </para></listitem><listitem><para>
47  *   Non-option arguments are returned to the application as rest arguments.
48  * </para></listitem><listitem><para>
49  *   An argument consisting solely of two dashes turns off further parsing,
50  *   any remaining arguments (even those starting with a dash) are returned
51  *   to the application as rest arguments.
52  * </para></listitem></itemizedlist>
53  *
54  * Another important feature of GOption is that it can automatically
55  * generate nicely formatted help output. Unless it is explicitly turned
56  * off with g_option_context_set_help_enabled(), GOption will recognize
57  * the <option>--help</option>, <option>-?</option>,
58  * <option>--help-all</option> and
59  * <option>--help-</option><replaceable>groupname</replaceable> options
60  * (where <replaceable>groupname</replaceable> is the name of a
61  * #GOptionGroup) and write a text similar to the one shown in the
62  * following example to stdout.
63  *
64  * <informalexample><screen>
65  * Usage:
66  *   testtreemodel [OPTION...] - test tree model performance
67  *  
68  * Help Options:
69  *   -h, --help               Show help options
70  *   --help-all               Show all help options
71  *   --help-gtk               Show GTK+ Options
72  *  
73  * Application Options:
74  *   -r, --repeats=N          Average over N repetitions
75  *   -m, --max-size=M         Test up to 2^M items
76  *   --display=DISPLAY        X display to use
77  *   -v, --verbose            Be verbose
78  *   -b, --beep               Beep when done
79  *   --rand                   Randomize the data
80  * </screen></informalexample>
81  *
82  * GOption groups options in #GOptionGroup<!-- -->s, which makes it easy to
83  * incorporate options from multiple sources. The intended use for this is
84  * to let applications collect option groups from the libraries it uses,
85  * add them to their #GOptionContext, and parse all options by a single call
86  * to g_option_context_parse(). See gtk_get_option_group() for an example.
87  *
88  * If an option is declared to be of type string or filename, GOption takes
89  * care of converting it to the right encoding; strings are returned in
90  * UTF-8, filenames are returned in the GLib filename encoding. Note that
91  * this only works if setlocale() has been called before
92  * g_option_context_parse().
93  *
94  * Here is a complete example of setting up GOption to parse the example
95  * commandline above and produce the example help output.
96  *
97  * <informalexample><programlisting>
98  * static gint repeats = 2;
99  * static gint max_size = 8;
100  * static gboolean verbose = FALSE;
101  * static gboolean beep = FALSE;
102  * static gboolean rand = FALSE;
103  *
104  * static GOptionEntry entries[] =
105  * {
106  *   { "repeats", 'r', 0, G_OPTION_ARG_INT, &repeats, "Average over N repetitions", "N" },
107  *   { "max-size", 'm', 0, G_OPTION_ARG_INT, &max_size, "Test up to 2^M items", "M" },
108  *   { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Be verbose", NULL },
109  *   { "beep", 'b', 0, G_OPTION_ARG_NONE, &beep, "Beep when done", NULL },
110  *   { "rand", 0, 0, G_OPTION_ARG_NONE, &rand, "Randomize the data", NULL },
111  *   { NULL }
112  * };
113  *
114  * int
115  * main (int argc, char *argv[])
116  * {
117  *   GError *error = NULL;
118  *   GOptionContext *context;
119  *
120  *   context = g_option_context_new ("- test tree model performance");
121  *   g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
122  *   g_option_context_add_group (context, gtk_get_option_group (TRUE));
123  *   if (!g_option_context_parse (context, &argc, &argv, &error))
124  *     {
125  *       g_print ("option parsing failed: %s\n", error->message);
126  *       exit (1);
127  *     }
128  *
129  *   /&ast; ... &ast;/
130  *
131  * }
132  * </programlisting></informalexample>
133  */
134
135 #include "config.h"
136
137 #include <string.h>
138 #include <stdlib.h>
139 #include <stdio.h>
140 #include <errno.h>
141
142 #if defined __OpenBSD__
143 #include <sys/types.h>
144 #include <unistd.h>
145 #include <sys/param.h>
146 #include <sys/sysctl.h>
147 #endif
148
149 #include "goption.h"
150
151 #include "gprintf.h"
152 #include "glibintl.h"
153
154 #define TRANSLATE(group, str) (((group)->translate_func ? (* (group)->translate_func) ((str), (group)->translate_data) : (str)))
155
156 #define NO_ARG(entry) ((entry)->arg == G_OPTION_ARG_NONE ||       \
157                        ((entry)->arg == G_OPTION_ARG_CALLBACK &&  \
158                         ((entry)->flags & G_OPTION_FLAG_NO_ARG)))
159
160 #define OPTIONAL_ARG(entry) ((entry)->arg == G_OPTION_ARG_CALLBACK &&  \
161                        (entry)->flags & G_OPTION_FLAG_OPTIONAL_ARG)
162
163 typedef struct
164 {
165   GOptionArg arg_type;
166   gpointer arg_data;
167   union
168   {
169     gboolean bool;
170     gint integer;
171     gchar *str;
172     gchar **array;
173     gdouble dbl;
174     gint64 int64;
175   } prev;
176   union
177   {
178     gchar *str;
179     struct
180     {
181       gint len;
182       gchar **data;
183     } array;
184   } allocated;
185 } Change;
186
187 typedef struct
188 {
189   gchar **ptr;
190   gchar *value;
191 } PendingNull;
192
193 struct _GOptionContext
194 {
195   GList           *groups;
196
197   gchar           *parameter_string;
198   gchar           *summary;
199   gchar           *description;
200
201   GTranslateFunc   translate_func;
202   GDestroyNotify   translate_notify;
203   gpointer         translate_data;
204
205   guint            help_enabled   : 1;
206   guint            ignore_unknown : 1;
207
208   GOptionGroup    *main_group;
209
210   /* We keep a list of change so we can revert them */
211   GList           *changes;
212
213   /* We also keep track of all argv elements
214    * that should be NULLed or modified.
215    */
216   GList           *pending_nulls;
217 };
218
219 struct _GOptionGroup
220 {
221   gchar           *name;
222   gchar           *description;
223   gchar           *help_description;
224
225   GDestroyNotify   destroy_notify;
226   gpointer         user_data;
227
228   GTranslateFunc   translate_func;
229   GDestroyNotify   translate_notify;
230   gpointer         translate_data;
231
232   GOptionEntry    *entries;
233   gint             n_entries;
234
235   GOptionParseFunc pre_parse_func;
236   GOptionParseFunc post_parse_func;
237   GOptionErrorFunc error_func;
238 };
239
240 static void free_changes_list (GOptionContext *context,
241                                gboolean        revert);
242 static void free_pending_nulls (GOptionContext *context,
243                                 gboolean        perform_nulls);
244
245
246 static int
247 _g_unichar_get_width (gunichar c)
248 {
249   if (G_UNLIKELY (g_unichar_iszerowidth (c)))
250     return 0;
251
252   /* we ignore the fact that we should call g_unichar_iswide_cjk() under
253    * some locales (legacy East Asian ones) */
254   if (g_unichar_iswide (c))
255     return 2;
256
257   return 1;
258 }
259
260 static glong
261 _g_utf8_strwidth (const gchar *p)
262 {
263   glong len = 0;
264   g_return_val_if_fail (p != NULL, 0);
265
266   while (*p)
267     {
268       len += _g_unichar_get_width (g_utf8_get_char (p));
269       p = g_utf8_next_char (p);
270     }
271
272   return len;
273 }
274
275 G_DEFINE_QUARK (g-option-context-error-quark, g_option_error)
276
277 /**
278  * g_option_context_new:
279  * @parameter_string: (allow-none): a string which is displayed in
280  *    the first line of <option>--help</option> output, after the
281  *    usage summary
282  *    <literal><replaceable>programname</replaceable> [OPTION...]</literal>
283  *
284  * Creates a new option context.
285  *
286  * The @parameter_string can serve multiple purposes. It can be used
287  * to add descriptions for "rest" arguments, which are not parsed by
288  * the #GOptionContext, typically something like "FILES" or
289  * "FILE1 FILE2...". If you are using #G_OPTION_REMAINING for
290  * collecting "rest" arguments, GLib handles this automatically by
291  * using the @arg_description of the corresponding #GOptionEntry in
292  * the usage summary.
293  *
294  * Another usage is to give a short summary of the program
295  * functionality, like " - frob the strings", which will be displayed
296  * in the same line as the usage. For a longer description of the
297  * program functionality that should be displayed as a paragraph
298  * below the usage line, use g_option_context_set_summary().
299  *
300  * Note that the @parameter_string is translated using the
301  * function set with g_option_context_set_translate_func(), so
302  * it should normally be passed untranslated.
303  *
304  * Returns: a newly created #GOptionContext, which must be
305  *    freed with g_option_context_free() after use.
306  *
307  * Since: 2.6
308  */
309 GOptionContext *
310 g_option_context_new (const gchar *parameter_string)
311
312 {
313   GOptionContext *context;
314
315   context = g_new0 (GOptionContext, 1);
316
317   context->parameter_string = g_strdup (parameter_string);
318   context->help_enabled = TRUE;
319   context->ignore_unknown = FALSE;
320
321   return context;
322 }
323
324 /**
325  * g_option_context_free:
326  * @context: a #GOptionContext
327  *
328  * Frees context and all the groups which have been
329  * added to it.
330  *
331  * Please note that parsed arguments need to be freed separately (see
332  * #GOptionEntry).
333  *
334  * Since: 2.6
335  */
336 void g_option_context_free (GOptionContext *context)
337 {
338   g_return_if_fail (context != NULL);
339
340   g_list_free_full (context->groups, (GDestroyNotify) g_option_group_free);
341
342   if (context->main_group)
343     g_option_group_free (context->main_group);
344
345   free_changes_list (context, FALSE);
346   free_pending_nulls (context, FALSE);
347
348   g_free (context->parameter_string);
349   g_free (context->summary);
350   g_free (context->description);
351
352   if (context->translate_notify)
353     (* context->translate_notify) (context->translate_data);
354
355   g_free (context);
356 }
357
358
359 /**
360  * g_option_context_set_help_enabled:
361  * @context: a #GOptionContext
362  * @help_enabled: %TRUE to enable <option>--help</option>, %FALSE to disable it
363  *
364  * Enables or disables automatic generation of <option>--help</option>
365  * output. By default, g_option_context_parse() recognizes
366  * <option>--help</option>, <option>-h</option>,
367  * <option>-?</option>, <option>--help-all</option>
368  * and <option>--help-</option><replaceable>groupname</replaceable> and creates
369  * suitable output to stdout.
370  *
371  * Since: 2.6
372  */
373 void g_option_context_set_help_enabled (GOptionContext *context,
374                                         gboolean        help_enabled)
375
376 {
377   g_return_if_fail (context != NULL);
378
379   context->help_enabled = help_enabled;
380 }
381
382 /**
383  * g_option_context_get_help_enabled:
384  * @context: a #GOptionContext
385  *
386  * Returns whether automatic <option>--help</option> generation
387  * is turned on for @context. See g_option_context_set_help_enabled().
388  *
389  * Returns: %TRUE if automatic help generation is turned on.
390  *
391  * Since: 2.6
392  */
393 gboolean
394 g_option_context_get_help_enabled (GOptionContext *context)
395 {
396   g_return_val_if_fail (context != NULL, FALSE);
397
398   return context->help_enabled;
399 }
400
401 /**
402  * g_option_context_set_ignore_unknown_options:
403  * @context: a #GOptionContext
404  * @ignore_unknown: %TRUE to ignore unknown options, %FALSE to produce
405  *    an error when unknown options are met
406  *
407  * Sets whether to ignore unknown options or not. If an argument is
408  * ignored, it is left in the @argv array after parsing. By default,
409  * g_option_context_parse() treats unknown options as error.
410  *
411  * This setting does not affect non-option arguments (i.e. arguments
412  * which don't start with a dash). But note that GOption cannot reliably
413  * determine whether a non-option belongs to a preceding unknown option.
414  *
415  * Since: 2.6
416  **/
417 void
418 g_option_context_set_ignore_unknown_options (GOptionContext *context,
419                                              gboolean        ignore_unknown)
420 {
421   g_return_if_fail (context != NULL);
422
423   context->ignore_unknown = ignore_unknown;
424 }
425
426 /**
427  * g_option_context_get_ignore_unknown_options:
428  * @context: a #GOptionContext
429  *
430  * Returns whether unknown options are ignored or not. See
431  * g_option_context_set_ignore_unknown_options().
432  *
433  * Returns: %TRUE if unknown options are ignored.
434  *
435  * Since: 2.6
436  **/
437 gboolean
438 g_option_context_get_ignore_unknown_options (GOptionContext *context)
439 {
440   g_return_val_if_fail (context != NULL, FALSE);
441
442   return context->ignore_unknown;
443 }
444
445 /**
446  * g_option_context_add_group:
447  * @context: a #GOptionContext
448  * @group: the group to add
449  *
450  * Adds a #GOptionGroup to the @context, so that parsing with @context
451  * will recognize the options in the group. Note that the group will
452  * be freed together with the context when g_option_context_free() is
453  * called, so you must not free the group yourself after adding it
454  * to a context.
455  *
456  * Since: 2.6
457  **/
458 void
459 g_option_context_add_group (GOptionContext *context,
460                             GOptionGroup   *group)
461 {
462   GList *list;
463
464   g_return_if_fail (context != NULL);
465   g_return_if_fail (group != NULL);
466   g_return_if_fail (group->name != NULL);
467   g_return_if_fail (group->description != NULL);
468   g_return_if_fail (group->help_description != NULL);
469
470   for (list = context->groups; list; list = list->next)
471     {
472       GOptionGroup *g = (GOptionGroup *)list->data;
473
474       if ((group->name == NULL && g->name == NULL) ||
475           (group->name && g->name && strcmp (group->name, g->name) == 0))
476         g_warning ("A group named \"%s\" is already part of this GOptionContext",
477                    group->name);
478     }
479
480   context->groups = g_list_append (context->groups, group);
481 }
482
483 /**
484  * g_option_context_set_main_group:
485  * @context: a #GOptionContext
486  * @group: the group to set as main group
487  *
488  * Sets a #GOptionGroup as main group of the @context.
489  * This has the same effect as calling g_option_context_add_group(),
490  * the only difference is that the options in the main group are
491  * treated differently when generating <option>--help</option> output.
492  *
493  * Since: 2.6
494  **/
495 void
496 g_option_context_set_main_group (GOptionContext *context,
497                                  GOptionGroup   *group)
498 {
499   g_return_if_fail (context != NULL);
500   g_return_if_fail (group != NULL);
501
502   if (context->main_group)
503     {
504       g_warning ("This GOptionContext already has a main group");
505
506       return;
507     }
508
509   context->main_group = group;
510 }
511
512 /**
513  * g_option_context_get_main_group:
514  * @context: a #GOptionContext
515  *
516  * Returns a pointer to the main group of @context.
517  *
518  * Return value: the main group of @context, or %NULL if @context doesn't
519  *  have a main group. Note that group belongs to @context and should
520  *  not be modified or freed.
521  *
522  * Since: 2.6
523  **/
524 GOptionGroup *
525 g_option_context_get_main_group (GOptionContext *context)
526 {
527   g_return_val_if_fail (context != NULL, NULL);
528
529   return context->main_group;
530 }
531
532 /**
533  * g_option_context_add_main_entries:
534  * @context: a #GOptionContext
535  * @entries: a %NULL-terminated array of #GOptionEntry<!-- -->s
536  * @translation_domain: (allow-none): a translation domain to use for translating
537  *    the <option>--help</option> output for the options in @entries
538  *    with gettext(), or %NULL
539  *
540  * A convenience function which creates a main group if it doesn't
541  * exist, adds the @entries to it and sets the translation domain.
542  *
543  * Since: 2.6
544  **/
545 void
546 g_option_context_add_main_entries (GOptionContext      *context,
547                                    const GOptionEntry  *entries,
548                                    const gchar         *translation_domain)
549 {
550   g_return_if_fail (entries != NULL);
551
552   if (!context->main_group)
553     context->main_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
554
555   g_option_group_add_entries (context->main_group, entries);
556   g_option_group_set_translation_domain (context->main_group, translation_domain);
557 }
558
559 static gint
560 calculate_max_length (GOptionGroup *group,
561                       GHashTable   *aliases)
562 {
563   GOptionEntry *entry;
564   gint i, len, max_length;
565   const gchar *long_name;
566
567   max_length = 0;
568
569   for (i = 0; i < group->n_entries; i++)
570     {
571       entry = &group->entries[i];
572
573       if (entry->flags & G_OPTION_FLAG_HIDDEN)
574         continue;
575
576       long_name = g_hash_table_lookup (aliases, &entry->long_name);
577       if (!long_name)
578         long_name = entry->long_name;
579       len = _g_utf8_strwidth (long_name);
580
581       if (entry->short_name)
582         len += 4;
583
584       if (!NO_ARG (entry) && entry->arg_description)
585         len += 1 + _g_utf8_strwidth (TRANSLATE (group, entry->arg_description));
586
587       max_length = MAX (max_length, len);
588     }
589
590   return max_length;
591 }
592
593 static void
594 print_entry (GOptionGroup       *group,
595              gint                max_length,
596              const GOptionEntry *entry,
597              GString            *string,
598              GHashTable         *aliases)
599 {
600   GString *str;
601   const gchar *long_name;
602
603   if (entry->flags & G_OPTION_FLAG_HIDDEN)
604     return;
605
606   if (entry->long_name[0] == 0)
607     return;
608
609   long_name = g_hash_table_lookup (aliases, &entry->long_name);
610   if (!long_name)
611     long_name = entry->long_name;
612
613   str = g_string_new (NULL);
614
615   if (entry->short_name)
616     g_string_append_printf (str, "  -%c, --%s", entry->short_name, long_name);
617   else
618     g_string_append_printf (str, "  --%s", long_name);
619
620   if (entry->arg_description)
621     g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
622
623   g_string_append_printf (string, "%s%*s %s\n", str->str,
624                           (int) (max_length + 4 - _g_utf8_strwidth (str->str)), "",
625                           entry->description ? TRANSLATE (group, entry->description) : "");
626   g_string_free (str, TRUE);
627 }
628
629 static gboolean
630 group_has_visible_entries (GOptionContext *context,
631                            GOptionGroup *group,
632                            gboolean      main_entries)
633 {
634   GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
635   GOptionEntry *entry;
636   gint i, l;
637   gboolean main_group = group == context->main_group;
638
639   if (!main_entries)
640     reject_filter |= G_OPTION_FLAG_IN_MAIN;
641
642   for (i = 0, l = (group ? group->n_entries : 0); i < l; i++)
643     {
644       entry = &group->entries[i];
645
646       if (main_entries && !main_group && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
647         continue;
648       if (entry->long_name[0] == 0) /* ignore rest entry */
649         continue;
650       if (!(entry->flags & reject_filter))
651         return TRUE;
652     }
653
654   return FALSE;
655 }
656
657 static gboolean
658 group_list_has_visible_entries (GOptionContext *context,
659                                 GList          *group_list,
660                                 gboolean       main_entries)
661 {
662   while (group_list)
663     {
664       if (group_has_visible_entries (context, group_list->data, main_entries))
665         return TRUE;
666
667       group_list = group_list->next;
668     }
669
670   return FALSE;
671 }
672
673 static gboolean
674 context_has_h_entry (GOptionContext *context)
675 {
676   gsize i;
677   GList *list;
678
679   if (context->main_group)
680     {
681       for (i = 0; i < context->main_group->n_entries; i++)
682         {
683           if (context->main_group->entries[i].short_name == 'h')
684             return TRUE;
685         }
686     }
687
688   for (list = context->groups; list != NULL; list = g_list_next (list))
689     {
690      GOptionGroup *group;
691
692       group = (GOptionGroup*)list->data;
693       for (i = 0; i < group->n_entries; i++)
694         {
695           if (group->entries[i].short_name == 'h')
696             return TRUE;
697         }
698     }
699   return FALSE;
700 }
701
702 /**
703  * g_option_context_get_help:
704  * @context: a #GOptionContext
705  * @main_help: if %TRUE, only include the main group
706  * @group: (allow-none): the #GOptionGroup to create help for, or %NULL
707  *
708  * Returns a formatted, translated help text for the given context.
709  * To obtain the text produced by <option>--help</option>, call
710  * <literal>g_option_context_get_help (context, TRUE, NULL)</literal>.
711  * To obtain the text produced by <option>--help-all</option>, call
712  * <literal>g_option_context_get_help (context, FALSE, NULL)</literal>.
713  * To obtain the help text for an option group, call
714  * <literal>g_option_context_get_help (context, FALSE, group)</literal>.
715  *
716  * Returns: A newly allocated string containing the help text
717  *
718  * Since: 2.14
719  */
720 gchar *
721 g_option_context_get_help (GOptionContext *context,
722                            gboolean        main_help,
723                            GOptionGroup   *group)
724 {
725   GList *list;
726   gint max_length = 0, len;
727   gint i;
728   GOptionEntry *entry;
729   GHashTable *shadow_map;
730   GHashTable *aliases;
731   gboolean seen[256];
732   const gchar *rest_description;
733   GString *string;
734   guchar token;
735
736   string = g_string_sized_new (1024);
737
738   rest_description = NULL;
739   if (context->main_group)
740     {
741
742       for (i = 0; i < context->main_group->n_entries; i++)
743         {
744           entry = &context->main_group->entries[i];
745           if (entry->long_name[0] == 0)
746             {
747               rest_description = TRANSLATE (context->main_group, entry->arg_description);
748               break;
749             }
750         }
751     }
752
753   g_string_append_printf (string, "%s\n  %s %s",
754                           _("Usage:"), g_get_prgname(), _("[OPTION...]"));
755
756   if (rest_description)
757     {
758       g_string_append (string, " ");
759       g_string_append (string, rest_description);
760     }
761
762   if (context->parameter_string)
763     {
764       g_string_append (string, " ");
765       g_string_append (string, TRANSLATE (context, context->parameter_string));
766     }
767
768   g_string_append (string, "\n\n");
769
770   if (context->summary)
771     {
772       g_string_append (string, TRANSLATE (context, context->summary));
773       g_string_append (string, "\n\n");
774     }
775
776   memset (seen, 0, sizeof (gboolean) * 256);
777   shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
778   aliases = g_hash_table_new_full (NULL, NULL, NULL, g_free);
779
780   if (context->main_group)
781     {
782       for (i = 0; i < context->main_group->n_entries; i++)
783         {
784           entry = &context->main_group->entries[i];
785           g_hash_table_insert (shadow_map,
786                                (gpointer)entry->long_name,
787                                entry);
788
789           if (seen[(guchar)entry->short_name])
790             entry->short_name = 0;
791           else
792             seen[(guchar)entry->short_name] = TRUE;
793         }
794     }
795
796   list = context->groups;
797   while (list != NULL)
798     {
799       GOptionGroup *g = list->data;
800       for (i = 0; i < g->n_entries; i++)
801         {
802           entry = &g->entries[i];
803           if (g_hash_table_lookup (shadow_map, entry->long_name) &&
804               !(entry->flags & G_OPTION_FLAG_NOALIAS))
805             {
806               g_hash_table_insert (aliases, &entry->long_name,
807                                    g_strdup_printf ("%s-%s", g->name, entry->long_name));
808             }
809           else
810             g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
811
812           if (seen[(guchar)entry->short_name] &&
813               !(entry->flags & G_OPTION_FLAG_NOALIAS))
814             entry->short_name = 0;
815           else
816             seen[(guchar)entry->short_name] = TRUE;
817         }
818       list = list->next;
819     }
820
821   g_hash_table_destroy (shadow_map);
822
823   list = context->groups;
824
825   if (context->help_enabled)
826     {
827       max_length = _g_utf8_strwidth ("-?, --help");
828
829       if (list)
830         {
831           len = _g_utf8_strwidth ("--help-all");
832           max_length = MAX (max_length, len);
833         }
834     }
835
836   if (context->main_group)
837     {
838       len = calculate_max_length (context->main_group, aliases);
839       max_length = MAX (max_length, len);
840     }
841
842   while (list != NULL)
843     {
844       GOptionGroup *g = list->data;
845
846       if (context->help_enabled)
847         {
848           /* First, we check the --help-<groupname> options */
849           len = _g_utf8_strwidth ("--help-") + _g_utf8_strwidth (g->name);
850           max_length = MAX (max_length, len);
851         }
852
853       /* Then we go through the entries */
854       len = calculate_max_length (g, aliases);
855       max_length = MAX (max_length, len);
856
857       list = list->next;
858     }
859
860   /* Add a bit of padding */
861   max_length += 4;
862
863   if (!group && context->help_enabled)
864     {
865       list = context->groups;
866
867       token = context_has_h_entry (context) ? '?' : 'h';
868
869       g_string_append_printf (string, "%s\n  -%c, --%-*s %s\n",
870                               _("Help Options:"), token, max_length - 4, "help",
871                               _("Show help options"));
872
873       /* We only want --help-all when there are groups */
874       if (list)
875         g_string_append_printf (string, "  --%-*s %s\n",
876                                 max_length, "help-all",
877                                 _("Show all help options"));
878
879       while (list)
880         {
881           GOptionGroup *g = list->data;
882
883           if (group_has_visible_entries (context, g, FALSE))
884             g_string_append_printf (string, "  --help-%-*s %s\n",
885                                     max_length - 5, g->name,
886                                     TRANSLATE (g, g->help_description));
887
888           list = list->next;
889         }
890
891       g_string_append (string, "\n");
892     }
893
894   if (group)
895     {
896       /* Print a certain group */
897
898       if (group_has_visible_entries (context, group, FALSE))
899         {
900           g_string_append (string, TRANSLATE (group, group->description));
901           g_string_append (string, "\n");
902           for (i = 0; i < group->n_entries; i++)
903             print_entry (group, max_length, &group->entries[i], string, aliases);
904           g_string_append (string, "\n");
905         }
906     }
907   else if (!main_help)
908     {
909       /* Print all groups */
910
911       list = context->groups;
912
913       while (list)
914         {
915           GOptionGroup *g = list->data;
916
917           if (group_has_visible_entries (context, g, FALSE))
918             {
919               g_string_append (string, g->description);
920               g_string_append (string, "\n");
921               for (i = 0; i < g->n_entries; i++)
922                 if (!(g->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
923                   print_entry (g, max_length, &g->entries[i], string, aliases);
924
925               g_string_append (string, "\n");
926             }
927
928           list = list->next;
929         }
930     }
931
932   /* Print application options if --help or --help-all has been specified */
933   if ((main_help || !group) &&
934       (group_has_visible_entries (context, context->main_group, TRUE) ||
935        group_list_has_visible_entries (context, context->groups, TRUE)))
936     {
937       list = context->groups;
938
939       g_string_append (string,  _("Application Options:"));
940       g_string_append (string, "\n");
941       if (context->main_group)
942         for (i = 0; i < context->main_group->n_entries; i++)
943           print_entry (context->main_group, max_length,
944                        &context->main_group->entries[i], string, aliases);
945
946       while (list != NULL)
947         {
948           GOptionGroup *g = list->data;
949
950           /* Print main entries from other groups */
951           for (i = 0; i < g->n_entries; i++)
952             if (g->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
953               print_entry (g, max_length, &g->entries[i], string, aliases);
954
955           list = list->next;
956         }
957
958       g_string_append (string, "\n");
959     }
960
961   if (context->description)
962     {
963       g_string_append (string, TRANSLATE (context, context->description));
964       g_string_append (string, "\n");
965     }
966
967   g_hash_table_destroy (aliases);
968
969   return g_string_free (string, FALSE);
970 }
971
972 G_GNUC_NORETURN
973 static void
974 print_help (GOptionContext *context,
975             gboolean        main_help,
976             GOptionGroup   *group)
977 {
978   gchar *help;
979
980   help = g_option_context_get_help (context, main_help, group);
981   g_print ("%s", help);
982   g_free (help);
983
984   exit (0);
985 }
986
987 static gboolean
988 parse_int (const gchar *arg_name,
989            const gchar *arg,
990            gint        *result,
991            GError     **error)
992 {
993   gchar *end;
994   glong tmp;
995
996   errno = 0;
997   tmp = strtol (arg, &end, 0);
998
999   if (*arg == '\0' || *end != '\0')
1000     {
1001       g_set_error (error,
1002                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1003                    _("Cannot parse integer value '%s' for %s"),
1004                    arg, arg_name);
1005       return FALSE;
1006     }
1007
1008   *result = tmp;
1009   if (*result != tmp || errno == ERANGE)
1010     {
1011       g_set_error (error,
1012                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1013                    _("Integer value '%s' for %s out of range"),
1014                    arg, arg_name);
1015       return FALSE;
1016     }
1017
1018   return TRUE;
1019 }
1020
1021
1022 static gboolean
1023 parse_double (const gchar *arg_name,
1024            const gchar *arg,
1025            gdouble        *result,
1026            GError     **error)
1027 {
1028   gchar *end;
1029   gdouble tmp;
1030
1031   errno = 0;
1032   tmp = g_strtod (arg, &end);
1033
1034   if (*arg == '\0' || *end != '\0')
1035     {
1036       g_set_error (error,
1037                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1038                    _("Cannot parse double value '%s' for %s"),
1039                    arg, arg_name);
1040       return FALSE;
1041     }
1042   if (errno == ERANGE)
1043     {
1044       g_set_error (error,
1045                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1046                    _("Double value '%s' for %s out of range"),
1047                    arg, arg_name);
1048       return FALSE;
1049     }
1050
1051   *result = tmp;
1052
1053   return TRUE;
1054 }
1055
1056
1057 static gboolean
1058 parse_int64 (const gchar *arg_name,
1059              const gchar *arg,
1060              gint64      *result,
1061              GError     **error)
1062 {
1063   gchar *end;
1064   gint64 tmp;
1065
1066   errno = 0;
1067   tmp = g_ascii_strtoll (arg, &end, 0);
1068
1069   if (*arg == '\0' || *end != '\0')
1070     {
1071       g_set_error (error,
1072                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1073                    _("Cannot parse integer value '%s' for %s"),
1074                    arg, arg_name);
1075       return FALSE;
1076     }
1077   if (errno == ERANGE)
1078     {
1079       g_set_error (error,
1080                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1081                    _("Integer value '%s' for %s out of range"),
1082                    arg, arg_name);
1083       return FALSE;
1084     }
1085
1086   *result = tmp;
1087
1088   return TRUE;
1089 }
1090
1091
1092 static Change *
1093 get_change (GOptionContext *context,
1094             GOptionArg      arg_type,
1095             gpointer        arg_data)
1096 {
1097   GList *list;
1098   Change *change = NULL;
1099
1100   for (list = context->changes; list != NULL; list = list->next)
1101     {
1102       change = list->data;
1103
1104       if (change->arg_data == arg_data)
1105         goto found;
1106     }
1107
1108   change = g_new0 (Change, 1);
1109   change->arg_type = arg_type;
1110   change->arg_data = arg_data;
1111
1112   context->changes = g_list_prepend (context->changes, change);
1113
1114  found:
1115
1116   return change;
1117 }
1118
1119 static void
1120 add_pending_null (GOptionContext *context,
1121                   gchar         **ptr,
1122                   gchar          *value)
1123 {
1124   PendingNull *n;
1125
1126   n = g_new0 (PendingNull, 1);
1127   n->ptr = ptr;
1128   n->value = value;
1129
1130   context->pending_nulls = g_list_prepend (context->pending_nulls, n);
1131 }
1132
1133 static gboolean
1134 parse_arg (GOptionContext *context,
1135            GOptionGroup   *group,
1136            GOptionEntry   *entry,
1137            const gchar    *value,
1138            const gchar    *option_name,
1139            GError        **error)
1140
1141 {
1142   Change *change;
1143
1144   g_assert (value || OPTIONAL_ARG (entry) || NO_ARG (entry));
1145
1146   switch (entry->arg)
1147     {
1148     case G_OPTION_ARG_NONE:
1149       {
1150         change = get_change (context, G_OPTION_ARG_NONE,
1151                              entry->arg_data);
1152
1153         *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
1154         break;
1155       }
1156     case G_OPTION_ARG_STRING:
1157       {
1158         gchar *data;
1159
1160         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1161
1162         if (!data)
1163           return FALSE;
1164
1165         change = get_change (context, G_OPTION_ARG_STRING,
1166                              entry->arg_data);
1167         g_free (change->allocated.str);
1168
1169         change->prev.str = *(gchar **)entry->arg_data;
1170         change->allocated.str = data;
1171
1172         *(gchar **)entry->arg_data = data;
1173         break;
1174       }
1175     case G_OPTION_ARG_STRING_ARRAY:
1176       {
1177         gchar *data;
1178
1179         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1180
1181         if (!data)
1182           return FALSE;
1183
1184         change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1185                              entry->arg_data);
1186
1187         if (change->allocated.array.len == 0)
1188           {
1189             change->prev.array = *(gchar ***)entry->arg_data;
1190             change->allocated.array.data = g_new (gchar *, 2);
1191           }
1192         else
1193           change->allocated.array.data =
1194             g_renew (gchar *, change->allocated.array.data,
1195                      change->allocated.array.len + 2);
1196
1197         change->allocated.array.data[change->allocated.array.len] = data;
1198         change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1199
1200         change->allocated.array.len ++;
1201
1202         *(gchar ***)entry->arg_data = change->allocated.array.data;
1203
1204         break;
1205       }
1206
1207     case G_OPTION_ARG_FILENAME:
1208       {
1209         gchar *data;
1210
1211 #ifdef G_OS_WIN32
1212         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1213
1214         if (!data)
1215           return FALSE;
1216 #else
1217         data = g_strdup (value);
1218 #endif
1219         change = get_change (context, G_OPTION_ARG_FILENAME,
1220                              entry->arg_data);
1221         g_free (change->allocated.str);
1222
1223         change->prev.str = *(gchar **)entry->arg_data;
1224         change->allocated.str = data;
1225
1226         *(gchar **)entry->arg_data = data;
1227         break;
1228       }
1229
1230     case G_OPTION_ARG_FILENAME_ARRAY:
1231       {
1232         gchar *data;
1233
1234 #ifdef G_OS_WIN32
1235         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1236
1237         if (!data)
1238           return FALSE;
1239 #else
1240         data = g_strdup (value);
1241 #endif
1242         change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1243                              entry->arg_data);
1244
1245         if (change->allocated.array.len == 0)
1246           {
1247             change->prev.array = *(gchar ***)entry->arg_data;
1248             change->allocated.array.data = g_new (gchar *, 2);
1249           }
1250         else
1251           change->allocated.array.data =
1252             g_renew (gchar *, change->allocated.array.data,
1253                      change->allocated.array.len + 2);
1254
1255         change->allocated.array.data[change->allocated.array.len] = data;
1256         change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1257
1258         change->allocated.array.len ++;
1259
1260         *(gchar ***)entry->arg_data = change->allocated.array.data;
1261
1262         break;
1263       }
1264
1265     case G_OPTION_ARG_INT:
1266       {
1267         gint data;
1268
1269         if (!parse_int (option_name, value,
1270                         &data,
1271                         error))
1272           return FALSE;
1273
1274         change = get_change (context, G_OPTION_ARG_INT,
1275                              entry->arg_data);
1276         change->prev.integer = *(gint *)entry->arg_data;
1277         *(gint *)entry->arg_data = data;
1278         break;
1279       }
1280     case G_OPTION_ARG_CALLBACK:
1281       {
1282         gchar *data;
1283         gboolean retval;
1284
1285         if (!value && entry->flags & G_OPTION_FLAG_OPTIONAL_ARG)
1286           data = NULL;
1287         else if (entry->flags & G_OPTION_FLAG_NO_ARG)
1288           data = NULL;
1289         else if (entry->flags & G_OPTION_FLAG_FILENAME)
1290           {
1291 #ifdef G_OS_WIN32
1292             data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1293 #else
1294             data = g_strdup (value);
1295 #endif
1296           }
1297         else
1298           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1299
1300         if (!(entry->flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG)) &&
1301             !data)
1302           return FALSE;
1303
1304         retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
1305
1306         if (!retval && error != NULL && *error == NULL)
1307           g_set_error (error,
1308                        G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1309                        _("Error parsing option %s"), option_name);
1310
1311         g_free (data);
1312
1313         return retval;
1314
1315         break;
1316       }
1317     case G_OPTION_ARG_DOUBLE:
1318       {
1319         gdouble data;
1320
1321         if (!parse_double (option_name, value,
1322                         &data,
1323                         error))
1324           {
1325             return FALSE;
1326           }
1327
1328         change = get_change (context, G_OPTION_ARG_DOUBLE,
1329                              entry->arg_data);
1330         change->prev.dbl = *(gdouble *)entry->arg_data;
1331         *(gdouble *)entry->arg_data = data;
1332         break;
1333       }
1334     case G_OPTION_ARG_INT64:
1335       {
1336         gint64 data;
1337
1338         if (!parse_int64 (option_name, value,
1339                          &data,
1340                          error))
1341           {
1342             return FALSE;
1343           }
1344
1345         change = get_change (context, G_OPTION_ARG_INT64,
1346                              entry->arg_data);
1347         change->prev.int64 = *(gint64 *)entry->arg_data;
1348         *(gint64 *)entry->arg_data = data;
1349         break;
1350       }
1351     default:
1352       g_assert_not_reached ();
1353     }
1354
1355   return TRUE;
1356 }
1357
1358 static gboolean
1359 parse_short_option (GOptionContext *context,
1360                     GOptionGroup   *group,
1361                     gint            idx,
1362                     gint           *new_idx,
1363                     gchar           arg,
1364                     gint           *argc,
1365                     gchar        ***argv,
1366                     GError        **error,
1367                     gboolean       *parsed)
1368 {
1369   gint j;
1370
1371   for (j = 0; j < group->n_entries; j++)
1372     {
1373       if (arg == group->entries[j].short_name)
1374         {
1375           gchar *option_name;
1376           gchar *value = NULL;
1377
1378           option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
1379
1380           if (NO_ARG (&group->entries[j]))
1381             value = NULL;
1382           else
1383             {
1384               if (*new_idx > idx)
1385                 {
1386                   g_set_error (error,
1387                                G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1388                                _("Error parsing option %s"), option_name);
1389                   g_free (option_name);
1390                   return FALSE;
1391                 }
1392
1393               if (idx < *argc - 1)
1394                 {
1395                   if (!OPTIONAL_ARG (&group->entries[j]))
1396                     {
1397                       value = (*argv)[idx + 1];
1398                       add_pending_null (context, &((*argv)[idx + 1]), NULL);
1399                       *new_idx = idx + 1;
1400                     }
1401                   else
1402                     {
1403                       if ((*argv)[idx + 1][0] == '-')
1404                         value = NULL;
1405                       else
1406                         {
1407                           value = (*argv)[idx + 1];
1408                           add_pending_null (context, &((*argv)[idx + 1]), NULL);
1409                           *new_idx = idx + 1;
1410                         }
1411                     }
1412                 }
1413               else if (idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1414                 value = NULL;
1415               else
1416                 {
1417                   g_set_error (error,
1418                                G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1419                                _("Missing argument for %s"), option_name);
1420                   g_free (option_name);
1421                   return FALSE;
1422                 }
1423             }
1424
1425           if (!parse_arg (context, group, &group->entries[j],
1426                           value, option_name, error))
1427             {
1428               g_free (option_name);
1429               return FALSE;
1430             }
1431
1432           g_free (option_name);
1433           *parsed = TRUE;
1434         }
1435     }
1436
1437   return TRUE;
1438 }
1439
1440 static gboolean
1441 parse_long_option (GOptionContext *context,
1442                    GOptionGroup   *group,
1443                    gint           *idx,
1444                    gchar          *arg,
1445                    gboolean        aliased,
1446                    gint           *argc,
1447                    gchar        ***argv,
1448                    GError        **error,
1449                    gboolean       *parsed)
1450 {
1451   gint j;
1452
1453   for (j = 0; j < group->n_entries; j++)
1454     {
1455       if (*idx >= *argc)
1456         return TRUE;
1457
1458       if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
1459         continue;
1460
1461       if (NO_ARG (&group->entries[j]) &&
1462           strcmp (arg, group->entries[j].long_name) == 0)
1463         {
1464           gchar *option_name;
1465           gboolean retval;
1466
1467           option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1468           retval = parse_arg (context, group, &group->entries[j],
1469                               NULL, option_name, error);
1470           g_free (option_name);
1471
1472           add_pending_null (context, &((*argv)[*idx]), NULL);
1473           *parsed = TRUE;
1474
1475           return retval;
1476         }
1477       else
1478         {
1479           gint len = strlen (group->entries[j].long_name);
1480
1481           if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
1482               (arg[len] == '=' || arg[len] == 0))
1483             {
1484               gchar *value = NULL;
1485               gchar *option_name;
1486
1487               add_pending_null (context, &((*argv)[*idx]), NULL);
1488               option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1489
1490               if (arg[len] == '=')
1491                 value = arg + len + 1;
1492               else if (*idx < *argc - 1)
1493                 {
1494                   if (!OPTIONAL_ARG (&group->entries[j]))
1495                     {
1496                       value = (*argv)[*idx + 1];
1497                       add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1498                       (*idx)++;
1499                     }
1500                   else
1501                     {
1502                       if ((*argv)[*idx + 1][0] == '-')
1503                         {
1504                           gboolean retval;
1505                           retval = parse_arg (context, group, &group->entries[j],
1506                                               NULL, option_name, error);
1507                           *parsed = TRUE;
1508                           g_free (option_name);
1509                           return retval;
1510                         }
1511                       else
1512                         {
1513                           value = (*argv)[*idx + 1];
1514                           add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1515                           (*idx)++;
1516                         }
1517                     }
1518                 }
1519               else if (*idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1520                 {
1521                     gboolean retval;
1522                     retval = parse_arg (context, group, &group->entries[j],
1523                                         NULL, option_name, error);
1524                     *parsed = TRUE;
1525                     g_free (option_name);
1526                     return retval;
1527                 }
1528               else
1529                 {
1530                   g_set_error (error,
1531                                G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1532                                _("Missing argument for %s"), option_name);
1533                   g_free (option_name);
1534                   return FALSE;
1535                 }
1536
1537               if (!parse_arg (context, group, &group->entries[j],
1538                               value, option_name, error))
1539                 {
1540                   g_free (option_name);
1541                   return FALSE;
1542                 }
1543
1544               g_free (option_name);
1545               *parsed = TRUE;
1546             }
1547         }
1548     }
1549
1550   return TRUE;
1551 }
1552
1553 static gboolean
1554 parse_remaining_arg (GOptionContext *context,
1555                      GOptionGroup   *group,
1556                      gint           *idx,
1557                      gint           *argc,
1558                      gchar        ***argv,
1559                      GError        **error,
1560                      gboolean       *parsed)
1561 {
1562   gint j;
1563
1564   for (j = 0; j < group->n_entries; j++)
1565     {
1566       if (*idx >= *argc)
1567         return TRUE;
1568
1569       if (group->entries[j].long_name[0])
1570         continue;
1571
1572       g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_CALLBACK ||
1573                             group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1574                             group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1575
1576       add_pending_null (context, &((*argv)[*idx]), NULL);
1577
1578       if (!parse_arg (context, group, &group->entries[j], (*argv)[*idx], "", error))
1579         return FALSE;
1580
1581       *parsed = TRUE;
1582       return TRUE;
1583     }
1584
1585   return TRUE;
1586 }
1587
1588 static void
1589 free_changes_list (GOptionContext *context,
1590                    gboolean        revert)
1591 {
1592   GList *list;
1593
1594   for (list = context->changes; list != NULL; list = list->next)
1595     {
1596       Change *change = list->data;
1597
1598       if (revert)
1599         {
1600           switch (change->arg_type)
1601             {
1602             case G_OPTION_ARG_NONE:
1603               *(gboolean *)change->arg_data = change->prev.bool;
1604               break;
1605             case G_OPTION_ARG_INT:
1606               *(gint *)change->arg_data = change->prev.integer;
1607               break;
1608             case G_OPTION_ARG_STRING:
1609             case G_OPTION_ARG_FILENAME:
1610               g_free (change->allocated.str);
1611               *(gchar **)change->arg_data = change->prev.str;
1612               break;
1613             case G_OPTION_ARG_STRING_ARRAY:
1614             case G_OPTION_ARG_FILENAME_ARRAY:
1615               g_strfreev (change->allocated.array.data);
1616               *(gchar ***)change->arg_data = change->prev.array;
1617               break;
1618             case G_OPTION_ARG_DOUBLE:
1619               *(gdouble *)change->arg_data = change->prev.dbl;
1620               break;
1621             case G_OPTION_ARG_INT64:
1622               *(gint64 *)change->arg_data = change->prev.int64;
1623               break;
1624             default:
1625               g_assert_not_reached ();
1626             }
1627         }
1628
1629       g_free (change);
1630     }
1631
1632   g_list_free (context->changes);
1633   context->changes = NULL;
1634 }
1635
1636 static void
1637 free_pending_nulls (GOptionContext *context,
1638                     gboolean        perform_nulls)
1639 {
1640   GList *list;
1641
1642   for (list = context->pending_nulls; list != NULL; list = list->next)
1643     {
1644       PendingNull *n = list->data;
1645
1646       if (perform_nulls)
1647         {
1648           if (n->value)
1649             {
1650               /* Copy back the short options */
1651               *(n->ptr)[0] = '-';
1652               strcpy (*n->ptr + 1, n->value);
1653             }
1654           else
1655             *n->ptr = NULL;
1656         }
1657
1658       g_free (n->value);
1659       g_free (n);
1660     }
1661
1662   g_list_free (context->pending_nulls);
1663   context->pending_nulls = NULL;
1664 }
1665
1666 /* Use a platform-specific mechanism to look up the first argument to
1667  * the current process. 
1668  * Note if you implement this for other platforms, also add it to
1669  * tests/option-argv0.c
1670  */
1671 static char *
1672 platform_get_argv0 (void)
1673 {
1674 #if defined __linux
1675   char *cmdline;
1676   char *base_arg0;
1677   gsize len;
1678
1679   if (!g_file_get_contents ("/proc/self/cmdline",
1680                             &cmdline,
1681                             &len,
1682                             NULL))
1683     return NULL;
1684   /* Sanity check for a NUL terminator. */
1685   if (!memchr (cmdline, 0, len))
1686     return NULL;
1687   /* We could just return cmdline, but I think it's better
1688    * to hold on to a smaller malloc block; the arguments
1689    * could be large.
1690    */
1691   base_arg0 = g_path_get_basename (cmdline);
1692   g_free (cmdline);
1693   return base_arg0;
1694 #elif defined __OpenBSD__
1695   char **cmdline = NULL;
1696   char *base_arg0;
1697   gsize len = PATH_MAX;
1698
1699   int mib[] = { CTL_KERN, KERN_PROC_ARGS, getpid(), KERN_PROC_ARGV };
1700
1701   cmdline = (char **) realloc (cmdline, len);
1702
1703   if (sysctl (mib, G_N_ELEMENTS (mib), cmdline, &len, NULL, 0) == -1)
1704     {
1705       g_free (cmdline);
1706       return NULL;
1707     }
1708
1709   /* We could just return cmdline, but I think it's better
1710    * to hold on to a smaller malloc block; the arguments
1711    * could be large.
1712    */
1713   base_arg0 = g_path_get_basename (*cmdline);
1714   g_free (cmdline);
1715   return base_arg0;
1716 #endif
1717
1718   return NULL;
1719 }
1720
1721 /**
1722  * g_option_context_parse:
1723  * @context: a #GOptionContext
1724  * @argc: (inout) (allow-none): a pointer to the number of command line arguments
1725  * @argv: (inout) (array length=argc) (allow-none): a pointer to the array of command line arguments
1726  * @error: a return location for errors
1727  *
1728  * Parses the command line arguments, recognizing options
1729  * which have been added to @context. A side-effect of
1730  * calling this function is that g_set_prgname() will be
1731  * called.
1732  *
1733  * If the parsing is successful, any parsed arguments are
1734  * removed from the array and @argc and @argv are updated
1735  * accordingly. A '--' option is stripped from @argv
1736  * unless there are unparsed options before and after it,
1737  * or some of the options after it start with '-'. In case
1738  * of an error, @argc and @argv are left unmodified.
1739  *
1740  * If automatic <option>--help</option> support is enabled
1741  * (see g_option_context_set_help_enabled()), and the
1742  * @argv array contains one of the recognized help options,
1743  * this function will produce help output to stdout and
1744  * call <literal>exit (0)</literal>.
1745  *
1746  * Note that function depends on the
1747  * <link linkend="setlocale">current locale</link> for
1748  * automatic character set conversion of string and filename
1749  * arguments.
1750  *
1751  * Return value: %TRUE if the parsing was successful,
1752  *               %FALSE if an error occurred
1753  *
1754  * Since: 2.6
1755  **/
1756 gboolean
1757 g_option_context_parse (GOptionContext   *context,
1758                         gint             *argc,
1759                         gchar          ***argv,
1760                         GError          **error)
1761 {
1762   gint i, j, k;
1763   GList *list;
1764
1765   /* Set program name */
1766   if (!g_get_prgname())
1767     {
1768       gchar *prgname;
1769
1770       if (argc && argv && *argc)
1771         prgname = g_path_get_basename ((*argv)[0]);
1772       else
1773         prgname = platform_get_argv0 ();
1774
1775       if (prgname)
1776         g_set_prgname (prgname);
1777       else
1778         g_set_prgname ("<unknown>");
1779
1780       g_free (prgname);
1781     }
1782
1783   /* Call pre-parse hooks */
1784   list = context->groups;
1785   while (list)
1786     {
1787       GOptionGroup *group = list->data;
1788
1789       if (group->pre_parse_func)
1790         {
1791           if (!(* group->pre_parse_func) (context, group,
1792                                           group->user_data, error))
1793             goto fail;
1794         }
1795
1796       list = list->next;
1797     }
1798
1799   if (context->main_group && context->main_group->pre_parse_func)
1800     {
1801       if (!(* context->main_group->pre_parse_func) (context, context->main_group,
1802                                                     context->main_group->user_data, error))
1803         goto fail;
1804     }
1805
1806   if (argc && argv)
1807     {
1808       gboolean stop_parsing = FALSE;
1809       gboolean has_unknown = FALSE;
1810       gint separator_pos = 0;
1811
1812       for (i = 1; i < *argc; i++)
1813         {
1814           gchar *arg, *dash;
1815           gboolean parsed = FALSE;
1816
1817           if ((*argv)[i][0] == '-' && (*argv)[i][1] != '\0' && !stop_parsing)
1818             {
1819               if ((*argv)[i][1] == '-')
1820                 {
1821                   /* -- option */
1822
1823                   arg = (*argv)[i] + 2;
1824
1825                   /* '--' terminates list of arguments */
1826                   if (*arg == 0)
1827                     {
1828                       separator_pos = i;
1829                       stop_parsing = TRUE;
1830                       continue;
1831                     }
1832
1833                   /* Handle help options */
1834                   if (context->help_enabled)
1835                     {
1836                       if (strcmp (arg, "help") == 0)
1837                         print_help (context, TRUE, NULL);
1838                       else if (strcmp (arg, "help-all") == 0)
1839                         print_help (context, FALSE, NULL);
1840                       else if (strncmp (arg, "help-", 5) == 0)
1841                         {
1842                           list = context->groups;
1843
1844                           while (list)
1845                             {
1846                               GOptionGroup *group = list->data;
1847
1848                               if (strcmp (arg + 5, group->name) == 0)
1849                                 print_help (context, FALSE, group);
1850
1851                               list = list->next;
1852                             }
1853                         }
1854                     }
1855
1856                   if (context->main_group &&
1857                       !parse_long_option (context, context->main_group, &i, arg,
1858                                           FALSE, argc, argv, error, &parsed))
1859                     goto fail;
1860
1861                   if (parsed)
1862                     continue;
1863
1864                   /* Try the groups */
1865                   list = context->groups;
1866                   while (list)
1867                     {
1868                       GOptionGroup *group = list->data;
1869
1870                       if (!parse_long_option (context, group, &i, arg,
1871                                               FALSE, argc, argv, error, &parsed))
1872                         goto fail;
1873
1874                       if (parsed)
1875                         break;
1876
1877                       list = list->next;
1878                     }
1879
1880                   if (parsed)
1881                     continue;
1882
1883                   /* Now look for --<group>-<option> */
1884                   dash = strchr (arg, '-');
1885                   if (dash)
1886                     {
1887                       /* Try the groups */
1888                       list = context->groups;
1889                       while (list)
1890                         {
1891                           GOptionGroup *group = list->data;
1892
1893                           if (strncmp (group->name, arg, dash - arg) == 0)
1894                             {
1895                               if (!parse_long_option (context, group, &i, dash + 1,
1896                                                       TRUE, argc, argv, error, &parsed))
1897                                 goto fail;
1898
1899                               if (parsed)
1900                                 break;
1901                             }
1902
1903                           list = list->next;
1904                         }
1905                     }
1906
1907                   if (context->ignore_unknown)
1908                     continue;
1909                 }
1910               else
1911                 { /* short option */
1912                   gint new_i = i, arg_length;
1913                   gboolean *nulled_out = NULL;
1914                   gboolean has_h_entry = context_has_h_entry (context);
1915                   arg = (*argv)[i] + 1;
1916                   arg_length = strlen (arg);
1917                   nulled_out = g_newa (gboolean, arg_length);
1918                   memset (nulled_out, 0, arg_length * sizeof (gboolean));
1919                   for (j = 0; j < arg_length; j++)
1920                     {
1921                       if (context->help_enabled && (arg[j] == '?' ||
1922                         (arg[j] == 'h' && !has_h_entry)))
1923                         print_help (context, TRUE, NULL);
1924                       parsed = FALSE;
1925                       if (context->main_group &&
1926                           !parse_short_option (context, context->main_group,
1927                                                i, &new_i, arg[j],
1928                                                argc, argv, error, &parsed))
1929                         goto fail;
1930                       if (!parsed)
1931                         {
1932                           /* Try the groups */
1933                           list = context->groups;
1934                           while (list)
1935                             {
1936                               GOptionGroup *group = list->data;
1937                               if (!parse_short_option (context, group, i, &new_i, arg[j],
1938                                                        argc, argv, error, &parsed))
1939                                 goto fail;
1940                               if (parsed)
1941                                 break;
1942                               list = list->next;
1943                             }
1944                         }
1945
1946                       if (context->ignore_unknown && parsed)
1947                         nulled_out[j] = TRUE;
1948                       else if (context->ignore_unknown)
1949                         continue;
1950                       else if (!parsed)
1951                         break;
1952                       /* !context->ignore_unknown && parsed */
1953                     }
1954                   if (context->ignore_unknown)
1955                     {
1956                       gchar *new_arg = NULL;
1957                       gint arg_index = 0;
1958                       for (j = 0; j < arg_length; j++)
1959                         {
1960                           if (!nulled_out[j])
1961                             {
1962                               if (!new_arg)
1963                                 new_arg = g_malloc (arg_length + 1);
1964                               new_arg[arg_index++] = arg[j];
1965                             }
1966                         }
1967                       if (new_arg)
1968                         new_arg[arg_index] = '\0';
1969                       add_pending_null (context, &((*argv)[i]), new_arg);
1970                     }
1971                   else if (parsed)
1972                     {
1973                       add_pending_null (context, &((*argv)[i]), NULL);
1974                       i = new_i;
1975                     }
1976                 }
1977
1978               if (!parsed)
1979                 has_unknown = TRUE;
1980
1981               if (!parsed && !context->ignore_unknown)
1982                 {
1983                   g_set_error (error,
1984                                G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
1985                                    _("Unknown option %s"), (*argv)[i]);
1986                   goto fail;
1987                 }
1988             }
1989           else
1990             {
1991               /* Collect remaining args */
1992               if (context->main_group &&
1993                   !parse_remaining_arg (context, context->main_group, &i,
1994                                         argc, argv, error, &parsed))
1995                 goto fail;
1996
1997               if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
1998                 separator_pos = 0;
1999             }
2000         }
2001
2002       if (separator_pos > 0)
2003         add_pending_null (context, &((*argv)[separator_pos]), NULL);
2004
2005     }
2006
2007   /* Call post-parse hooks */
2008   list = context->groups;
2009   while (list)
2010     {
2011       GOptionGroup *group = list->data;
2012
2013       if (group->post_parse_func)
2014         {
2015           if (!(* group->post_parse_func) (context, group,
2016                                            group->user_data, error))
2017             goto fail;
2018         }
2019
2020       list = list->next;
2021     }
2022
2023   if (context->main_group && context->main_group->post_parse_func)
2024     {
2025       if (!(* context->main_group->post_parse_func) (context, context->main_group,
2026                                                      context->main_group->user_data, error))
2027         goto fail;
2028     }
2029
2030   if (argc && argv)
2031     {
2032       free_pending_nulls (context, TRUE);
2033
2034       for (i = 1; i < *argc; i++)
2035         {
2036           for (k = i; k < *argc; k++)
2037             if ((*argv)[k] != NULL)
2038               break;
2039
2040           if (k > i)
2041             {
2042               k -= i;
2043               for (j = i + k; j < *argc; j++)
2044                 {
2045                   (*argv)[j-k] = (*argv)[j];
2046                   (*argv)[j] = NULL;
2047                 }
2048               *argc -= k;
2049             }
2050         }
2051     }
2052
2053   return TRUE;
2054
2055  fail:
2056
2057   /* Call error hooks */
2058   list = context->groups;
2059   while (list)
2060     {
2061       GOptionGroup *group = list->data;
2062
2063       if (group->error_func)
2064         (* group->error_func) (context, group,
2065                                group->user_data, error);
2066
2067       list = list->next;
2068     }
2069
2070   if (context->main_group && context->main_group->error_func)
2071     (* context->main_group->error_func) (context, context->main_group,
2072                                          context->main_group->user_data, error);
2073
2074   free_changes_list (context, TRUE);
2075   free_pending_nulls (context, FALSE);
2076
2077   return FALSE;
2078 }
2079
2080 /**
2081  * g_option_group_new:
2082  * @name: the name for the option group, this is used to provide
2083  *   help for the options in this group with <option>--help-</option>@name
2084  * @description: a description for this group to be shown in
2085  *   <option>--help</option>. This string is translated using the translation
2086  *   domain or translation function of the group
2087  * @help_description: a description for the <option>--help-</option>@name option.
2088  *   This string is translated using the translation domain or translation function
2089  *   of the group
2090  * @user_data: (allow-none): user data that will be passed to the pre- and post-parse hooks,
2091  *   the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
2092  * @destroy: (allow-none): a function that will be called to free @user_data, or %NULL
2093  *
2094  * Creates a new #GOptionGroup.
2095  *
2096  * Return value: a newly created option group. It should be added
2097  *   to a #GOptionContext or freed with g_option_group_free().
2098  *
2099  * Since: 2.6
2100  **/
2101 GOptionGroup *
2102 g_option_group_new (const gchar    *name,
2103                     const gchar    *description,
2104                     const gchar    *help_description,
2105                     gpointer        user_data,
2106                     GDestroyNotify  destroy)
2107
2108 {
2109   GOptionGroup *group;
2110
2111   group = g_new0 (GOptionGroup, 1);
2112   group->name = g_strdup (name);
2113   group->description = g_strdup (description);
2114   group->help_description = g_strdup (help_description);
2115   group->user_data = user_data;
2116   group->destroy_notify = destroy;
2117
2118   return group;
2119 }
2120
2121
2122 /**
2123  * g_option_group_free:
2124  * @group: a #GOptionGroup
2125  *
2126  * Frees a #GOptionGroup. Note that you must <emphasis>not</emphasis>
2127  * free groups which have been added to a #GOptionContext.
2128  *
2129  * Since: 2.6
2130  **/
2131 void
2132 g_option_group_free (GOptionGroup *group)
2133 {
2134   g_return_if_fail (group != NULL);
2135
2136   g_free (group->name);
2137   g_free (group->description);
2138   g_free (group->help_description);
2139
2140   g_free (group->entries);
2141
2142   if (group->destroy_notify)
2143     (* group->destroy_notify) (group->user_data);
2144
2145   if (group->translate_notify)
2146     (* group->translate_notify) (group->translate_data);
2147
2148   g_free (group);
2149 }
2150
2151
2152 /**
2153  * g_option_group_add_entries:
2154  * @group: a #GOptionGroup
2155  * @entries: a %NULL-terminated array of #GOptionEntry<!-- -->s
2156  *
2157  * Adds the options specified in @entries to @group.
2158  *
2159  * Since: 2.6
2160  **/
2161 void
2162 g_option_group_add_entries (GOptionGroup       *group,
2163                             const GOptionEntry *entries)
2164 {
2165   gint i, n_entries;
2166
2167   g_return_if_fail (entries != NULL);
2168
2169   for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++) ;
2170
2171   group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
2172
2173   memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
2174
2175   for (i = group->n_entries; i < group->n_entries + n_entries; i++)
2176     {
2177       gchar c = group->entries[i].short_name;
2178
2179       if (c == '-' || (c != 0 && !g_ascii_isprint (c)))
2180         {
2181           g_warning (G_STRLOC ": ignoring invalid short option '%c' (%d) in entry %s:%s",
2182               c, c, group->name, group->entries[i].long_name);
2183           group->entries[i].short_name = '\0';
2184         }
2185
2186       if (group->entries[i].arg != G_OPTION_ARG_NONE &&
2187           (group->entries[i].flags & G_OPTION_FLAG_REVERSE) != 0)
2188         {
2189           g_warning (G_STRLOC ": ignoring reverse flag on option of arg-type %d in entry %s:%s",
2190               group->entries[i].arg, group->name, group->entries[i].long_name);
2191
2192           group->entries[i].flags &= ~G_OPTION_FLAG_REVERSE;
2193         }
2194
2195       if (group->entries[i].arg != G_OPTION_ARG_CALLBACK &&
2196           (group->entries[i].flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME)) != 0)
2197         {
2198           g_warning (G_STRLOC ": ignoring no-arg, optional-arg or filename flags (%d) on option of arg-type %d in entry %s:%s",
2199               group->entries[i].flags, group->entries[i].arg, group->name, group->entries[i].long_name);
2200
2201           group->entries[i].flags &= ~(G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME);
2202         }
2203     }
2204
2205   group->n_entries += n_entries;
2206 }
2207
2208 /**
2209  * g_option_group_set_parse_hooks:
2210  * @group: a #GOptionGroup
2211  * @pre_parse_func: (allow-none): a function to call before parsing, or %NULL
2212  * @post_parse_func: (allow-none): a function to call after parsing, or %NULL
2213  *
2214  * Associates two functions with @group which will be called
2215  * from g_option_context_parse() before the first option is parsed
2216  * and after the last option has been parsed, respectively.
2217  *
2218  * Note that the user data to be passed to @pre_parse_func and
2219  * @post_parse_func can be specified when constructing the group
2220  * with g_option_group_new().
2221  *
2222  * Since: 2.6
2223  **/
2224 void
2225 g_option_group_set_parse_hooks (GOptionGroup     *group,
2226                                 GOptionParseFunc  pre_parse_func,
2227                                 GOptionParseFunc  post_parse_func)
2228 {
2229   g_return_if_fail (group != NULL);
2230
2231   group->pre_parse_func = pre_parse_func;
2232   group->post_parse_func = post_parse_func;
2233 }
2234
2235 /**
2236  * g_option_group_set_error_hook:
2237  * @group: a #GOptionGroup
2238  * @error_func: a function to call when an error occurs
2239  *
2240  * Associates a function with @group which will be called
2241  * from g_option_context_parse() when an error occurs.
2242  *
2243  * Note that the user data to be passed to @error_func can be
2244  * specified when constructing the group with g_option_group_new().
2245  *
2246  * Since: 2.6
2247  **/
2248 void
2249 g_option_group_set_error_hook (GOptionGroup     *group,
2250                                GOptionErrorFunc  error_func)
2251 {
2252   g_return_if_fail (group != NULL);
2253
2254   group->error_func = error_func;
2255 }
2256
2257
2258 /**
2259  * g_option_group_set_translate_func:
2260  * @group: a #GOptionGroup
2261  * @func: (allow-none): the #GTranslateFunc, or %NULL
2262  * @data: (allow-none): user data to pass to @func, or %NULL
2263  * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2264  *
2265  * Sets the function which is used to translate user-visible
2266  * strings, for <option>--help</option> output. Different
2267  * groups can use different #GTranslateFunc<!-- -->s. If @func
2268  * is %NULL, strings are not translated.
2269  *
2270  * If you are using gettext(), you only need to set the translation
2271  * domain, see g_option_group_set_translation_domain().
2272  *
2273  * Since: 2.6
2274  **/
2275 void
2276 g_option_group_set_translate_func (GOptionGroup   *group,
2277                                    GTranslateFunc  func,
2278                                    gpointer        data,
2279                                    GDestroyNotify  destroy_notify)
2280 {
2281   g_return_if_fail (group != NULL);
2282
2283   if (group->translate_notify)
2284     group->translate_notify (group->translate_data);
2285
2286   group->translate_func = func;
2287   group->translate_data = data;
2288   group->translate_notify = destroy_notify;
2289 }
2290
2291 static const gchar *
2292 dgettext_swapped (const gchar *msgid,
2293                   const gchar *domainname)
2294 {
2295   return g_dgettext (domainname, msgid);
2296 }
2297
2298 /**
2299  * g_option_group_set_translation_domain:
2300  * @group: a #GOptionGroup
2301  * @domain: the domain to use
2302  *
2303  * A convenience function to use gettext() for translating
2304  * user-visible strings.
2305  *
2306  * Since: 2.6
2307  **/
2308 void
2309 g_option_group_set_translation_domain (GOptionGroup *group,
2310                                        const gchar  *domain)
2311 {
2312   g_return_if_fail (group != NULL);
2313
2314   g_option_group_set_translate_func (group,
2315                                      (GTranslateFunc)dgettext_swapped,
2316                                      g_strdup (domain),
2317                                      g_free);
2318 }
2319
2320 /**
2321  * g_option_context_set_translate_func:
2322  * @context: a #GOptionContext
2323  * @func: (allow-none): the #GTranslateFunc, or %NULL
2324  * @data: (allow-none): user data to pass to @func, or %NULL
2325  * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2326  *
2327  * Sets the function which is used to translate the contexts
2328  * user-visible strings, for <option>--help</option> output.
2329  * If @func is %NULL, strings are not translated.
2330  *
2331  * Note that option groups have their own translation functions,
2332  * this function only affects the @parameter_string (see g_option_context_new()),
2333  * the summary (see g_option_context_set_summary()) and the description
2334  * (see g_option_context_set_description()).
2335  *
2336  * If you are using gettext(), you only need to set the translation
2337  * domain, see g_option_context_set_translation_domain().
2338  *
2339  * Since: 2.12
2340  **/
2341 void
2342 g_option_context_set_translate_func (GOptionContext *context,
2343                                      GTranslateFunc func,
2344                                      gpointer       data,
2345                                      GDestroyNotify destroy_notify)
2346 {
2347   g_return_if_fail (context != NULL);
2348
2349   if (context->translate_notify)
2350     context->translate_notify (context->translate_data);
2351
2352   context->translate_func = func;
2353   context->translate_data = data;
2354   context->translate_notify = destroy_notify;
2355 }
2356
2357 /**
2358  * g_option_context_set_translation_domain:
2359  * @context: a #GOptionContext
2360  * @domain: the domain to use
2361  *
2362  * A convenience function to use gettext() for translating
2363  * user-visible strings.
2364  *
2365  * Since: 2.12
2366  **/
2367 void
2368 g_option_context_set_translation_domain (GOptionContext *context,
2369                                          const gchar     *domain)
2370 {
2371   g_return_if_fail (context != NULL);
2372
2373   g_option_context_set_translate_func (context,
2374                                        (GTranslateFunc)dgettext_swapped,
2375                                        g_strdup (domain),
2376                                        g_free);
2377 }
2378
2379 /**
2380  * g_option_context_set_summary:
2381  * @context: a #GOptionContext
2382  * @summary: (allow-none): a string to be shown in <option>--help</option> output
2383  *  before the list of options, or %NULL
2384  *
2385  * Adds a string to be displayed in <option>--help</option> output
2386  * before the list of options. This is typically a summary of the
2387  * program functionality.
2388  *
2389  * Note that the summary is translated (see
2390  * g_option_context_set_translate_func() and
2391  * g_option_context_set_translation_domain()).
2392  *
2393  * Since: 2.12
2394  */
2395 void
2396 g_option_context_set_summary (GOptionContext *context,
2397                               const gchar    *summary)
2398 {
2399   g_return_if_fail (context != NULL);
2400
2401   g_free (context->summary);
2402   context->summary = g_strdup (summary);
2403 }
2404
2405
2406 /**
2407  * g_option_context_get_summary:
2408  * @context: a #GOptionContext
2409  *
2410  * Returns the summary. See g_option_context_set_summary().
2411  *
2412  * Returns: the summary
2413  *
2414  * Since: 2.12
2415  */
2416 const gchar *
2417 g_option_context_get_summary (GOptionContext *context)
2418 {
2419   g_return_val_if_fail (context != NULL, NULL);
2420
2421   return context->summary;
2422 }
2423
2424 /**
2425  * g_option_context_set_description:
2426  * @context: a #GOptionContext
2427  * @description: (allow-none): a string to be shown in <option>--help</option> output
2428  *   after the list of options, or %NULL
2429  *
2430  * Adds a string to be displayed in <option>--help</option> output
2431  * after the list of options. This text often includes a bug reporting
2432  * address.
2433  *
2434  * Note that the summary is translated (see
2435  * g_option_context_set_translate_func()).
2436  *
2437  * Since: 2.12
2438  */
2439 void
2440 g_option_context_set_description (GOptionContext *context,
2441                                   const gchar    *description)
2442 {
2443   g_return_if_fail (context != NULL);
2444
2445   g_free (context->description);
2446   context->description = g_strdup (description);
2447 }
2448
2449
2450 /**
2451  * g_option_context_get_description:
2452  * @context: a #GOptionContext
2453  *
2454  * Returns the description. See g_option_context_set_description().
2455  *
2456  * Returns: the description
2457  *
2458  * Since: 2.12
2459  */
2460 const gchar *
2461 g_option_context_get_description (GOptionContext *context)
2462 {
2463   g_return_val_if_fail (context != NULL, NULL);
2464
2465   return context->description;
2466 }