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