Do not show empty groups in --help output. Initial patch from Yevgen
[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 static gboolean
524 group_has_visible_entries (GOptionGroup *group,
525                            gboolean      main_entries)
526 {
527   GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
528   GOptionEntry *entry;
529   gint i, l;
530
531   if (!main_entries)
532     reject_filter |= G_OPTION_FLAG_IN_MAIN;
533
534   for (i = 0, l = (group ? group->n_entries : 0); i < l; i++)
535     {
536       entry = &group->entries[i];
537
538       if (main_entries && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
539         continue;
540       if (!(entry->flags & reject_filter))
541         return TRUE;
542     }
543
544   return FALSE;
545 }
546
547 static gboolean
548 group_list_has_visible_entires (GList    *group_list,
549                                 gboolean  main_entries)
550 {
551   while (group_list)
552     {
553       if (group_has_visible_entries (group_list->data, main_entries))
554         return TRUE;
555
556       group_list = group_list->next;
557     }
558
559   return FALSE;
560 }
561
562 /**
563  * g_option_context_get_help: 
564  * @context: a #GOptionContext
565  * @main_help: if %TRUE, only include the main group 
566  * @group: the #GOptionGroup to create help for, or %NULL
567  *
568  * Returns a formatted, translated help text for the given context.
569  * To obtain the text produced by <option>--help</option>, call
570  * <literal>g_option_context_get_help (context, TRUE, NULL)</literal>.
571  * To obtain the text produced by <option>--help-all</option>, call
572  * <literal>g_option_context_get_help (context, FALSE, NULL)</literal>.
573  * To obtain the help text for an option group, call
574  * <literal>g_option_context_get_help (context, FALSE, group)</literal>.
575  *
576  * Returns: A newly allocated string containing the help text
577  *
578  * Since: 2.14
579  */
580 gchar *
581 g_option_context_get_help (GOptionContext *context,
582                            gboolean        main_help,
583                            GOptionGroup   *group)
584 {
585   GList *list;
586   gint max_length, len;
587   gint i;
588   GOptionEntry *entry;
589   GHashTable *shadow_map;
590   gboolean seen[256];
591   const gchar *rest_description;
592   GString *string;
593
594   string = g_string_sized_new (1024);
595
596   rest_description = NULL;
597   if (context->main_group)
598     {
599
600       for (i = 0; i < context->main_group->n_entries; i++)
601         {
602           entry = &context->main_group->entries[i];
603           if (entry->long_name[0] == 0)
604             {
605               rest_description = TRANSLATE (context->main_group, entry->arg_description);
606               break;
607             }
608         }
609     }
610
611   g_string_append_printf (string, "%s\n  %s %s", 
612                           _("Usage:"), g_get_prgname(), _("[OPTION...]"));
613
614   if (rest_description)
615     {
616       g_string_append (string, " ");
617       g_string_append (string, rest_description);
618     }
619
620   if (context->parameter_string)
621     {
622       g_string_append (string, " ");
623       g_string_append (string, TRANSLATE (context, context->parameter_string));
624     }
625
626   g_string_append (string, "\n\n");
627
628   if (context->summary)
629     {
630       g_string_append (string, TRANSLATE (context, context->summary));
631       g_string_append (string, "\n\n");
632     }
633
634   memset (seen, 0, sizeof (gboolean) * 256);
635   shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
636
637   if (context->main_group)
638     {
639       for (i = 0; i < context->main_group->n_entries; i++)
640         {
641           entry = &context->main_group->entries[i];
642           g_hash_table_insert (shadow_map, 
643                                (gpointer)entry->long_name, 
644                                entry);
645           
646           if (seen[(guchar)entry->short_name])
647             entry->short_name = 0;
648           else
649             seen[(guchar)entry->short_name] = TRUE;
650         }
651     }
652
653   list = context->groups;
654   while (list != NULL)
655     {
656       GOptionGroup *group = list->data;
657       for (i = 0; i < group->n_entries; i++)
658         {
659           entry = &group->entries[i];
660           if (g_hash_table_lookup (shadow_map, entry->long_name) && 
661               !(entry->flags & G_OPTION_FLAG_NOALIAS))
662             entry->long_name = g_strdup_printf ("%s-%s", group->name, entry->long_name);
663           else  
664             g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
665
666           if (seen[(guchar)entry->short_name] && 
667               !(entry->flags & G_OPTION_FLAG_NOALIAS))
668             entry->short_name = 0;
669           else
670             seen[(guchar)entry->short_name] = TRUE;
671         }
672       list = list->next;
673     }
674
675   g_hash_table_destroy (shadow_map);
676
677   list = context->groups;
678
679   max_length = _g_utf8_strwidth ("-?, --help", -1);
680
681   if (list)
682     {
683       len = _g_utf8_strwidth ("--help-all", -1);
684       max_length = MAX (max_length, len);
685     }
686
687   if (context->main_group)
688     {
689       len = calculate_max_length (context->main_group);
690       max_length = MAX (max_length, len);
691     }
692
693   while (list != NULL)
694     {
695       GOptionGroup *group = list->data;
696       
697       /* First, we check the --help-<groupname> options */
698       len = _g_utf8_strwidth ("--help-", -1) + _g_utf8_strwidth (group->name, -1);
699       max_length = MAX (max_length, len);
700
701       /* Then we go through the entries */
702       len = calculate_max_length (group);
703       max_length = MAX (max_length, len);
704       
705       list = list->next;
706     }
707
708   /* Add a bit of padding */
709   max_length += 4;
710
711   if (!group)
712     {
713       list = context->groups;
714       
715       g_string_append_printf (string, "%s\n  -%c, --%-*s %s\n", 
716                               _("Help Options:"), '?', max_length - 4, "help", 
717                               _("Show help options"));
718       
719       /* We only want --help-all when there are groups */
720       if (list)
721         g_string_append_printf (string, "  --%-*s %s\n", 
722                                 max_length, "help-all", 
723                                 _("Show all help options"));
724       
725       while (list)
726         {
727           GOptionGroup *group = list->data;
728
729           if (group_has_visible_entries (group, FALSE))
730             g_string_append_printf (string, "  --help-%-*s %s\n",
731                                     max_length - 5, group->name,
732                                     TRANSLATE (group, group->help_description));
733           
734           list = list->next;
735         }
736
737       g_string_append (string, "\n");
738     }
739
740   if (group)
741     {
742       /* Print a certain group */
743
744       if (group_has_visible_entries (group, FALSE))
745         {
746           g_string_append (string, TRANSLATE (group, group->description));
747           g_string_append (string, "\n");
748           for (i = 0; i < group->n_entries; i++)
749             print_entry (group, max_length, &group->entries[i], string);
750           g_string_append (string, "\n");
751         }
752     }
753   else if (!main_help)
754     {
755       /* Print all groups */
756
757       list = context->groups;
758
759       while (list)
760         {
761           GOptionGroup *group = list->data;
762
763           if (group_has_visible_entries (group, FALSE))
764             {
765               g_string_append (string, group->description);
766               g_string_append (string, "\n");
767               for (i = 0; i < group->n_entries; i++)
768                 if (!(group->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
769                   print_entry (group, max_length, &group->entries[i], string);
770           
771               g_string_append (string, "\n");
772             }
773
774           list = list->next;
775         }
776     }
777   
778   /* Print application options if --help or --help-all has been specified */
779   if ((main_help || !group) &&
780       (group_has_visible_entries (context->main_group, TRUE) ||
781        group_list_has_visible_entires (context->groups, TRUE)))
782     {
783       list = context->groups;
784
785       g_string_append (string,  _("Application Options:"));
786       g_string_append (string, "\n");
787       if (context->main_group)
788         for (i = 0; i < context->main_group->n_entries; i++) 
789           print_entry (context->main_group, max_length, 
790                        &context->main_group->entries[i], string);
791
792       while (list != NULL)
793         {
794           GOptionGroup *group = list->data;
795
796           /* Print main entries from other groups */
797           for (i = 0; i < group->n_entries; i++)
798             if (group->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
799               print_entry (group, max_length, &group->entries[i], string);
800           
801           list = list->next;
802         }
803
804       g_string_append (string, "\n");
805     }
806  
807   if (context->description)
808     {
809       g_string_append (string, TRANSLATE (context, context->description));
810       g_string_append (string, "\n");
811     }
812
813   return g_string_free (string, FALSE);
814 }
815
816 static void
817 print_help (GOptionContext *context,
818             gboolean        main_help,
819             GOptionGroup   *group)
820 {
821   gchar *help;
822
823   help = g_option_context_get_help (context, main_help, group);
824   g_print ("%s", help);
825   g_free (help);
826
827   exit (0);  
828 }
829
830 static gboolean
831 parse_int (const gchar *arg_name,
832            const gchar *arg,
833            gint        *result,
834            GError     **error)
835 {
836   gchar *end;
837   glong tmp;
838
839   errno = 0;
840   tmp = strtol (arg, &end, 0);
841   
842   if (*arg == '\0' || *end != '\0')
843     {
844       g_set_error (error,
845                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
846                    _("Cannot parse integer value '%s' for %s"),
847                    arg, arg_name);
848       return FALSE;
849     }
850
851   *result = tmp;
852   if (*result != tmp || errno == ERANGE)
853     {
854       g_set_error (error,
855                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
856                    _("Integer value '%s' for %s out of range"),
857                    arg, arg_name);
858       return FALSE;
859     }
860
861   return TRUE;
862 }
863
864
865 static gboolean
866 parse_double (const gchar *arg_name,
867            const gchar *arg,
868            gdouble        *result,
869            GError     **error)
870 {
871   gchar *end;
872   gdouble tmp;
873
874   errno = 0;
875   tmp = g_strtod (arg, &end);
876   
877   if (*arg == '\0' || *end != '\0')
878     {
879       g_set_error (error,
880                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
881                    _("Cannot parse double value '%s' for %s"),
882                    arg, arg_name);
883       return FALSE;
884     }
885   if (errno == ERANGE)
886     {
887       g_set_error (error,
888                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
889                    _("Double value '%s' for %s out of range"),
890                    arg, arg_name);
891       return FALSE;
892     }
893
894   *result = tmp;
895   
896   return TRUE;
897 }
898
899
900 static gboolean
901 parse_int64 (const gchar *arg_name,
902              const gchar *arg,
903              gint64      *result,
904              GError     **error)
905 {
906   gchar *end;
907   gint64 tmp;
908
909   errno = 0;
910   tmp = g_ascii_strtoll (arg, &end, 0);
911
912   if (*arg == '\0' || *end != '\0')
913     {
914       g_set_error (error,
915                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
916                    _("Cannot parse integer value '%s' for %s"),
917                    arg, arg_name);
918       return FALSE;
919     }
920   if (errno == ERANGE)
921     {
922       g_set_error (error,
923                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
924                    _("Integer value '%s' for %s out of range"),
925                    arg, arg_name);
926       return FALSE;
927     }
928
929   *result = tmp;
930   
931   return TRUE;
932 }
933
934
935 static Change *
936 get_change (GOptionContext *context,
937             GOptionArg      arg_type,
938             gpointer        arg_data)
939 {
940   GList *list;
941   Change *change = NULL;
942   
943   for (list = context->changes; list != NULL; list = list->next)
944     {
945       change = list->data;
946
947       if (change->arg_data == arg_data)
948         goto found;
949     }
950
951   change = g_new0 (Change, 1);
952   change->arg_type = arg_type;
953   change->arg_data = arg_data;
954   
955   context->changes = g_list_prepend (context->changes, change);
956   
957  found:
958
959   return change;
960 }
961
962 static void
963 add_pending_null (GOptionContext *context,
964                   gchar         **ptr,
965                   gchar          *value)
966 {
967   PendingNull *n;
968
969   n = g_new0 (PendingNull, 1);
970   n->ptr = ptr;
971   n->value = value;
972
973   context->pending_nulls = g_list_prepend (context->pending_nulls, n);
974 }
975                   
976 static gboolean
977 parse_arg (GOptionContext *context,
978            GOptionGroup   *group,
979            GOptionEntry   *entry,
980            const gchar    *value,
981            const gchar    *option_name,
982            GError        **error)
983      
984 {
985   Change *change;
986
987   g_assert (value || OPTIONAL_ARG (entry) || NO_ARG (entry));
988
989   switch (entry->arg)
990     {
991     case G_OPTION_ARG_NONE:
992       {
993         change = get_change (context, G_OPTION_ARG_NONE,
994                              entry->arg_data);
995
996         *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
997         break;
998       }      
999     case G_OPTION_ARG_STRING:
1000       {
1001         gchar *data;
1002         
1003         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1004
1005         if (!data)
1006           return FALSE;
1007
1008         change = get_change (context, G_OPTION_ARG_STRING,
1009                              entry->arg_data);
1010         g_free (change->allocated.str);
1011         
1012         change->prev.str = *(gchar **)entry->arg_data;
1013         change->allocated.str = data;
1014         
1015         *(gchar **)entry->arg_data = data;
1016         break;
1017       }
1018     case G_OPTION_ARG_STRING_ARRAY:
1019       {
1020         gchar *data;
1021
1022         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1023
1024         if (!data)
1025           return FALSE;
1026
1027         change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1028                              entry->arg_data);
1029
1030         if (change->allocated.array.len == 0)
1031           {
1032             change->prev.array = *(gchar ***)entry->arg_data;
1033             change->allocated.array.data = g_new (gchar *, 2);
1034           }
1035         else
1036           change->allocated.array.data =
1037             g_renew (gchar *, change->allocated.array.data,
1038                      change->allocated.array.len + 2);
1039
1040         change->allocated.array.data[change->allocated.array.len] = data;
1041         change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1042
1043         change->allocated.array.len ++;
1044
1045         *(gchar ***)entry->arg_data = change->allocated.array.data;
1046
1047         break;
1048       }
1049       
1050     case G_OPTION_ARG_FILENAME:
1051       {
1052         gchar *data;
1053
1054 #ifdef G_OS_WIN32
1055         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1056         
1057         if (!data)
1058           return FALSE;
1059 #else
1060         data = g_strdup (value);
1061 #endif
1062         change = get_change (context, G_OPTION_ARG_FILENAME,
1063                              entry->arg_data);
1064         g_free (change->allocated.str);
1065         
1066         change->prev.str = *(gchar **)entry->arg_data;
1067         change->allocated.str = data;
1068
1069         *(gchar **)entry->arg_data = data;
1070         break;
1071       }
1072
1073     case G_OPTION_ARG_FILENAME_ARRAY:
1074       {
1075         gchar *data;
1076         
1077 #ifdef G_OS_WIN32
1078         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1079         
1080         if (!data)
1081           return FALSE;
1082 #else
1083         data = g_strdup (value);
1084 #endif
1085         change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1086                              entry->arg_data);
1087
1088         if (change->allocated.array.len == 0)
1089           {
1090             change->prev.array = *(gchar ***)entry->arg_data;
1091             change->allocated.array.data = g_new (gchar *, 2);
1092           }
1093         else
1094           change->allocated.array.data =
1095             g_renew (gchar *, change->allocated.array.data,
1096                      change->allocated.array.len + 2);
1097
1098         change->allocated.array.data[change->allocated.array.len] = data;
1099         change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1100
1101         change->allocated.array.len ++;
1102
1103         *(gchar ***)entry->arg_data = change->allocated.array.data;
1104
1105         break;
1106       }
1107       
1108     case G_OPTION_ARG_INT:
1109       {
1110         gint data;
1111
1112         if (!parse_int (option_name, value,
1113                         &data,
1114                         error))
1115           return FALSE;
1116
1117         change = get_change (context, G_OPTION_ARG_INT,
1118                              entry->arg_data);
1119         change->prev.integer = *(gint *)entry->arg_data;
1120         *(gint *)entry->arg_data = data;
1121         break;
1122       }
1123     case G_OPTION_ARG_CALLBACK:
1124       {
1125         gchar *data;
1126         gboolean retval;
1127
1128         if (!value && entry->flags & G_OPTION_FLAG_OPTIONAL_ARG)
1129           data = NULL;
1130         else if (entry->flags & G_OPTION_FLAG_NO_ARG)
1131           data = NULL;
1132         else if (entry->flags & G_OPTION_FLAG_FILENAME)
1133           {
1134 #ifdef G_OS_WIN32
1135             data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1136 #else
1137             data = g_strdup (value);
1138 #endif
1139           }
1140         else
1141           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1142
1143         if (!(entry->flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG)) && 
1144             !data)
1145           return FALSE;
1146
1147         retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
1148         
1149         g_free (data);
1150         
1151         return retval;
1152         
1153         break;
1154       }
1155     case G_OPTION_ARG_DOUBLE:
1156       {
1157         gdouble data;
1158
1159         if (!parse_double (option_name, value,
1160                         &data,
1161                         error))
1162           {
1163             return FALSE;
1164           }
1165
1166         change = get_change (context, G_OPTION_ARG_DOUBLE,
1167                              entry->arg_data);
1168         change->prev.dbl = *(gdouble *)entry->arg_data;
1169         *(gdouble *)entry->arg_data = data;
1170         break;
1171       }
1172     case G_OPTION_ARG_INT64:
1173       {
1174         gint64 data;
1175
1176         if (!parse_int64 (option_name, value,
1177                          &data,
1178                          error))
1179           {
1180             return FALSE;
1181           }
1182
1183         change = get_change (context, G_OPTION_ARG_INT64,
1184                              entry->arg_data);
1185         change->prev.int64 = *(gint64 *)entry->arg_data;
1186         *(gint64 *)entry->arg_data = data;
1187         break;
1188       }
1189     default:
1190       g_assert_not_reached ();
1191     }
1192
1193   return TRUE;
1194 }
1195
1196 static gboolean
1197 parse_short_option (GOptionContext *context,
1198                     GOptionGroup   *group,
1199                     gint            index,
1200                     gint           *new_index,
1201                     gchar           arg,
1202                     gint           *argc,
1203                     gchar        ***argv,
1204                     GError        **error,
1205                     gboolean       *parsed)
1206 {
1207   gint j;
1208     
1209   for (j = 0; j < group->n_entries; j++)
1210     {
1211       if (arg == group->entries[j].short_name)
1212         {
1213           gchar *option_name;
1214           gchar *value = NULL;
1215           
1216           option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
1217
1218           if (NO_ARG (&group->entries[j]))
1219             value = NULL;
1220           else
1221             {
1222               if (*new_index > index)
1223                 {
1224                   g_set_error (error, 
1225                                G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1226                                _("Error parsing option %s"), option_name);
1227                   g_free (option_name);
1228                   return FALSE;
1229                 }
1230
1231               if (index < *argc - 1)
1232                 {
1233                   if (!OPTIONAL_ARG (&group->entries[j]))       
1234                     {    
1235                       value = (*argv)[index + 1];
1236                       add_pending_null (context, &((*argv)[index + 1]), NULL);
1237                       *new_index = index+1;
1238                     }
1239                   else
1240                     {
1241                       if ((*argv)[index + 1][0] == '-') 
1242                         value = NULL;
1243                       else
1244                         {
1245                           value = (*argv)[index + 1];
1246                           add_pending_null (context, &((*argv)[index + 1]), NULL);
1247                           *new_index = index + 1;
1248                         }
1249                     }
1250                 }
1251               else if (index >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1252                 value = NULL;
1253               else
1254                 {
1255                   g_set_error (error, 
1256                                G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1257                                _("Missing argument for %s"), option_name);
1258                   g_free (option_name);
1259                   return FALSE;
1260                 }
1261             }
1262
1263           if (!parse_arg (context, group, &group->entries[j], 
1264                           value, option_name, error))
1265             {
1266               g_free (option_name);
1267               return FALSE;
1268             }
1269           
1270           g_free (option_name);
1271           *parsed = TRUE;
1272         }
1273     }
1274
1275   return TRUE;
1276 }
1277
1278 static gboolean
1279 parse_long_option (GOptionContext *context,
1280                    GOptionGroup   *group,
1281                    gint           *index,
1282                    gchar          *arg,
1283                    gboolean        aliased,
1284                    gint           *argc,
1285                    gchar        ***argv,
1286                    GError        **error,
1287                    gboolean       *parsed)
1288 {
1289   gint j;
1290
1291   for (j = 0; j < group->n_entries; j++)
1292     {
1293       if (*index >= *argc)
1294         return TRUE;
1295
1296       if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
1297         continue;
1298
1299       if (NO_ARG (&group->entries[j]) &&
1300           strcmp (arg, group->entries[j].long_name) == 0)
1301         {
1302           gchar *option_name;
1303
1304           option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1305           parse_arg (context, group, &group->entries[j],
1306                      NULL, option_name, error);
1307           g_free(option_name);
1308           
1309           add_pending_null (context, &((*argv)[*index]), NULL);
1310           *parsed = TRUE;
1311         }
1312       else
1313         {
1314           gint len = strlen (group->entries[j].long_name);
1315           
1316           if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
1317               (arg[len] == '=' || arg[len] == 0))
1318             {
1319               gchar *value = NULL;
1320               gchar *option_name;
1321
1322               add_pending_null (context, &((*argv)[*index]), NULL);
1323               option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1324
1325               if (arg[len] == '=')
1326                 value = arg + len + 1;
1327               else if (*index < *argc - 1) 
1328                 {
1329                   if (!(group->entries[j].flags & G_OPTION_FLAG_OPTIONAL_ARG))  
1330                     {    
1331                       value = (*argv)[*index + 1];
1332                       add_pending_null (context, &((*argv)[*index + 1]), NULL);
1333                       (*index)++;
1334                     }
1335                   else
1336                     {
1337                       if ((*argv)[*index + 1][0] == '-') 
1338                         {
1339                           gboolean retval;
1340                           retval = parse_arg (context, group, &group->entries[j],
1341                                               NULL, option_name, error);
1342                           *parsed = TRUE;
1343                           g_free (option_name);
1344                           return retval;
1345                         }
1346                       else
1347                         {
1348                           value = (*argv)[*index + 1];
1349                           add_pending_null (context, &((*argv)[*index + 1]), NULL);
1350                           (*index)++;
1351                         }
1352                     }
1353                 }
1354               else if (*index >= *argc - 1 &&
1355                        group->entries[j].flags & G_OPTION_FLAG_OPTIONAL_ARG)
1356                 {
1357                     gboolean retval;
1358                     retval = parse_arg (context, group, &group->entries[j],
1359                                         NULL, option_name, error);
1360                     *parsed = TRUE;
1361                     g_free (option_name);
1362                     return retval;
1363                 }
1364               else
1365                 {
1366                   g_set_error (error, 
1367                                G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1368                                _("Missing argument for %s"), option_name);
1369                   g_free (option_name);
1370                   return FALSE;
1371                 }
1372
1373               if (!parse_arg (context, group, &group->entries[j], 
1374                               value, option_name, error))
1375                 {
1376                   g_free (option_name);
1377                   return FALSE;
1378                 }
1379
1380               g_free (option_name);
1381               *parsed = TRUE;
1382             } 
1383         }
1384     }
1385   
1386   return TRUE;
1387 }
1388
1389 static gboolean
1390 parse_remaining_arg (GOptionContext *context,
1391                      GOptionGroup   *group,
1392                      gint           *index,
1393                      gint           *argc,
1394                      gchar        ***argv,
1395                      GError        **error,
1396                      gboolean       *parsed)
1397 {
1398   gint j;
1399
1400   for (j = 0; j < group->n_entries; j++)
1401     {
1402       if (*index >= *argc)
1403         return TRUE;
1404
1405       if (group->entries[j].long_name[0])
1406         continue;
1407
1408       g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_CALLBACK ||
1409                             group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1410                             group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1411       
1412       add_pending_null (context, &((*argv)[*index]), NULL);
1413       
1414       if (!parse_arg (context, group, &group->entries[j], (*argv)[*index], "", error))
1415         return FALSE;
1416       
1417       *parsed = TRUE;
1418       return TRUE;
1419     }
1420
1421   return TRUE;
1422 }
1423
1424 static void
1425 free_changes_list (GOptionContext *context,
1426                    gboolean        revert)
1427 {
1428   GList *list;
1429
1430   for (list = context->changes; list != NULL; list = list->next)
1431     {
1432       Change *change = list->data;
1433
1434       if (revert)
1435         {
1436           switch (change->arg_type)
1437             {
1438             case G_OPTION_ARG_NONE:
1439               *(gboolean *)change->arg_data = change->prev.bool;
1440               break;
1441             case G_OPTION_ARG_INT:
1442               *(gint *)change->arg_data = change->prev.integer;
1443               break;
1444             case G_OPTION_ARG_STRING:
1445             case G_OPTION_ARG_FILENAME:
1446               g_free (change->allocated.str);
1447               *(gchar **)change->arg_data = change->prev.str;
1448               break;
1449             case G_OPTION_ARG_STRING_ARRAY:
1450             case G_OPTION_ARG_FILENAME_ARRAY:
1451               g_strfreev (change->allocated.array.data);
1452               *(gchar ***)change->arg_data = change->prev.array;
1453               break;
1454             case G_OPTION_ARG_DOUBLE:
1455               *(gdouble *)change->arg_data = change->prev.dbl;
1456               break;
1457             case G_OPTION_ARG_INT64:
1458               *(gint64 *)change->arg_data = change->prev.int64;
1459               break;
1460             default:
1461               g_assert_not_reached ();
1462             }
1463         }
1464       
1465       g_free (change);
1466     }
1467
1468   g_list_free (context->changes);
1469   context->changes = NULL;
1470 }
1471
1472 static void
1473 free_pending_nulls (GOptionContext *context,
1474                     gboolean        perform_nulls)
1475 {
1476   GList *list;
1477
1478   for (list = context->pending_nulls; list != NULL; list = list->next)
1479     {
1480       PendingNull *n = list->data;
1481
1482       if (perform_nulls)
1483         {
1484           if (n->value)
1485             {
1486               /* Copy back the short options */
1487               *(n->ptr)[0] = '-';             
1488               strcpy (*n->ptr + 1, n->value);
1489             }
1490           else
1491             *n->ptr = NULL;
1492         }
1493       
1494       g_free (n->value);
1495       g_free (n);
1496     }
1497
1498   g_list_free (context->pending_nulls);
1499   context->pending_nulls = NULL;
1500 }
1501
1502 /**
1503  * g_option_context_parse:
1504  * @context: a #GOptionContext
1505  * @argc: a pointer to the number of command line arguments
1506  * @argv: a pointer to the array of command line arguments
1507  * @error: a return location for errors 
1508  * 
1509  * Parses the command line arguments, recognizing options
1510  * which have been added to @context. A side-effect of 
1511  * calling this function is that g_set_prgname() will be
1512  * called.
1513  *
1514  * If the parsing is successful, any parsed arguments are
1515  * removed from the array and @argc and @argv are updated 
1516  * accordingly. A '--' option is stripped from @argv
1517  * unless there are unparsed options before and after it, 
1518  * or some of the options after it start with '-'. In case 
1519  * of an error, @argc and @argv are left unmodified. 
1520  *
1521  * If automatic <option>--help</option> support is enabled
1522  * (see g_option_context_set_help_enabled()), and the 
1523  * @argv array contains one of the recognized help options,
1524  * this function will produce help output to stdout and
1525  * call <literal>exit (0)</literal>.
1526  *
1527  * Note that function depends on the 
1528  * <link linkend="setlocale">current locale</link> for 
1529  * automatic character set conversion of string and filename
1530  * arguments.
1531  * 
1532  * Return value: %TRUE if the parsing was successful, 
1533  *               %FALSE if an error occurred
1534  *
1535  * Since: 2.6
1536  **/
1537 gboolean
1538 g_option_context_parse (GOptionContext   *context,
1539                         gint             *argc,
1540                         gchar          ***argv,
1541                         GError          **error)
1542 {
1543   gint i, j, k;
1544   GList *list;
1545
1546   /* Set program name */
1547   if (!g_get_prgname())
1548     {
1549       if (argc && argv && *argc)
1550         {
1551           gchar *prgname;
1552           
1553           prgname = g_path_get_basename ((*argv)[0]);
1554           g_set_prgname (prgname);
1555           g_free (prgname);
1556         }
1557       else
1558         g_set_prgname ("<unknown>");
1559     }
1560
1561   /* Call pre-parse hooks */
1562   list = context->groups;
1563   while (list)
1564     {
1565       GOptionGroup *group = list->data;
1566       
1567       if (group->pre_parse_func)
1568         {
1569           if (!(* group->pre_parse_func) (context, group,
1570                                           group->user_data, error))
1571             goto fail;
1572         }
1573       
1574       list = list->next;
1575     }
1576
1577   if (context->main_group && context->main_group->pre_parse_func)
1578     {
1579       if (!(* context->main_group->pre_parse_func) (context, context->main_group,
1580                                                     context->main_group->user_data, error))
1581         goto fail;
1582     }
1583
1584   if (argc && argv)
1585     {
1586       gboolean stop_parsing = FALSE;
1587       gboolean has_unknown = FALSE;
1588       gint separator_pos = 0;
1589
1590       for (i = 1; i < *argc; i++)
1591         {
1592           gchar *arg, *dash;
1593           gboolean parsed = FALSE;
1594
1595           if ((*argv)[i][0] == '-' && (*argv)[i][1] != '\0' && !stop_parsing)
1596             {
1597               if ((*argv)[i][1] == '-')
1598                 {
1599                   /* -- option */
1600
1601                   arg = (*argv)[i] + 2;
1602
1603                   /* '--' terminates list of arguments */
1604                   if (*arg == 0)
1605                     {
1606                       separator_pos = i;
1607                       stop_parsing = TRUE;
1608                       continue;
1609                     }
1610
1611                   /* Handle help options */
1612                   if (context->help_enabled)
1613                     {
1614                       if (strcmp (arg, "help") == 0)
1615                         print_help (context, TRUE, NULL);
1616                       else if (strcmp (arg, "help-all") == 0)
1617                         print_help (context, FALSE, NULL);                    
1618                       else if (strncmp (arg, "help-", 5) == 0)
1619                         {
1620                           GList *list;
1621                           
1622                           list = context->groups;
1623                           
1624                           while (list)
1625                             {
1626                               GOptionGroup *group = list->data;
1627                               
1628                               if (strcmp (arg + 5, group->name) == 0)
1629                                 print_help (context, FALSE, group);                                           
1630                               
1631                               list = list->next;
1632                             }
1633                         }
1634                     }
1635
1636                   if (context->main_group &&
1637                       !parse_long_option (context, context->main_group, &i, arg,
1638                                           FALSE, argc, argv, error, &parsed))
1639                     goto fail;
1640
1641                   if (parsed)
1642                     continue;
1643                   
1644                   /* Try the groups */
1645                   list = context->groups;
1646                   while (list)
1647                     {
1648                       GOptionGroup *group = list->data;
1649                       
1650                       if (!parse_long_option (context, group, &i, arg, 
1651                                               FALSE, argc, argv, error, &parsed))
1652                         goto fail;
1653                       
1654                       if (parsed)
1655                         break;
1656                       
1657                       list = list->next;
1658                     }
1659                   
1660                   if (parsed)
1661                     continue;
1662
1663                   /* Now look for --<group>-<option> */
1664                   dash = strchr (arg, '-');
1665                   if (dash)
1666                     {
1667                       /* Try the groups */
1668                       list = context->groups;
1669                       while (list)
1670                         {
1671                           GOptionGroup *group = list->data;
1672                           
1673                           if (strncmp (group->name, arg, dash - arg) == 0)
1674                             {
1675                               if (!parse_long_option (context, group, &i, dash + 1,
1676                                                       TRUE, argc, argv, error, &parsed))
1677                                 goto fail;
1678                               
1679                               if (parsed)
1680                                 break;
1681                             }
1682                           
1683                           list = list->next;
1684                         }
1685                     }
1686                   
1687                   if (context->ignore_unknown)
1688                     continue;
1689                 }
1690               else
1691                 { /* short option */
1692                   gint j, new_i = i, arg_length;
1693                   gboolean *nulled_out = NULL;
1694                   arg = (*argv)[i] + 1;
1695                   arg_length = strlen (arg);
1696                   nulled_out = g_newa (gboolean, arg_length);
1697                   memset (nulled_out, 0, arg_length * sizeof (gboolean));
1698                   for (j = 0; j < arg_length; j++)
1699                     {
1700                       if (context->help_enabled && arg[j] == '?')
1701                         print_help (context, TRUE, NULL);
1702                       parsed = FALSE;
1703                       if (context->main_group &&
1704                           !parse_short_option (context, context->main_group,
1705                                                i, &new_i, arg[j],
1706                                                argc, argv, error, &parsed))
1707                         goto fail;
1708                       if (!parsed)
1709                         {
1710                           /* Try the groups */
1711                           list = context->groups;
1712                           while (list)
1713                             {
1714                               GOptionGroup *group = list->data;
1715                               if (!parse_short_option (context, group, i, &new_i, arg[j],
1716                                                        argc, argv, error, &parsed))
1717                                 goto fail;
1718                               if (parsed)
1719                                 break;
1720                               list = list->next;
1721                             }
1722                         }
1723                       
1724                       if (context->ignore_unknown && parsed)
1725                         nulled_out[j] = TRUE;
1726                       else if (context->ignore_unknown)
1727                         continue;
1728                       else if (!parsed)
1729                         break;
1730                       /* !context->ignore_unknown && parsed */
1731                     }
1732                   if (context->ignore_unknown)
1733                     {
1734                       gchar *new_arg = NULL; 
1735                       gint arg_index = 0;
1736                       for (j = 0; j < arg_length; j++)
1737                         {
1738                           if (!nulled_out[j])
1739                             {
1740                               if (!new_arg)
1741                                 new_arg = g_malloc (arg_length + 1);
1742                               new_arg[arg_index++] = arg[j];
1743                             }
1744                         }
1745                       if (new_arg)
1746                         new_arg[arg_index] = '\0';
1747                       add_pending_null (context, &((*argv)[i]), new_arg);
1748                     }
1749                   else if (parsed)
1750                     {
1751                       add_pending_null (context, &((*argv)[i]), NULL);
1752                       i = new_i;
1753                     }
1754                 }
1755               
1756               if (!parsed)
1757                 has_unknown = TRUE;
1758
1759               if (!parsed && !context->ignore_unknown)
1760                 {
1761                   g_set_error (error,
1762                                G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
1763                                    _("Unknown option %s"), (*argv)[i]);
1764                   goto fail;
1765                 }
1766             }
1767           else
1768             {
1769               /* Collect remaining args */
1770               if (context->main_group &&
1771                   !parse_remaining_arg (context, context->main_group, &i,
1772                                         argc, argv, error, &parsed))
1773                 goto fail;
1774               
1775               if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
1776                 separator_pos = 0;
1777             }
1778         }
1779
1780       if (separator_pos > 0)
1781         add_pending_null (context, &((*argv)[separator_pos]), NULL);
1782         
1783     }
1784
1785   /* Call post-parse hooks */
1786   list = context->groups;
1787   while (list)
1788     {
1789       GOptionGroup *group = list->data;
1790       
1791       if (group->post_parse_func)
1792         {
1793           if (!(* group->post_parse_func) (context, group,
1794                                            group->user_data, error))
1795             goto fail;
1796         }
1797       
1798       list = list->next;
1799     }
1800   
1801   if (context->main_group && context->main_group->post_parse_func)
1802     {
1803       if (!(* context->main_group->post_parse_func) (context, context->main_group,
1804                                                      context->main_group->user_data, error))
1805         goto fail;
1806     }
1807   
1808   if (argc && argv)
1809     {
1810       free_pending_nulls (context, TRUE);
1811       
1812       for (i = 1; i < *argc; i++)
1813         {
1814           for (k = i; k < *argc; k++)
1815             if ((*argv)[k] != NULL)
1816               break;
1817           
1818           if (k > i)
1819             {
1820               k -= i;
1821               for (j = i + k; j < *argc; j++)
1822                 {
1823                   (*argv)[j-k] = (*argv)[j];
1824                   (*argv)[j] = NULL;
1825                 }
1826               *argc -= k;
1827             }
1828         }      
1829     }
1830
1831   return TRUE;
1832
1833  fail:
1834   
1835   /* Call error hooks */
1836   list = context->groups;
1837   while (list)
1838     {
1839       GOptionGroup *group = list->data;
1840       
1841       if (group->error_func)
1842         (* group->error_func) (context, group,
1843                                group->user_data, error);
1844       
1845       list = list->next;
1846     }
1847
1848   if (context->main_group && context->main_group->error_func)
1849     (* context->main_group->error_func) (context, context->main_group,
1850                                          context->main_group->user_data, error);
1851   
1852   free_changes_list (context, TRUE);
1853   free_pending_nulls (context, FALSE);
1854
1855   return FALSE;
1856 }
1857                                    
1858 /**
1859  * g_option_group_new:
1860  * @name: the name for the option group, this is used to provide
1861  *   help for the options in this group with <option>--help-</option>@name
1862  * @description: a description for this group to be shown in 
1863  *   <option>--help</option>. This string is translated using the translation
1864  *   domain or translation function of the group
1865  * @help_description: a description for the <option>--help-</option>@name option.
1866  *   This string is translated using the translation domain or translation function
1867  *   of the group
1868  * @user_data: user data that will be passed to the pre- and post-parse hooks,
1869  *   the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
1870  * @destroy: a function that will be called to free @user_data, or %NULL
1871  * 
1872  * Creates a new #GOptionGroup.
1873  * 
1874  * Return value: a newly created option group. It should be added 
1875  *   to a #GOptionContext or freed with g_option_group_free().
1876  *
1877  * Since: 2.6
1878  **/
1879 GOptionGroup *
1880 g_option_group_new (const gchar    *name,
1881                     const gchar    *description,
1882                     const gchar    *help_description,
1883                     gpointer        user_data,
1884                     GDestroyNotify  destroy)
1885
1886 {
1887   GOptionGroup *group;
1888
1889   group = g_new0 (GOptionGroup, 1);
1890   group->name = g_strdup (name);
1891   group->description = g_strdup (description);
1892   group->help_description = g_strdup (help_description);
1893   group->user_data = user_data;
1894   group->destroy_notify = destroy;
1895   
1896   return group;
1897 }
1898
1899
1900 /**
1901  * g_option_group_free:
1902  * @group: a #GOptionGroup
1903  * 
1904  * Frees a #GOptionGroup. Note that you must <emphasis>not</emphasis>
1905  * free groups which have been added to a #GOptionContext.
1906  *
1907  * Since: 2.6
1908  **/
1909 void
1910 g_option_group_free (GOptionGroup *group)
1911 {
1912   g_return_if_fail (group != NULL);
1913
1914   g_free (group->name);
1915   g_free (group->description);
1916   g_free (group->help_description);
1917
1918   g_free (group->entries);
1919   
1920   if (group->destroy_notify)
1921     (* group->destroy_notify) (group->user_data);
1922
1923   if (group->translate_notify)
1924     (* group->translate_notify) (group->translate_data);
1925   
1926   g_free (group);
1927 }
1928
1929
1930 /**
1931  * g_option_group_add_entries:
1932  * @group: a #GOptionGroup
1933  * @entries: a %NULL-terminated array of #GOptionEntry<!-- -->s
1934  * 
1935  * Adds the options specified in @entries to @group.
1936  *
1937  * Since: 2.6
1938  **/
1939 void
1940 g_option_group_add_entries (GOptionGroup       *group,
1941                             const GOptionEntry *entries)
1942 {
1943   gint i, n_entries;
1944   
1945   g_return_if_fail (entries != NULL);
1946
1947   for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++) ;
1948
1949   group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
1950
1951   memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
1952
1953   for (i = group->n_entries; i < group->n_entries + n_entries; i++)
1954     {
1955       gchar c = group->entries[i].short_name;
1956
1957       if (c)
1958         {
1959           if (c == '-' || !g_ascii_isprint (c))
1960             {
1961               g_warning (G_STRLOC": ignoring invalid short option '%c' (%d)", c, c);
1962               group->entries[i].short_name = 0;
1963             }
1964         }
1965     }
1966
1967   group->n_entries += n_entries;
1968 }
1969
1970 /**
1971  * g_option_group_set_parse_hooks:
1972  * @group: a #GOptionGroup
1973  * @pre_parse_func: a function to call before parsing, or %NULL
1974  * @post_parse_func: a function to call after parsing, or %NULL
1975  * 
1976  * Associates two functions with @group which will be called 
1977  * from g_option_context_parse() before the first option is parsed
1978  * and after the last option has been parsed, respectively.
1979  *
1980  * Note that the user data to be passed to @pre_parse_func and
1981  * @post_parse_func can be specified when constructing the group
1982  * with g_option_group_new().
1983  *
1984  * Since: 2.6
1985  **/
1986 void
1987 g_option_group_set_parse_hooks (GOptionGroup     *group,
1988                                 GOptionParseFunc  pre_parse_func,
1989                                 GOptionParseFunc  post_parse_func)
1990 {
1991   g_return_if_fail (group != NULL);
1992
1993   group->pre_parse_func = pre_parse_func;
1994   group->post_parse_func = post_parse_func;  
1995 }
1996
1997 /**
1998  * g_option_group_set_error_hook:
1999  * @group: a #GOptionGroup
2000  * @error_func: a function to call when an error occurs
2001  * 
2002  * Associates a function with @group which will be called 
2003  * from g_option_context_parse() when an error occurs.
2004  *
2005  * Note that the user data to be passed to @pre_parse_func and
2006  * @post_parse_func can be specified when constructing the group
2007  * with g_option_group_new().
2008  *
2009  * Since: 2.6
2010  **/
2011 void
2012 g_option_group_set_error_hook (GOptionGroup     *group,
2013                                GOptionErrorFunc  error_func)
2014 {
2015   g_return_if_fail (group != NULL);
2016
2017   group->error_func = error_func;  
2018 }
2019
2020
2021 /**
2022  * g_option_group_set_translate_func:
2023  * @group: a #GOptionGroup
2024  * @func: the #GTranslateFunc, or %NULL 
2025  * @data: user data to pass to @func, or %NULL
2026  * @destroy_notify: a function which gets called to free @data, or %NULL
2027  * 
2028  * Sets the function which is used to translate user-visible
2029  * strings, for <option>--help</option> output. Different
2030  * groups can use different #GTranslateFunc<!-- -->s. If @func
2031  * is %NULL, strings are not translated.
2032  *
2033  * If you are using gettext(), you only need to set the translation
2034  * domain, see g_option_group_set_translation_domain().
2035  *
2036  * Since: 2.6
2037  **/
2038 void
2039 g_option_group_set_translate_func (GOptionGroup   *group,
2040                                    GTranslateFunc  func,
2041                                    gpointer        data,
2042                                    GDestroyNotify  destroy_notify)
2043 {
2044   g_return_if_fail (group != NULL);
2045   
2046   if (group->translate_notify)
2047     group->translate_notify (group->translate_data);
2048       
2049   group->translate_func = func;
2050   group->translate_data = data;
2051   group->translate_notify = destroy_notify;
2052 }
2053
2054 static gchar *
2055 dgettext_swapped (const gchar *msgid, 
2056                   const gchar *domainname)
2057 {
2058   return dgettext (domainname, msgid);
2059 }
2060
2061 /**
2062  * g_option_group_set_translation_domain:
2063  * @group: a #GOptionGroup
2064  * @domain: the domain to use
2065  * 
2066  * A convenience function to use gettext() for translating
2067  * user-visible strings. 
2068  * 
2069  * Since: 2.6
2070  **/
2071 void
2072 g_option_group_set_translation_domain (GOptionGroup *group,
2073                                        const gchar  *domain)
2074 {
2075   g_return_if_fail (group != NULL);
2076
2077   g_option_group_set_translate_func (group, 
2078                                      (GTranslateFunc)dgettext_swapped,
2079                                      g_strdup (domain),
2080                                      g_free);
2081
2082
2083 /**
2084  * g_option_context_set_translate_func:
2085  * @context: a #GOptionContext
2086  * @func: the #GTranslateFunc, or %NULL 
2087  * @data: user data to pass to @func, or %NULL
2088  * @destroy_notify: a function which gets called to free @data, or %NULL
2089  * 
2090  * Sets the function which is used to translate the contexts 
2091  * user-visible strings, for <option>--help</option> output. 
2092  * If @func is %NULL, strings are not translated.
2093  *
2094  * Note that option groups have their own translation functions, 
2095  * this function only affects the @parameter_string (see g_option_context_new()), 
2096  * the summary (see g_option_context_set_summary()) and the description 
2097  * (see g_option_context_set_description()).
2098  *
2099  * If you are using gettext(), you only need to set the translation
2100  * domain, see g_context_group_set_translation_domain().
2101  *
2102  * Since: 2.12
2103  **/
2104 void
2105 g_option_context_set_translate_func (GOptionContext *context,
2106                                      GTranslateFunc func,
2107                                      gpointer       data,
2108                                      GDestroyNotify destroy_notify)
2109 {
2110   g_return_if_fail (context != NULL);
2111   
2112   if (context->translate_notify)
2113     context->translate_notify (context->translate_data);
2114       
2115   context->translate_func = func;
2116   context->translate_data = data;
2117   context->translate_notify = destroy_notify;
2118 }
2119
2120 /**
2121  * g_option_context_set_translation_domain:
2122  * @context: a #GOptionContext
2123  * @domain: the domain to use
2124  * 
2125  * A convenience function to use gettext() for translating
2126  * user-visible strings. 
2127  * 
2128  * Since: 2.12
2129  **/
2130 void
2131 g_option_context_set_translation_domain (GOptionContext *context,
2132                                          const gchar     *domain)
2133 {
2134   g_return_if_fail (context != NULL);
2135
2136   g_option_context_set_translate_func (context, 
2137                                        (GTranslateFunc)dgettext_swapped,
2138                                        g_strdup (domain),
2139                                        g_free);
2140 }
2141
2142 /**
2143  * g_option_context_set_summary:
2144  * @context: a #GOptionContext
2145  * @summary: a string to be shown in <option>--help</option> output 
2146  *  before the list of options, or %NULL
2147  * 
2148  * Adds a string to be displayed in <option>--help</option> output
2149  * before the list of options. This is typically a summary of the
2150  * program functionality. 
2151  *
2152  * Note that the summary is translated (see 
2153  * g_option_context_set_translate_func(), g_option_context_set_translation_domain()).
2154  *
2155  * Since: 2.12
2156  */
2157 void
2158 g_option_context_set_summary (GOptionContext *context,
2159                               const gchar    *summary)
2160 {
2161   g_return_if_fail (context != NULL);
2162
2163   g_free (context->summary);
2164   context->summary = g_strdup (summary);
2165 }
2166
2167
2168 /**
2169  * g_option_context_get_summary:
2170  * @context: a #GOptionContext
2171  * 
2172  * Returns the summary. See g_option_context_set_summary().
2173  *
2174  * Returns: the summary
2175  *
2176  * Since: 2.12
2177  */
2178 G_CONST_RETURN gchar *
2179 g_option_context_get_summary (GOptionContext *context)
2180 {
2181   g_return_val_if_fail (context != NULL, NULL);
2182
2183   return context->summary;
2184 }
2185
2186 /**
2187  * g_option_context_set_description:
2188  * @context: a #GOptionContext
2189  * @description: a string to be shown in <option>--help</option> output 
2190  *   after the list of options, or %NULL
2191  * 
2192  * Adds a string to be displayed in <option>--help</option> output
2193  * after the list of options. This text often includes a bug reporting
2194  * address.
2195  *
2196  * Note that the summary is translated (see 
2197  * g_option_context_set_translate_func()).
2198  *
2199  * Since: 2.12
2200  */
2201 void
2202 g_option_context_set_description (GOptionContext *context,
2203                                   const gchar    *description)
2204 {
2205   g_return_if_fail (context != NULL);
2206
2207   g_free (context->description);
2208   context->description = g_strdup (description);
2209 }
2210
2211
2212 /**
2213  * g_option_context_get_description:
2214  * @context: a #GOptionContext
2215  * 
2216  * Returns the description. See g_option_context_set_description().
2217  *
2218  * Returns: the description
2219  *
2220  * Since: 2.12
2221  */
2222 G_CONST_RETURN gchar *
2223 g_option_context_get_description (GOptionContext *context)
2224 {
2225   g_return_val_if_fail (context != NULL, NULL);
2226
2227   return context->description;
2228 }
2229
2230
2231 #define __G_OPTION_C__
2232 #include "galiasdef.c"