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