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