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