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