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