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