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