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