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