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