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