g_option_context_help: don't modify the input data
[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: 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, 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   max_length = _g_utf8_strwidth ("-?, --help");
826
827   if (list)
828     {
829       len = _g_utf8_strwidth ("--help-all");
830       max_length = MAX (max_length, len);
831     }
832
833   if (context->main_group)
834     {
835       len = calculate_max_length (context->main_group, aliases);
836       max_length = MAX (max_length, len);
837     }
838
839   while (list != NULL)
840     {
841       GOptionGroup *g = list->data;
842
843       /* First, we check the --help-<groupname> options */
844       len = _g_utf8_strwidth ("--help-") + _g_utf8_strwidth (g->name);
845       max_length = MAX (max_length, len);
846
847       /* Then we go through the entries */
848       len = calculate_max_length (g, aliases);
849       max_length = MAX (max_length, len);
850
851       list = list->next;
852     }
853
854   /* Add a bit of padding */
855   max_length += 4;
856
857   if (!group)
858     {
859       list = context->groups;
860
861       token = context_has_h_entry (context) ? '?' : 'h';
862
863       g_string_append_printf (string, "%s\n  -%c, --%-*s %s\n",
864                               _("Help Options:"), token, max_length - 4, "help",
865                               _("Show help options"));
866
867       /* We only want --help-all when there are groups */
868       if (list)
869         g_string_append_printf (string, "  --%-*s %s\n",
870                                 max_length, "help-all",
871                                 _("Show all help options"));
872
873       while (list)
874         {
875           GOptionGroup *g = list->data;
876
877           if (group_has_visible_entries (context, g, FALSE))
878             g_string_append_printf (string, "  --help-%-*s %s\n",
879                                     max_length - 5, g->name,
880                                     TRANSLATE (g, g->help_description));
881
882           list = list->next;
883         }
884
885       g_string_append (string, "\n");
886     }
887
888   if (group)
889     {
890       /* Print a certain group */
891
892       if (group_has_visible_entries (context, group, FALSE))
893         {
894           g_string_append (string, TRANSLATE (group, group->description));
895           g_string_append (string, "\n");
896           for (i = 0; i < group->n_entries; i++)
897             print_entry (group, max_length, &group->entries[i], string, aliases);
898           g_string_append (string, "\n");
899         }
900     }
901   else if (!main_help)
902     {
903       /* Print all groups */
904
905       list = context->groups;
906
907       while (list)
908         {
909           GOptionGroup *g = list->data;
910
911           if (group_has_visible_entries (context, g, FALSE))
912             {
913               g_string_append (string, g->description);
914               g_string_append (string, "\n");
915               for (i = 0; i < g->n_entries; i++)
916                 if (!(g->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
917                   print_entry (g, max_length, &g->entries[i], string, aliases);
918
919               g_string_append (string, "\n");
920             }
921
922           list = list->next;
923         }
924     }
925
926   /* Print application options if --help or --help-all has been specified */
927   if ((main_help || !group) &&
928       (group_has_visible_entries (context, context->main_group, TRUE) ||
929        group_list_has_visible_entries (context, context->groups, TRUE)))
930     {
931       list = context->groups;
932
933       g_string_append (string,  _("Application Options:"));
934       g_string_append (string, "\n");
935       if (context->main_group)
936         for (i = 0; i < context->main_group->n_entries; i++)
937           print_entry (context->main_group, max_length,
938                        &context->main_group->entries[i], string, aliases);
939
940       while (list != NULL)
941         {
942           GOptionGroup *g = list->data;
943
944           /* Print main entries from other groups */
945           for (i = 0; i < g->n_entries; i++)
946             if (g->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
947               print_entry (g, max_length, &g->entries[i], string, aliases);
948
949           list = list->next;
950         }
951
952       g_string_append (string, "\n");
953     }
954
955   if (context->description)
956     {
957       g_string_append (string, TRANSLATE (context, context->description));
958       g_string_append (string, "\n");
959     }
960
961   g_hash_table_destroy (aliases);
962
963   return g_string_free (string, FALSE);
964 }
965
966 G_GNUC_NORETURN
967 static void
968 print_help (GOptionContext *context,
969             gboolean        main_help,
970             GOptionGroup   *group)
971 {
972   gchar *help;
973
974   help = g_option_context_get_help (context, main_help, group);
975   g_print ("%s", help);
976   g_free (help);
977
978   exit (0);
979 }
980
981 static gboolean
982 parse_int (const gchar *arg_name,
983            const gchar *arg,
984            gint        *result,
985            GError     **error)
986 {
987   gchar *end;
988   glong tmp;
989
990   errno = 0;
991   tmp = strtol (arg, &end, 0);
992
993   if (*arg == '\0' || *end != '\0')
994     {
995       g_set_error (error,
996                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
997                    _("Cannot parse integer value '%s' for %s"),
998                    arg, arg_name);
999       return FALSE;
1000     }
1001
1002   *result = tmp;
1003   if (*result != tmp || errno == ERANGE)
1004     {
1005       g_set_error (error,
1006                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1007                    _("Integer value '%s' for %s out of range"),
1008                    arg, arg_name);
1009       return FALSE;
1010     }
1011
1012   return TRUE;
1013 }
1014
1015
1016 static gboolean
1017 parse_double (const gchar *arg_name,
1018            const gchar *arg,
1019            gdouble        *result,
1020            GError     **error)
1021 {
1022   gchar *end;
1023   gdouble tmp;
1024
1025   errno = 0;
1026   tmp = g_strtod (arg, &end);
1027
1028   if (*arg == '\0' || *end != '\0')
1029     {
1030       g_set_error (error,
1031                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1032                    _("Cannot parse double value '%s' for %s"),
1033                    arg, arg_name);
1034       return FALSE;
1035     }
1036   if (errno == ERANGE)
1037     {
1038       g_set_error (error,
1039                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1040                    _("Double value '%s' for %s out of range"),
1041                    arg, arg_name);
1042       return FALSE;
1043     }
1044
1045   *result = tmp;
1046
1047   return TRUE;
1048 }
1049
1050
1051 static gboolean
1052 parse_int64 (const gchar *arg_name,
1053              const gchar *arg,
1054              gint64      *result,
1055              GError     **error)
1056 {
1057   gchar *end;
1058   gint64 tmp;
1059
1060   errno = 0;
1061   tmp = g_ascii_strtoll (arg, &end, 0);
1062
1063   if (*arg == '\0' || *end != '\0')
1064     {
1065       g_set_error (error,
1066                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1067                    _("Cannot parse integer value '%s' for %s"),
1068                    arg, arg_name);
1069       return FALSE;
1070     }
1071   if (errno == ERANGE)
1072     {
1073       g_set_error (error,
1074                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1075                    _("Integer value '%s' for %s out of range"),
1076                    arg, arg_name);
1077       return FALSE;
1078     }
1079
1080   *result = tmp;
1081
1082   return TRUE;
1083 }
1084
1085
1086 static Change *
1087 get_change (GOptionContext *context,
1088             GOptionArg      arg_type,
1089             gpointer        arg_data)
1090 {
1091   GList *list;
1092   Change *change = NULL;
1093
1094   for (list = context->changes; list != NULL; list = list->next)
1095     {
1096       change = list->data;
1097
1098       if (change->arg_data == arg_data)
1099         goto found;
1100     }
1101
1102   change = g_new0 (Change, 1);
1103   change->arg_type = arg_type;
1104   change->arg_data = arg_data;
1105
1106   context->changes = g_list_prepend (context->changes, change);
1107
1108  found:
1109
1110   return change;
1111 }
1112
1113 static void
1114 add_pending_null (GOptionContext *context,
1115                   gchar         **ptr,
1116                   gchar          *value)
1117 {
1118   PendingNull *n;
1119
1120   n = g_new0 (PendingNull, 1);
1121   n->ptr = ptr;
1122   n->value = value;
1123
1124   context->pending_nulls = g_list_prepend (context->pending_nulls, n);
1125 }
1126
1127 static gboolean
1128 parse_arg (GOptionContext *context,
1129            GOptionGroup   *group,
1130            GOptionEntry   *entry,
1131            const gchar    *value,
1132            const gchar    *option_name,
1133            GError        **error)
1134
1135 {
1136   Change *change;
1137
1138   g_assert (value || OPTIONAL_ARG (entry) || NO_ARG (entry));
1139
1140   switch (entry->arg)
1141     {
1142     case G_OPTION_ARG_NONE:
1143       {
1144         change = get_change (context, G_OPTION_ARG_NONE,
1145                              entry->arg_data);
1146
1147         *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
1148         break;
1149       }
1150     case G_OPTION_ARG_STRING:
1151       {
1152         gchar *data;
1153
1154         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1155
1156         if (!data)
1157           return FALSE;
1158
1159         change = get_change (context, G_OPTION_ARG_STRING,
1160                              entry->arg_data);
1161         g_free (change->allocated.str);
1162
1163         change->prev.str = *(gchar **)entry->arg_data;
1164         change->allocated.str = data;
1165
1166         *(gchar **)entry->arg_data = data;
1167         break;
1168       }
1169     case G_OPTION_ARG_STRING_ARRAY:
1170       {
1171         gchar *data;
1172
1173         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1174
1175         if (!data)
1176           return FALSE;
1177
1178         change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1179                              entry->arg_data);
1180
1181         if (change->allocated.array.len == 0)
1182           {
1183             change->prev.array = *(gchar ***)entry->arg_data;
1184             change->allocated.array.data = g_new (gchar *, 2);
1185           }
1186         else
1187           change->allocated.array.data =
1188             g_renew (gchar *, change->allocated.array.data,
1189                      change->allocated.array.len + 2);
1190
1191         change->allocated.array.data[change->allocated.array.len] = data;
1192         change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1193
1194         change->allocated.array.len ++;
1195
1196         *(gchar ***)entry->arg_data = change->allocated.array.data;
1197
1198         break;
1199       }
1200
1201     case G_OPTION_ARG_FILENAME:
1202       {
1203         gchar *data;
1204
1205 #ifdef G_OS_WIN32
1206         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1207
1208         if (!data)
1209           return FALSE;
1210 #else
1211         data = g_strdup (value);
1212 #endif
1213         change = get_change (context, G_OPTION_ARG_FILENAME,
1214                              entry->arg_data);
1215         g_free (change->allocated.str);
1216
1217         change->prev.str = *(gchar **)entry->arg_data;
1218         change->allocated.str = data;
1219
1220         *(gchar **)entry->arg_data = data;
1221         break;
1222       }
1223
1224     case G_OPTION_ARG_FILENAME_ARRAY:
1225       {
1226         gchar *data;
1227
1228 #ifdef G_OS_WIN32
1229         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1230
1231         if (!data)
1232           return FALSE;
1233 #else
1234         data = g_strdup (value);
1235 #endif
1236         change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1237                              entry->arg_data);
1238
1239         if (change->allocated.array.len == 0)
1240           {
1241             change->prev.array = *(gchar ***)entry->arg_data;
1242             change->allocated.array.data = g_new (gchar *, 2);
1243           }
1244         else
1245           change->allocated.array.data =
1246             g_renew (gchar *, change->allocated.array.data,
1247                      change->allocated.array.len + 2);
1248
1249         change->allocated.array.data[change->allocated.array.len] = data;
1250         change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1251
1252         change->allocated.array.len ++;
1253
1254         *(gchar ***)entry->arg_data = change->allocated.array.data;
1255
1256         break;
1257       }
1258
1259     case G_OPTION_ARG_INT:
1260       {
1261         gint data;
1262
1263         if (!parse_int (option_name, value,
1264                         &data,
1265                         error))
1266           return FALSE;
1267
1268         change = get_change (context, G_OPTION_ARG_INT,
1269                              entry->arg_data);
1270         change->prev.integer = *(gint *)entry->arg_data;
1271         *(gint *)entry->arg_data = data;
1272         break;
1273       }
1274     case G_OPTION_ARG_CALLBACK:
1275       {
1276         gchar *data;
1277         gboolean retval;
1278
1279         if (!value && entry->flags & G_OPTION_FLAG_OPTIONAL_ARG)
1280           data = NULL;
1281         else if (entry->flags & G_OPTION_FLAG_NO_ARG)
1282           data = NULL;
1283         else if (entry->flags & G_OPTION_FLAG_FILENAME)
1284           {
1285 #ifdef G_OS_WIN32
1286             data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1287 #else
1288             data = g_strdup (value);
1289 #endif
1290           }
1291         else
1292           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1293
1294         if (!(entry->flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG)) &&
1295             !data)
1296           return FALSE;
1297
1298         retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
1299
1300         if (!retval && error != NULL && *error == NULL)
1301           g_set_error (error,
1302                        G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1303                        _("Error parsing option %s"), option_name);
1304
1305         g_free (data);
1306
1307         return retval;
1308
1309         break;
1310       }
1311     case G_OPTION_ARG_DOUBLE:
1312       {
1313         gdouble data;
1314
1315         if (!parse_double (option_name, value,
1316                         &data,
1317                         error))
1318           {
1319             return FALSE;
1320           }
1321
1322         change = get_change (context, G_OPTION_ARG_DOUBLE,
1323                              entry->arg_data);
1324         change->prev.dbl = *(gdouble *)entry->arg_data;
1325         *(gdouble *)entry->arg_data = data;
1326         break;
1327       }
1328     case G_OPTION_ARG_INT64:
1329       {
1330         gint64 data;
1331
1332         if (!parse_int64 (option_name, value,
1333                          &data,
1334                          error))
1335           {
1336             return FALSE;
1337           }
1338
1339         change = get_change (context, G_OPTION_ARG_INT64,
1340                              entry->arg_data);
1341         change->prev.int64 = *(gint64 *)entry->arg_data;
1342         *(gint64 *)entry->arg_data = data;
1343         break;
1344       }
1345     default:
1346       g_assert_not_reached ();
1347     }
1348
1349   return TRUE;
1350 }
1351
1352 static gboolean
1353 parse_short_option (GOptionContext *context,
1354                     GOptionGroup   *group,
1355                     gint            idx,
1356                     gint           *new_idx,
1357                     gchar           arg,
1358                     gint           *argc,
1359                     gchar        ***argv,
1360                     GError        **error,
1361                     gboolean       *parsed)
1362 {
1363   gint j;
1364
1365   for (j = 0; j < group->n_entries; j++)
1366     {
1367       if (arg == group->entries[j].short_name)
1368         {
1369           gchar *option_name;
1370           gchar *value = NULL;
1371
1372           option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
1373
1374           if (NO_ARG (&group->entries[j]))
1375             value = NULL;
1376           else
1377             {
1378               if (*new_idx > idx)
1379                 {
1380                   g_set_error (error,
1381                                G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1382                                _("Error parsing option %s"), option_name);
1383                   g_free (option_name);
1384                   return FALSE;
1385                 }
1386
1387               if (idx < *argc - 1)
1388                 {
1389                   if (!OPTIONAL_ARG (&group->entries[j]))
1390                     {
1391                       value = (*argv)[idx + 1];
1392                       add_pending_null (context, &((*argv)[idx + 1]), NULL);
1393                       *new_idx = idx + 1;
1394                     }
1395                   else
1396                     {
1397                       if ((*argv)[idx + 1][0] == '-')
1398                         value = NULL;
1399                       else
1400                         {
1401                           value = (*argv)[idx + 1];
1402                           add_pending_null (context, &((*argv)[idx + 1]), NULL);
1403                           *new_idx = idx + 1;
1404                         }
1405                     }
1406                 }
1407               else if (idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1408                 value = NULL;
1409               else
1410                 {
1411                   g_set_error (error,
1412                                G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1413                                _("Missing argument for %s"), option_name);
1414                   g_free (option_name);
1415                   return FALSE;
1416                 }
1417             }
1418
1419           if (!parse_arg (context, group, &group->entries[j],
1420                           value, option_name, error))
1421             {
1422               g_free (option_name);
1423               return FALSE;
1424             }
1425
1426           g_free (option_name);
1427           *parsed = TRUE;
1428         }
1429     }
1430
1431   return TRUE;
1432 }
1433
1434 static gboolean
1435 parse_long_option (GOptionContext *context,
1436                    GOptionGroup   *group,
1437                    gint           *idx,
1438                    gchar          *arg,
1439                    gboolean        aliased,
1440                    gint           *argc,
1441                    gchar        ***argv,
1442                    GError        **error,
1443                    gboolean       *parsed)
1444 {
1445   gint j;
1446
1447   for (j = 0; j < group->n_entries; j++)
1448     {
1449       if (*idx >= *argc)
1450         return TRUE;
1451
1452       if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
1453         continue;
1454
1455       if (NO_ARG (&group->entries[j]) &&
1456           strcmp (arg, group->entries[j].long_name) == 0)
1457         {
1458           gchar *option_name;
1459           gboolean retval;
1460
1461           option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1462           retval = parse_arg (context, group, &group->entries[j],
1463                               NULL, option_name, error);
1464           g_free (option_name);
1465
1466           add_pending_null (context, &((*argv)[*idx]), NULL);
1467           *parsed = TRUE;
1468
1469           return retval;
1470         }
1471       else
1472         {
1473           gint len = strlen (group->entries[j].long_name);
1474
1475           if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
1476               (arg[len] == '=' || arg[len] == 0))
1477             {
1478               gchar *value = NULL;
1479               gchar *option_name;
1480
1481               add_pending_null (context, &((*argv)[*idx]), NULL);
1482               option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1483
1484               if (arg[len] == '=')
1485                 value = arg + len + 1;
1486               else if (*idx < *argc - 1)
1487                 {
1488                   if (!OPTIONAL_ARG (&group->entries[j]))
1489                     {
1490                       value = (*argv)[*idx + 1];
1491                       add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1492                       (*idx)++;
1493                     }
1494                   else
1495                     {
1496                       if ((*argv)[*idx + 1][0] == '-')
1497                         {
1498                           gboolean retval;
1499                           retval = parse_arg (context, group, &group->entries[j],
1500                                               NULL, option_name, error);
1501                           *parsed = TRUE;
1502                           g_free (option_name);
1503                           return retval;
1504                         }
1505                       else
1506                         {
1507                           value = (*argv)[*idx + 1];
1508                           add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1509                           (*idx)++;
1510                         }
1511                     }
1512                 }
1513               else if (*idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1514                 {
1515                     gboolean retval;
1516                     retval = parse_arg (context, group, &group->entries[j],
1517                                         NULL, option_name, error);
1518                     *parsed = TRUE;
1519                     g_free (option_name);
1520                     return retval;
1521                 }
1522               else
1523                 {
1524                   g_set_error (error,
1525                                G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1526                                _("Missing argument for %s"), option_name);
1527                   g_free (option_name);
1528                   return FALSE;
1529                 }
1530
1531               if (!parse_arg (context, group, &group->entries[j],
1532                               value, option_name, error))
1533                 {
1534                   g_free (option_name);
1535                   return FALSE;
1536                 }
1537
1538               g_free (option_name);
1539               *parsed = TRUE;
1540             }
1541         }
1542     }
1543
1544   return TRUE;
1545 }
1546
1547 static gboolean
1548 parse_remaining_arg (GOptionContext *context,
1549                      GOptionGroup   *group,
1550                      gint           *idx,
1551                      gint           *argc,
1552                      gchar        ***argv,
1553                      GError        **error,
1554                      gboolean       *parsed)
1555 {
1556   gint j;
1557
1558   for (j = 0; j < group->n_entries; j++)
1559     {
1560       if (*idx >= *argc)
1561         return TRUE;
1562
1563       if (group->entries[j].long_name[0])
1564         continue;
1565
1566       g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_CALLBACK ||
1567                             group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1568                             group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1569
1570       add_pending_null (context, &((*argv)[*idx]), NULL);
1571
1572       if (!parse_arg (context, group, &group->entries[j], (*argv)[*idx], "", error))
1573         return FALSE;
1574
1575       *parsed = TRUE;
1576       return TRUE;
1577     }
1578
1579   return TRUE;
1580 }
1581
1582 static void
1583 free_changes_list (GOptionContext *context,
1584                    gboolean        revert)
1585 {
1586   GList *list;
1587
1588   for (list = context->changes; list != NULL; list = list->next)
1589     {
1590       Change *change = list->data;
1591
1592       if (revert)
1593         {
1594           switch (change->arg_type)
1595             {
1596             case G_OPTION_ARG_NONE:
1597               *(gboolean *)change->arg_data = change->prev.bool;
1598               break;
1599             case G_OPTION_ARG_INT:
1600               *(gint *)change->arg_data = change->prev.integer;
1601               break;
1602             case G_OPTION_ARG_STRING:
1603             case G_OPTION_ARG_FILENAME:
1604               g_free (change->allocated.str);
1605               *(gchar **)change->arg_data = change->prev.str;
1606               break;
1607             case G_OPTION_ARG_STRING_ARRAY:
1608             case G_OPTION_ARG_FILENAME_ARRAY:
1609               g_strfreev (change->allocated.array.data);
1610               *(gchar ***)change->arg_data = change->prev.array;
1611               break;
1612             case G_OPTION_ARG_DOUBLE:
1613               *(gdouble *)change->arg_data = change->prev.dbl;
1614               break;
1615             case G_OPTION_ARG_INT64:
1616               *(gint64 *)change->arg_data = change->prev.int64;
1617               break;
1618             default:
1619               g_assert_not_reached ();
1620             }
1621         }
1622
1623       g_free (change);
1624     }
1625
1626   g_list_free (context->changes);
1627   context->changes = NULL;
1628 }
1629
1630 static void
1631 free_pending_nulls (GOptionContext *context,
1632                     gboolean        perform_nulls)
1633 {
1634   GList *list;
1635
1636   for (list = context->pending_nulls; list != NULL; list = list->next)
1637     {
1638       PendingNull *n = list->data;
1639
1640       if (perform_nulls)
1641         {
1642           if (n->value)
1643             {
1644               /* Copy back the short options */
1645               *(n->ptr)[0] = '-';
1646               strcpy (*n->ptr + 1, n->value);
1647             }
1648           else
1649             *n->ptr = NULL;
1650         }
1651
1652       g_free (n->value);
1653       g_free (n);
1654     }
1655
1656   g_list_free (context->pending_nulls);
1657   context->pending_nulls = NULL;
1658 }
1659
1660 /* Use a platform-specific mechanism to look up the first argument to
1661  * the current process. 
1662  * Note if you implement this for other platforms, also add it to
1663  * tests/option-argv0.c
1664  */
1665 static char *
1666 platform_get_argv0 (void)
1667 {
1668 #if defined __linux
1669   char *cmdline;
1670   char *base_arg0;
1671   gsize len;
1672
1673   if (!g_file_get_contents ("/proc/self/cmdline",
1674                             &cmdline,
1675                             &len,
1676                             NULL))
1677     return NULL;
1678   /* Sanity check for a NUL terminator. */
1679   if (!memchr (cmdline, 0, len))
1680     return NULL;
1681   /* We could just return cmdline, but I think it's better
1682    * to hold on to a smaller malloc block; the arguments
1683    * could be large.
1684    */
1685   base_arg0 = g_path_get_basename (cmdline);
1686   g_free (cmdline);
1687   return base_arg0;
1688 #elif defined __OpenBSD__
1689   char **cmdline = NULL;
1690   char *base_arg0;
1691   gsize len = PATH_MAX;
1692
1693   int mib[] = { CTL_KERN, KERN_PROC_ARGS, getpid(), KERN_PROC_ARGV };
1694
1695   cmdline = (char **) realloc (cmdline, len);
1696
1697   if (sysctl (mib, G_N_ELEMENTS (mib), cmdline, &len, NULL, 0) == -1)
1698     {
1699       g_free (cmdline);
1700       return NULL;
1701     }
1702
1703   /* We could just return cmdline, but I think it's better
1704    * to hold on to a smaller malloc block; the arguments
1705    * could be large.
1706    */
1707   base_arg0 = g_path_get_basename (*cmdline);
1708   g_free (cmdline);
1709   return base_arg0;
1710 #endif
1711
1712   return NULL;
1713 }
1714
1715 /**
1716  * g_option_context_parse:
1717  * @context: a #GOptionContext
1718  * @argc: (inout) (allow-none): a pointer to the number of command line arguments
1719  * @argv: (inout) (array length=argc) (allow-none): a pointer to the array of command line arguments
1720  * @error: a return location for errors
1721  *
1722  * Parses the command line arguments, recognizing options
1723  * which have been added to @context. A side-effect of
1724  * calling this function is that g_set_prgname() will be
1725  * called.
1726  *
1727  * If the parsing is successful, any parsed arguments are
1728  * removed from the array and @argc and @argv are updated
1729  * accordingly. A '--' option is stripped from @argv
1730  * unless there are unparsed options before and after it,
1731  * or some of the options after it start with '-'. In case
1732  * of an error, @argc and @argv are left unmodified.
1733  *
1734  * If automatic <option>--help</option> support is enabled
1735  * (see g_option_context_set_help_enabled()), and the
1736  * @argv array contains one of the recognized help options,
1737  * this function will produce help output to stdout and
1738  * call <literal>exit (0)</literal>.
1739  *
1740  * Note that function depends on the
1741  * <link linkend="setlocale">current locale</link> for
1742  * automatic character set conversion of string and filename
1743  * arguments.
1744  *
1745  * Return value: %TRUE if the parsing was successful,
1746  *               %FALSE if an error occurred
1747  *
1748  * Since: 2.6
1749  **/
1750 gboolean
1751 g_option_context_parse (GOptionContext   *context,
1752                         gint             *argc,
1753                         gchar          ***argv,
1754                         GError          **error)
1755 {
1756   gint i, j, k;
1757   GList *list;
1758
1759   /* Set program name */
1760   if (!g_get_prgname())
1761     {
1762       gchar *prgname;
1763
1764       if (argc && argv && *argc)
1765         prgname = g_path_get_basename ((*argv)[0]);
1766       else
1767         prgname = platform_get_argv0 ();
1768
1769       if (prgname)
1770         g_set_prgname (prgname);
1771       else
1772         g_set_prgname ("<unknown>");
1773
1774       g_free (prgname);
1775     }
1776
1777   /* Call pre-parse hooks */
1778   list = context->groups;
1779   while (list)
1780     {
1781       GOptionGroup *group = list->data;
1782
1783       if (group->pre_parse_func)
1784         {
1785           if (!(* group->pre_parse_func) (context, group,
1786                                           group->user_data, error))
1787             goto fail;
1788         }
1789
1790       list = list->next;
1791     }
1792
1793   if (context->main_group && context->main_group->pre_parse_func)
1794     {
1795       if (!(* context->main_group->pre_parse_func) (context, context->main_group,
1796                                                     context->main_group->user_data, error))
1797         goto fail;
1798     }
1799
1800   if (argc && argv)
1801     {
1802       gboolean stop_parsing = FALSE;
1803       gboolean has_unknown = FALSE;
1804       gint separator_pos = 0;
1805
1806       for (i = 1; i < *argc; i++)
1807         {
1808           gchar *arg, *dash;
1809           gboolean parsed = FALSE;
1810
1811           if ((*argv)[i][0] == '-' && (*argv)[i][1] != '\0' && !stop_parsing)
1812             {
1813               if ((*argv)[i][1] == '-')
1814                 {
1815                   /* -- option */
1816
1817                   arg = (*argv)[i] + 2;
1818
1819                   /* '--' terminates list of arguments */
1820                   if (*arg == 0)
1821                     {
1822                       separator_pos = i;
1823                       stop_parsing = TRUE;
1824                       continue;
1825                     }
1826
1827                   /* Handle help options */
1828                   if (context->help_enabled)
1829                     {
1830                       if (strcmp (arg, "help") == 0)
1831                         print_help (context, TRUE, NULL);
1832                       else if (strcmp (arg, "help-all") == 0)
1833                         print_help (context, FALSE, NULL);
1834                       else if (strncmp (arg, "help-", 5) == 0)
1835                         {
1836                           list = context->groups;
1837
1838                           while (list)
1839                             {
1840                               GOptionGroup *group = list->data;
1841
1842                               if (strcmp (arg + 5, group->name) == 0)
1843                                 print_help (context, FALSE, group);
1844
1845                               list = list->next;
1846                             }
1847                         }
1848                     }
1849
1850                   if (context->main_group &&
1851                       !parse_long_option (context, context->main_group, &i, arg,
1852                                           FALSE, argc, argv, error, &parsed))
1853                     goto fail;
1854
1855                   if (parsed)
1856                     continue;
1857
1858                   /* Try the groups */
1859                   list = context->groups;
1860                   while (list)
1861                     {
1862                       GOptionGroup *group = list->data;
1863
1864                       if (!parse_long_option (context, group, &i, arg,
1865                                               FALSE, argc, argv, error, &parsed))
1866                         goto fail;
1867
1868                       if (parsed)
1869                         break;
1870
1871                       list = list->next;
1872                     }
1873
1874                   if (parsed)
1875                     continue;
1876
1877                   /* Now look for --<group>-<option> */
1878                   dash = strchr (arg, '-');
1879                   if (dash)
1880                     {
1881                       /* Try the groups */
1882                       list = context->groups;
1883                       while (list)
1884                         {
1885                           GOptionGroup *group = list->data;
1886
1887                           if (strncmp (group->name, arg, dash - arg) == 0)
1888                             {
1889                               if (!parse_long_option (context, group, &i, dash + 1,
1890                                                       TRUE, argc, argv, error, &parsed))
1891                                 goto fail;
1892
1893                               if (parsed)
1894                                 break;
1895                             }
1896
1897                           list = list->next;
1898                         }
1899                     }
1900
1901                   if (context->ignore_unknown)
1902                     continue;
1903                 }
1904               else
1905                 { /* short option */
1906                   gint new_i = i, arg_length;
1907                   gboolean *nulled_out = NULL;
1908                   gboolean has_h_entry = context_has_h_entry (context);
1909                   arg = (*argv)[i] + 1;
1910                   arg_length = strlen (arg);
1911                   nulled_out = g_newa (gboolean, arg_length);
1912                   memset (nulled_out, 0, arg_length * sizeof (gboolean));
1913                   for (j = 0; j < arg_length; j++)
1914                     {
1915                       if (context->help_enabled && (arg[j] == '?' ||
1916                         (arg[j] == 'h' && !has_h_entry)))
1917                         print_help (context, TRUE, NULL);
1918                       parsed = FALSE;
1919                       if (context->main_group &&
1920                           !parse_short_option (context, context->main_group,
1921                                                i, &new_i, arg[j],
1922                                                argc, argv, error, &parsed))
1923                         goto fail;
1924                       if (!parsed)
1925                         {
1926                           /* Try the groups */
1927                           list = context->groups;
1928                           while (list)
1929                             {
1930                               GOptionGroup *group = list->data;
1931                               if (!parse_short_option (context, group, i, &new_i, arg[j],
1932                                                        argc, argv, error, &parsed))
1933                                 goto fail;
1934                               if (parsed)
1935                                 break;
1936                               list = list->next;
1937                             }
1938                         }
1939
1940                       if (context->ignore_unknown && parsed)
1941                         nulled_out[j] = TRUE;
1942                       else if (context->ignore_unknown)
1943                         continue;
1944                       else if (!parsed)
1945                         break;
1946                       /* !context->ignore_unknown && parsed */
1947                     }
1948                   if (context->ignore_unknown)
1949                     {
1950                       gchar *new_arg = NULL;
1951                       gint arg_index = 0;
1952                       for (j = 0; j < arg_length; j++)
1953                         {
1954                           if (!nulled_out[j])
1955                             {
1956                               if (!new_arg)
1957                                 new_arg = g_malloc (arg_length + 1);
1958                               new_arg[arg_index++] = arg[j];
1959                             }
1960                         }
1961                       if (new_arg)
1962                         new_arg[arg_index] = '\0';
1963                       add_pending_null (context, &((*argv)[i]), new_arg);
1964                     }
1965                   else if (parsed)
1966                     {
1967                       add_pending_null (context, &((*argv)[i]), NULL);
1968                       i = new_i;
1969                     }
1970                 }
1971
1972               if (!parsed)
1973                 has_unknown = TRUE;
1974
1975               if (!parsed && !context->ignore_unknown)
1976                 {
1977                   g_set_error (error,
1978                                G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
1979                                    _("Unknown option %s"), (*argv)[i]);
1980                   goto fail;
1981                 }
1982             }
1983           else
1984             {
1985               /* Collect remaining args */
1986               if (context->main_group &&
1987                   !parse_remaining_arg (context, context->main_group, &i,
1988                                         argc, argv, error, &parsed))
1989                 goto fail;
1990
1991               if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
1992                 separator_pos = 0;
1993             }
1994         }
1995
1996       if (separator_pos > 0)
1997         add_pending_null (context, &((*argv)[separator_pos]), NULL);
1998
1999     }
2000
2001   /* Call post-parse hooks */
2002   list = context->groups;
2003   while (list)
2004     {
2005       GOptionGroup *group = list->data;
2006
2007       if (group->post_parse_func)
2008         {
2009           if (!(* group->post_parse_func) (context, group,
2010                                            group->user_data, error))
2011             goto fail;
2012         }
2013
2014       list = list->next;
2015     }
2016
2017   if (context->main_group && context->main_group->post_parse_func)
2018     {
2019       if (!(* context->main_group->post_parse_func) (context, context->main_group,
2020                                                      context->main_group->user_data, error))
2021         goto fail;
2022     }
2023
2024   if (argc && argv)
2025     {
2026       free_pending_nulls (context, TRUE);
2027
2028       for (i = 1; i < *argc; i++)
2029         {
2030           for (k = i; k < *argc; k++)
2031             if ((*argv)[k] != NULL)
2032               break;
2033
2034           if (k > i)
2035             {
2036               k -= i;
2037               for (j = i + k; j < *argc; j++)
2038                 {
2039                   (*argv)[j-k] = (*argv)[j];
2040                   (*argv)[j] = NULL;
2041                 }
2042               *argc -= k;
2043             }
2044         }
2045     }
2046
2047   return TRUE;
2048
2049  fail:
2050
2051   /* Call error hooks */
2052   list = context->groups;
2053   while (list)
2054     {
2055       GOptionGroup *group = list->data;
2056
2057       if (group->error_func)
2058         (* group->error_func) (context, group,
2059                                group->user_data, error);
2060
2061       list = list->next;
2062     }
2063
2064   if (context->main_group && context->main_group->error_func)
2065     (* context->main_group->error_func) (context, context->main_group,
2066                                          context->main_group->user_data, error);
2067
2068   free_changes_list (context, TRUE);
2069   free_pending_nulls (context, FALSE);
2070
2071   return FALSE;
2072 }
2073
2074 /**
2075  * g_option_group_new:
2076  * @name: the name for the option group, this is used to provide
2077  *   help for the options in this group with <option>--help-</option>@name
2078  * @description: a description for this group to be shown in
2079  *   <option>--help</option>. This string is translated using the translation
2080  *   domain or translation function of the group
2081  * @help_description: a description for the <option>--help-</option>@name option.
2082  *   This string is translated using the translation domain or translation function
2083  *   of the group
2084  * @user_data: (allow-none): user data that will be passed to the pre- and post-parse hooks,
2085  *   the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
2086  * @destroy: (allow-none): a function that will be called to free @user_data, or %NULL
2087  *
2088  * Creates a new #GOptionGroup.
2089  *
2090  * Return value: a newly created option group. It should be added
2091  *   to a #GOptionContext or freed with g_option_group_free().
2092  *
2093  * Since: 2.6
2094  **/
2095 GOptionGroup *
2096 g_option_group_new (const gchar    *name,
2097                     const gchar    *description,
2098                     const gchar    *help_description,
2099                     gpointer        user_data,
2100                     GDestroyNotify  destroy)
2101
2102 {
2103   GOptionGroup *group;
2104
2105   group = g_new0 (GOptionGroup, 1);
2106   group->name = g_strdup (name);
2107   group->description = g_strdup (description);
2108   group->help_description = g_strdup (help_description);
2109   group->user_data = user_data;
2110   group->destroy_notify = destroy;
2111
2112   return group;
2113 }
2114
2115
2116 /**
2117  * g_option_group_free:
2118  * @group: a #GOptionGroup
2119  *
2120  * Frees a #GOptionGroup. Note that you must <emphasis>not</emphasis>
2121  * free groups which have been added to a #GOptionContext.
2122  *
2123  * Since: 2.6
2124  **/
2125 void
2126 g_option_group_free (GOptionGroup *group)
2127 {
2128   g_return_if_fail (group != NULL);
2129
2130   g_free (group->name);
2131   g_free (group->description);
2132   g_free (group->help_description);
2133
2134   g_free (group->entries);
2135
2136   if (group->destroy_notify)
2137     (* group->destroy_notify) (group->user_data);
2138
2139   if (group->translate_notify)
2140     (* group->translate_notify) (group->translate_data);
2141
2142   g_free (group);
2143 }
2144
2145
2146 /**
2147  * g_option_group_add_entries:
2148  * @group: a #GOptionGroup
2149  * @entries: a %NULL-terminated array of #GOptionEntry<!-- -->s
2150  *
2151  * Adds the options specified in @entries to @group.
2152  *
2153  * Since: 2.6
2154  **/
2155 void
2156 g_option_group_add_entries (GOptionGroup       *group,
2157                             const GOptionEntry *entries)
2158 {
2159   gint i, n_entries;
2160
2161   g_return_if_fail (entries != NULL);
2162
2163   for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++) ;
2164
2165   group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
2166
2167   memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
2168
2169   for (i = group->n_entries; i < group->n_entries + n_entries; i++)
2170     {
2171       gchar c = group->entries[i].short_name;
2172
2173       if (c == '-' || (c != 0 && !g_ascii_isprint (c)))
2174         {
2175           g_warning (G_STRLOC ": ignoring invalid short option '%c' (%d) in entry %s:%s",
2176               c, c, group->name, group->entries[i].long_name);
2177           group->entries[i].short_name = '\0';
2178         }
2179
2180       if (group->entries[i].arg != G_OPTION_ARG_NONE &&
2181           (group->entries[i].flags & G_OPTION_FLAG_REVERSE) != 0)
2182         {
2183           g_warning (G_STRLOC ": ignoring reverse flag on option of arg-type %d in entry %s:%s",
2184               group->entries[i].arg, group->name, group->entries[i].long_name);
2185
2186           group->entries[i].flags &= ~G_OPTION_FLAG_REVERSE;
2187         }
2188
2189       if (group->entries[i].arg != G_OPTION_ARG_CALLBACK &&
2190           (group->entries[i].flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME)) != 0)
2191         {
2192           g_warning (G_STRLOC ": ignoring no-arg, optional-arg or filename flags (%d) on option of arg-type %d in entry %s:%s",
2193               group->entries[i].flags, group->entries[i].arg, group->name, group->entries[i].long_name);
2194
2195           group->entries[i].flags &= ~(G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME);
2196         }
2197     }
2198
2199   group->n_entries += n_entries;
2200 }
2201
2202 /**
2203  * g_option_group_set_parse_hooks:
2204  * @group: a #GOptionGroup
2205  * @pre_parse_func: (allow-none): a function to call before parsing, or %NULL
2206  * @post_parse_func: (allow-none): a function to call after parsing, or %NULL
2207  *
2208  * Associates two functions with @group which will be called
2209  * from g_option_context_parse() before the first option is parsed
2210  * and after the last option has been parsed, respectively.
2211  *
2212  * Note that the user data to be passed to @pre_parse_func and
2213  * @post_parse_func can be specified when constructing the group
2214  * with g_option_group_new().
2215  *
2216  * Since: 2.6
2217  **/
2218 void
2219 g_option_group_set_parse_hooks (GOptionGroup     *group,
2220                                 GOptionParseFunc  pre_parse_func,
2221                                 GOptionParseFunc  post_parse_func)
2222 {
2223   g_return_if_fail (group != NULL);
2224
2225   group->pre_parse_func = pre_parse_func;
2226   group->post_parse_func = post_parse_func;
2227 }
2228
2229 /**
2230  * g_option_group_set_error_hook:
2231  * @group: a #GOptionGroup
2232  * @error_func: a function to call when an error occurs
2233  *
2234  * Associates a function with @group which will be called
2235  * from g_option_context_parse() when an error occurs.
2236  *
2237  * Note that the user data to be passed to @error_func can be
2238  * specified when constructing the group with g_option_group_new().
2239  *
2240  * Since: 2.6
2241  **/
2242 void
2243 g_option_group_set_error_hook (GOptionGroup     *group,
2244                                GOptionErrorFunc  error_func)
2245 {
2246   g_return_if_fail (group != NULL);
2247
2248   group->error_func = error_func;
2249 }
2250
2251
2252 /**
2253  * g_option_group_set_translate_func:
2254  * @group: a #GOptionGroup
2255  * @func: (allow-none): the #GTranslateFunc, or %NULL
2256  * @data: (allow-none): user data to pass to @func, or %NULL
2257  * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2258  *
2259  * Sets the function which is used to translate user-visible
2260  * strings, for <option>--help</option> output. Different
2261  * groups can use different #GTranslateFunc<!-- -->s. If @func
2262  * is %NULL, strings are not translated.
2263  *
2264  * If you are using gettext(), you only need to set the translation
2265  * domain, see g_option_group_set_translation_domain().
2266  *
2267  * Since: 2.6
2268  **/
2269 void
2270 g_option_group_set_translate_func (GOptionGroup   *group,
2271                                    GTranslateFunc  func,
2272                                    gpointer        data,
2273                                    GDestroyNotify  destroy_notify)
2274 {
2275   g_return_if_fail (group != NULL);
2276
2277   if (group->translate_notify)
2278     group->translate_notify (group->translate_data);
2279
2280   group->translate_func = func;
2281   group->translate_data = data;
2282   group->translate_notify = destroy_notify;
2283 }
2284
2285 static const gchar *
2286 dgettext_swapped (const gchar *msgid,
2287                   const gchar *domainname)
2288 {
2289   return g_dgettext (domainname, msgid);
2290 }
2291
2292 /**
2293  * g_option_group_set_translation_domain:
2294  * @group: a #GOptionGroup
2295  * @domain: the domain to use
2296  *
2297  * A convenience function to use gettext() for translating
2298  * user-visible strings.
2299  *
2300  * Since: 2.6
2301  **/
2302 void
2303 g_option_group_set_translation_domain (GOptionGroup *group,
2304                                        const gchar  *domain)
2305 {
2306   g_return_if_fail (group != NULL);
2307
2308   g_option_group_set_translate_func (group,
2309                                      (GTranslateFunc)dgettext_swapped,
2310                                      g_strdup (domain),
2311                                      g_free);
2312 }
2313
2314 /**
2315  * g_option_context_set_translate_func:
2316  * @context: a #GOptionContext
2317  * @func: (allow-none): the #GTranslateFunc, or %NULL
2318  * @data: (allow-none): user data to pass to @func, or %NULL
2319  * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2320  *
2321  * Sets the function which is used to translate the contexts
2322  * user-visible strings, for <option>--help</option> output.
2323  * If @func is %NULL, strings are not translated.
2324  *
2325  * Note that option groups have their own translation functions,
2326  * this function only affects the @parameter_string (see g_option_context_new()),
2327  * the summary (see g_option_context_set_summary()) and the description
2328  * (see g_option_context_set_description()).
2329  *
2330  * If you are using gettext(), you only need to set the translation
2331  * domain, see g_option_context_set_translation_domain().
2332  *
2333  * Since: 2.12
2334  **/
2335 void
2336 g_option_context_set_translate_func (GOptionContext *context,
2337                                      GTranslateFunc func,
2338                                      gpointer       data,
2339                                      GDestroyNotify destroy_notify)
2340 {
2341   g_return_if_fail (context != NULL);
2342
2343   if (context->translate_notify)
2344     context->translate_notify (context->translate_data);
2345
2346   context->translate_func = func;
2347   context->translate_data = data;
2348   context->translate_notify = destroy_notify;
2349 }
2350
2351 /**
2352  * g_option_context_set_translation_domain:
2353  * @context: a #GOptionContext
2354  * @domain: the domain to use
2355  *
2356  * A convenience function to use gettext() for translating
2357  * user-visible strings.
2358  *
2359  * Since: 2.12
2360  **/
2361 void
2362 g_option_context_set_translation_domain (GOptionContext *context,
2363                                          const gchar     *domain)
2364 {
2365   g_return_if_fail (context != NULL);
2366
2367   g_option_context_set_translate_func (context,
2368                                        (GTranslateFunc)dgettext_swapped,
2369                                        g_strdup (domain),
2370                                        g_free);
2371 }
2372
2373 /**
2374  * g_option_context_set_summary:
2375  * @context: a #GOptionContext
2376  * @summary: (allow-none): a string to be shown in <option>--help</option> output
2377  *  before the list of options, or %NULL
2378  *
2379  * Adds a string to be displayed in <option>--help</option> output
2380  * before the list of options. This is typically a summary of the
2381  * program functionality.
2382  *
2383  * Note that the summary is translated (see
2384  * g_option_context_set_translate_func() and
2385  * g_option_context_set_translation_domain()).
2386  *
2387  * Since: 2.12
2388  */
2389 void
2390 g_option_context_set_summary (GOptionContext *context,
2391                               const gchar    *summary)
2392 {
2393   g_return_if_fail (context != NULL);
2394
2395   g_free (context->summary);
2396   context->summary = g_strdup (summary);
2397 }
2398
2399
2400 /**
2401  * g_option_context_get_summary:
2402  * @context: a #GOptionContext
2403  *
2404  * Returns the summary. See g_option_context_set_summary().
2405  *
2406  * Returns: the summary
2407  *
2408  * Since: 2.12
2409  */
2410 const gchar *
2411 g_option_context_get_summary (GOptionContext *context)
2412 {
2413   g_return_val_if_fail (context != NULL, NULL);
2414
2415   return context->summary;
2416 }
2417
2418 /**
2419  * g_option_context_set_description:
2420  * @context: a #GOptionContext
2421  * @description: (allow-none): a string to be shown in <option>--help</option> output
2422  *   after the list of options, or %NULL
2423  *
2424  * Adds a string to be displayed in <option>--help</option> output
2425  * after the list of options. This text often includes a bug reporting
2426  * address.
2427  *
2428  * Note that the summary is translated (see
2429  * g_option_context_set_translate_func()).
2430  *
2431  * Since: 2.12
2432  */
2433 void
2434 g_option_context_set_description (GOptionContext *context,
2435                                   const gchar    *description)
2436 {
2437   g_return_if_fail (context != NULL);
2438
2439   g_free (context->description);
2440   context->description = g_strdup (description);
2441 }
2442
2443
2444 /**
2445  * g_option_context_get_description:
2446  * @context: a #GOptionContext
2447  *
2448  * Returns the description. See g_option_context_set_description().
2449  *
2450  * Returns: the description
2451  *
2452  * Since: 2.12
2453  */
2454 const gchar *
2455 g_option_context_get_description (GOptionContext *context)
2456 {
2457   g_return_val_if_fail (context != NULL, NULL);
2458
2459   return context->description;
2460 }