1 /* goption.c - Option parser
3 * Copyright (C) 1999, 2003 Red Hat Software
4 * Copyright (C) 2004 Anders Carlsson <andersca@gnome.org>
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.
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.
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.
34 #define TRANSLATE(group, str) (((group)->translate_func ? (* (group)->translate_func) ((str), (group)->translate_data) : (str)))
36 #define NO_ARG(entry) ((entry)->arg == G_OPTION_ARG_NONE || \
37 ((entry)->arg == G_OPTION_ARG_CALLBACK && \
38 ((entry)->flags & G_OPTION_FLAG_NO_ARG)))
40 #define OPTIONAL_ARG(entry) ((entry)->arg == G_OPTION_ARG_CALLBACK && \
41 (entry)->flags & G_OPTION_FLAG_OPTIONAL_ARG)
73 struct _GOptionContext
77 gchar *parameter_string;
81 GTranslateFunc translate_func;
82 GDestroyNotify translate_notify;
83 gpointer translate_data;
85 guint help_enabled : 1;
86 guint ignore_unknown : 1;
88 GOptionGroup *main_group;
90 /* We keep a list of change so we can revert them */
93 /* We also keep track of all argv elements
94 * that should be NULLed or modified.
103 gchar *help_description;
105 GDestroyNotify destroy_notify;
108 GTranslateFunc translate_func;
109 GDestroyNotify translate_notify;
110 gpointer translate_data;
112 GOptionEntry *entries;
115 GOptionParseFunc pre_parse_func;
116 GOptionParseFunc post_parse_func;
117 GOptionErrorFunc error_func;
120 static void free_changes_list (GOptionContext *context,
122 static void free_pending_nulls (GOptionContext *context,
123 gboolean perform_nulls);
127 _g_unichar_get_width (gunichar c)
129 if (G_UNLIKELY (g_unichar_iszerowidth (c)))
132 /* we ignore the fact that we should call g_unichar_iswide_cjk() under
133 * some locales (legacy East Asian ones) */
134 if (g_unichar_iswide (c))
141 _g_utf8_strwidth (const gchar *p,
145 const gchar *start = p;
146 g_return_val_if_fail (p != NULL || max == 0, 0);
153 len += _g_unichar_get_width (g_utf8_get_char (p));
154 p = g_utf8_next_char (p);
162 /* this case may not be quite correct */
164 len += _g_unichar_get_width (g_utf8_get_char (p));
165 p = g_utf8_next_char (p);
167 while (p - start < max && *p)
169 len += _g_unichar_get_width (g_utf8_get_char (p));
170 p = g_utf8_next_char (p);
179 g_option_error_quark (void)
181 return g_quark_from_static_string ("g-option-context-error-quark");
185 * g_option_context_new:
186 * @parameter_string: a string which is displayed in
187 * the first line of <option>--help</option> output, after the
189 * <literal><replaceable>programname</replaceable> [OPTION...]</literal>
191 * Creates a new option context.
193 * The @parameter_string can serve multiple purposes. It can be used
194 * to add descriptions for "rest" arguments, which are not parsed by
195 * the #GOptionContext, typically something like "FILES" or
196 * "FILE1 FILE2...". If you are using #G_OPTION_REMAINING for
197 * collecting "rest" arguments, GLib handles this automatically by
198 * using the @arg_description of the corresponding #GOptionEntry in
201 * Another usage is to give a short summary of the program
202 * functionality, like " - frob the strings", which will be displayed
203 * in the same line as the usage. For a longer description of the
204 * program functionality that should be displayed as a paragraph
205 * below the usage line, use g_option_context_set_summary().
207 * Note that the @parameter_string is translated (see
208 * g_option_context_set_translate_func()).
210 * Returns: a newly created #GOptionContext, which must be
211 * freed with g_option_context_free() after use.
216 g_option_context_new (const gchar *parameter_string)
219 GOptionContext *context;
221 context = g_new0 (GOptionContext, 1);
223 context->parameter_string = g_strdup (parameter_string);
224 context->help_enabled = TRUE;
225 context->ignore_unknown = FALSE;
231 * g_option_context_free:
232 * @context: a #GOptionContext
234 * Frees context and all the groups which have been
239 void g_option_context_free (GOptionContext *context)
241 g_return_if_fail (context != NULL);
243 g_list_foreach (context->groups, (GFunc)g_option_group_free, NULL);
244 g_list_free (context->groups);
246 if (context->main_group)
247 g_option_group_free (context->main_group);
249 free_changes_list (context, FALSE);
250 free_pending_nulls (context, FALSE);
252 g_free (context->parameter_string);
253 g_free (context->summary);
254 g_free (context->description);
256 if (context->translate_notify)
257 (* context->translate_notify) (context->translate_data);
264 * g_option_context_set_help_enabled:
265 * @context: a #GOptionContext
266 * @help_enabled: %TRUE to enable <option>--help</option>, %FALSE to disable it
268 * Enables or disables automatic generation of <option>--help</option>
269 * output. By default, g_option_context_parse() recognizes
270 * <option>--help</option>, <option>-?</option>, <option>--help-all</option>
271 * and <option>--help-</option><replaceable>groupname</replaceable> and creates
272 * suitable output to stdout.
276 void g_option_context_set_help_enabled (GOptionContext *context,
277 gboolean help_enabled)
280 g_return_if_fail (context != NULL);
282 context->help_enabled = help_enabled;
286 * g_option_context_get_help_enabled:
287 * @context: a #GOptionContext
289 * Returns whether automatic <option>--help</option> generation
290 * is turned on for @context. See g_option_context_set_help_enabled().
292 * Returns: %TRUE if automatic help generation is turned on.
297 g_option_context_get_help_enabled (GOptionContext *context)
299 g_return_val_if_fail (context != NULL, FALSE);
301 return context->help_enabled;
305 * g_option_context_set_ignore_unknown_options:
306 * @context: a #GOptionContext
307 * @ignore_unknown: %TRUE to ignore unknown options, %FALSE to produce
308 * an error when unknown options are met
310 * Sets whether to ignore unknown options or not. If an argument is
311 * ignored, it is left in the @argv array after parsing. By default,
312 * g_option_context_parse() treats unknown options as error.
314 * This setting does not affect non-option arguments (i.e. arguments
315 * which don't start with a dash). But note that GOption cannot reliably
316 * determine whether a non-option belongs to a preceding unknown option.
321 g_option_context_set_ignore_unknown_options (GOptionContext *context,
322 gboolean ignore_unknown)
324 g_return_if_fail (context != NULL);
326 context->ignore_unknown = ignore_unknown;
330 * g_option_context_get_ignore_unknown_options:
331 * @context: a #GOptionContext
333 * Returns whether unknown options are ignored or not. See
334 * g_option_context_set_ignore_unknown_options().
336 * Returns: %TRUE if unknown options are ignored.
341 g_option_context_get_ignore_unknown_options (GOptionContext *context)
343 g_return_val_if_fail (context != NULL, FALSE);
345 return context->ignore_unknown;
349 * g_option_context_add_group:
350 * @context: a #GOptionContext
351 * @group: the group to add
353 * Adds a #GOptionGroup to the @context, so that parsing with @context
354 * will recognize the options in the group. Note that the group will
355 * be freed together with the context when g_option_context_free() is
356 * called, so you must not free the group yourself after adding it
362 g_option_context_add_group (GOptionContext *context,
367 g_return_if_fail (context != NULL);
368 g_return_if_fail (group != NULL);
369 g_return_if_fail (group->name != NULL);
370 g_return_if_fail (group->description != NULL);
371 g_return_if_fail (group->help_description != NULL);
373 for (list = context->groups; list; list = list->next)
375 GOptionGroup *g = (GOptionGroup *)list->data;
377 if ((group->name == NULL && g->name == NULL) ||
378 (group->name && g->name && strcmp (group->name, g->name) == 0))
379 g_warning ("A group named \"%s\" is already part of this GOptionContext",
383 context->groups = g_list_append (context->groups, group);
387 * g_option_context_set_main_group:
388 * @context: a #GOptionContext
389 * @group: the group to set as main group
391 * Sets a #GOptionGroup as main group of the @context.
392 * This has the same effect as calling g_option_context_add_group(),
393 * the only difference is that the options in the main group are
394 * treated differently when generating <option>--help</option> output.
399 g_option_context_set_main_group (GOptionContext *context,
402 g_return_if_fail (context != NULL);
403 g_return_if_fail (group != NULL);
405 if (context->main_group)
407 g_warning ("This GOptionContext already has a main group");
412 context->main_group = group;
416 * g_option_context_get_main_group:
417 * @context: a #GOptionContext
419 * Returns a pointer to the main group of @context.
421 * Return value: the main group of @context, or %NULL if @context doesn't
422 * have a main group. Note that group belongs to @context and should
423 * not be modified or freed.
428 g_option_context_get_main_group (GOptionContext *context)
430 g_return_val_if_fail (context != NULL, NULL);
432 return context->main_group;
436 * g_option_context_add_main_entries:
437 * @context: a #GOptionContext
438 * @entries: a %NULL-terminated array of #GOptionEntry<!-- -->s
439 * @translation_domain: a translation domain to use for translating
440 * the <option>--help</option> output for the options in @entries
441 * with gettext(), or %NULL
443 * A convenience function which creates a main group if it doesn't
444 * exist, adds the @entries to it and sets the translation domain.
449 g_option_context_add_main_entries (GOptionContext *context,
450 const GOptionEntry *entries,
451 const gchar *translation_domain)
453 g_return_if_fail (entries != NULL);
455 if (!context->main_group)
456 context->main_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
458 g_option_group_add_entries (context->main_group, entries);
459 g_option_group_set_translation_domain (context->main_group, translation_domain);
463 calculate_max_length (GOptionGroup *group)
466 gint i, len, max_length;
470 for (i = 0; i < group->n_entries; i++)
472 entry = &group->entries[i];
474 if (entry->flags & G_OPTION_FLAG_HIDDEN)
477 len = _g_utf8_strwidth (entry->long_name, -1);
479 if (entry->short_name)
482 if (!NO_ARG (entry) && entry->arg_description)
483 len += 1 + _g_utf8_strwidth (TRANSLATE (group, entry->arg_description), -1);
485 max_length = MAX (max_length, len);
492 print_entry (GOptionGroup *group,
494 const GOptionEntry *entry)
498 if (entry->flags & G_OPTION_FLAG_HIDDEN)
501 if (entry->long_name[0] == 0)
504 str = g_string_new (NULL);
506 if (entry->short_name)
507 g_string_append_printf (str, " -%c, --%s", entry->short_name, entry->long_name);
509 g_string_append_printf (str, " --%s", entry->long_name);
511 if (entry->arg_description)
512 g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
514 g_print ("%s%*s %s\n", str->str,
515 (int) (max_length + 4 - _g_utf8_strwidth (str->str, -1)), "",
516 entry->description ? TRANSLATE (group, entry->description) : "");
517 g_string_free (str, TRUE);
521 print_help (GOptionContext *context,
526 gint max_length, len;
529 GHashTable *shadow_map;
531 const gchar *rest_description;
533 rest_description = NULL;
534 if (context->main_group)
537 for (i = 0; i < context->main_group->n_entries; i++)
539 entry = &context->main_group->entries[i];
540 if (entry->long_name[0] == 0)
542 rest_description = TRANSLATE (context->main_group, entry->arg_description);
548 g_print ("%s\n %s %s%s%s%s%s\n\n",
549 _("Usage:"), g_get_prgname(), _("[OPTION...]"),
550 rest_description ? " " : "",
551 rest_description ? rest_description : "",
552 context->parameter_string ? " " : "",
553 context->parameter_string ? TRANSLATE (context, context->parameter_string) : "");
555 if (context->summary)
556 g_print ("%s\n\n", TRANSLATE (context, context->summary));
558 memset (seen, 0, sizeof (gboolean) * 256);
559 shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
561 if (context->main_group)
563 for (i = 0; i < context->main_group->n_entries; i++)
565 entry = &context->main_group->entries[i];
566 g_hash_table_insert (shadow_map,
567 (gpointer)entry->long_name,
570 if (seen[(guchar)entry->short_name])
571 entry->short_name = 0;
573 seen[(guchar)entry->short_name] = TRUE;
577 list = context->groups;
580 GOptionGroup *group = list->data;
581 for (i = 0; i < group->n_entries; i++)
583 entry = &group->entries[i];
584 if (g_hash_table_lookup (shadow_map, entry->long_name) &&
585 !(entry->flags && G_OPTION_FLAG_NOALIAS))
586 entry->long_name = g_strdup_printf ("%s-%s", group->name, entry->long_name);
588 g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
590 if (seen[(guchar)entry->short_name] &&
591 !(entry->flags && G_OPTION_FLAG_NOALIAS))
592 entry->short_name = 0;
594 seen[(guchar)entry->short_name] = TRUE;
599 g_hash_table_destroy (shadow_map);
601 list = context->groups;
603 max_length = _g_utf8_strwidth ("-?, --help", -1);
607 len = _g_utf8_strwidth ("--help-all", -1);
608 max_length = MAX (max_length, len);
611 if (context->main_group)
613 len = calculate_max_length (context->main_group);
614 max_length = MAX (max_length, len);
619 GOptionGroup *group = list->data;
621 /* First, we check the --help-<groupname> options */
622 len = _g_utf8_strwidth ("--help-", -1) + _g_utf8_strwidth (group->name, -1);
623 max_length = MAX (max_length, len);
625 /* Then we go through the entries */
626 len = calculate_max_length (group);
627 max_length = MAX (max_length, len);
632 /* Add a bit of padding */
637 list = context->groups;
639 g_print ("%s\n -%c, --%-*s %s\n",
640 _("Help Options:"), '?', max_length - 4, "help",
641 _("Show help options"));
643 /* We only want --help-all when there are groups */
645 g_print (" --%-*s %s\n", max_length, "help-all",
646 _("Show all help options"));
650 GOptionGroup *group = list->data;
652 g_print (" --help-%-*s %s\n", max_length - 5, group->name,
653 TRANSLATE (group, group->help_description));
663 /* Print a certain group */
665 g_print ("%s\n", TRANSLATE (group, group->description));
666 for (i = 0; i < group->n_entries; i++)
667 print_entry (group, max_length, &group->entries[i]);
672 /* Print all groups */
674 list = context->groups;
678 GOptionGroup *group = list->data;
680 g_print ("%s\n", group->description);
682 for (i = 0; i < group->n_entries; i++)
683 if (!(group->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
684 print_entry (group, max_length, &group->entries[i]);
691 /* Print application options if --help or --help-all has been specified */
692 if (main_help || !group)
694 list = context->groups;
696 g_print ("%s\n", _("Application Options:"));
698 if (context->main_group)
699 for (i = 0; i < context->main_group->n_entries; i++)
700 print_entry (context->main_group, max_length,
701 &context->main_group->entries[i]);
705 GOptionGroup *group = list->data;
707 /* Print main entries from other groups */
708 for (i = 0; i < group->n_entries; i++)
709 if (group->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
710 print_entry (group, max_length, &group->entries[i]);
718 if (context->description)
719 g_print ("%s\n", TRANSLATE (context, context->description));
725 parse_int (const gchar *arg_name,
734 tmp = strtol (arg, &end, 0);
736 if (*arg == '\0' || *end != '\0')
739 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
740 _("Cannot parse integer value '%s' for %s"),
746 if (*result != tmp || errno == ERANGE)
749 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
750 _("Integer value '%s' for %s out of range"),
760 parse_double (const gchar *arg_name,
769 tmp = g_strtod (arg, &end);
771 if (*arg == '\0' || *end != '\0')
774 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
775 _("Cannot parse double value '%s' for %s"),
782 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
783 _("Double value '%s' for %s out of range"),
795 parse_int64 (const gchar *arg_name,
804 tmp = g_ascii_strtoll (arg, &end, 0);
806 if (*arg == '\0' || *end != '\0')
809 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
810 _("Cannot parse integer value '%s' for %s"),
817 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
818 _("Integer value '%s' for %s out of range"),
830 get_change (GOptionContext *context,
835 Change *change = NULL;
837 for (list = context->changes; list != NULL; list = list->next)
841 if (change->arg_data == arg_data)
845 change = g_new0 (Change, 1);
846 change->arg_type = arg_type;
847 change->arg_data = arg_data;
849 context->changes = g_list_prepend (context->changes, change);
857 add_pending_null (GOptionContext *context,
863 n = g_new0 (PendingNull, 1);
867 context->pending_nulls = g_list_prepend (context->pending_nulls, n);
871 parse_arg (GOptionContext *context,
875 const gchar *option_name,
881 g_assert (value || OPTIONAL_ARG (entry) || NO_ARG (entry));
885 case G_OPTION_ARG_NONE:
887 change = get_change (context, G_OPTION_ARG_NONE,
890 *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
893 case G_OPTION_ARG_STRING:
897 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
902 change = get_change (context, G_OPTION_ARG_STRING,
904 g_free (change->allocated.str);
906 change->prev.str = *(gchar **)entry->arg_data;
907 change->allocated.str = data;
909 *(gchar **)entry->arg_data = data;
912 case G_OPTION_ARG_STRING_ARRAY:
916 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
921 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
924 if (change->allocated.array.len == 0)
926 change->prev.array = *(gchar ***)entry->arg_data;
927 change->allocated.array.data = g_new (gchar *, 2);
930 change->allocated.array.data =
931 g_renew (gchar *, change->allocated.array.data,
932 change->allocated.array.len + 2);
934 change->allocated.array.data[change->allocated.array.len] = data;
935 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
937 change->allocated.array.len ++;
939 *(gchar ***)entry->arg_data = change->allocated.array.data;
944 case G_OPTION_ARG_FILENAME:
949 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
954 data = g_strdup (value);
956 change = get_change (context, G_OPTION_ARG_FILENAME,
958 g_free (change->allocated.str);
960 change->prev.str = *(gchar **)entry->arg_data;
961 change->allocated.str = data;
963 *(gchar **)entry->arg_data = data;
967 case G_OPTION_ARG_FILENAME_ARRAY:
972 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
977 data = g_strdup (value);
979 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
982 if (change->allocated.array.len == 0)
984 change->prev.array = *(gchar ***)entry->arg_data;
985 change->allocated.array.data = g_new (gchar *, 2);
988 change->allocated.array.data =
989 g_renew (gchar *, change->allocated.array.data,
990 change->allocated.array.len + 2);
992 change->allocated.array.data[change->allocated.array.len] = data;
993 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
995 change->allocated.array.len ++;
997 *(gchar ***)entry->arg_data = change->allocated.array.data;
1002 case G_OPTION_ARG_INT:
1006 if (!parse_int (option_name, value,
1011 change = get_change (context, G_OPTION_ARG_INT,
1013 change->prev.integer = *(gint *)entry->arg_data;
1014 *(gint *)entry->arg_data = data;
1017 case G_OPTION_ARG_CALLBACK:
1022 if (!value && entry->flags & G_OPTION_FLAG_OPTIONAL_ARG)
1024 else if (entry->flags & G_OPTION_FLAG_NO_ARG)
1026 else if (entry->flags & G_OPTION_FLAG_FILENAME)
1029 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1031 data = g_strdup (value);
1035 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1037 if (!(entry->flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG)) &&
1041 retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
1049 case G_OPTION_ARG_DOUBLE:
1053 if (!parse_double (option_name, value,
1060 change = get_change (context, G_OPTION_ARG_DOUBLE,
1062 change->prev.dbl = *(gdouble *)entry->arg_data;
1063 *(gdouble *)entry->arg_data = data;
1066 case G_OPTION_ARG_INT64:
1070 if (!parse_int64 (option_name, value,
1077 change = get_change (context, G_OPTION_ARG_INT64,
1079 change->prev.int64 = *(gint64 *)entry->arg_data;
1080 *(gint64 *)entry->arg_data = data;
1084 g_assert_not_reached ();
1091 parse_short_option (GOptionContext *context,
1092 GOptionGroup *group,
1103 for (j = 0; j < group->n_entries; j++)
1105 if (arg == group->entries[j].short_name)
1108 gchar *value = NULL;
1110 option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
1112 if (NO_ARG (&group->entries[j]))
1116 if (*new_index > index)
1119 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1120 _("Error parsing option %s"), option_name);
1121 g_free (option_name);
1125 if (index < *argc - 1)
1127 if (!OPTIONAL_ARG (&group->entries[j]))
1129 value = (*argv)[index + 1];
1130 add_pending_null (context, &((*argv)[index + 1]), NULL);
1131 *new_index = index+1;
1135 if ((*argv)[index + 1][0] == '-')
1139 value = (*argv)[index + 1];
1140 add_pending_null (context, &((*argv)[index + 1]), NULL);
1141 *new_index = index + 1;
1145 else if (index >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1150 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1151 _("Missing argument for %s"), option_name);
1152 g_free (option_name);
1157 if (!parse_arg (context, group, &group->entries[j],
1158 value, option_name, error))
1160 g_free (option_name);
1164 g_free (option_name);
1173 parse_long_option (GOptionContext *context,
1174 GOptionGroup *group,
1185 for (j = 0; j < group->n_entries; j++)
1187 if (*index >= *argc)
1190 if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
1193 if (NO_ARG (&group->entries[j]) &&
1194 strcmp (arg, group->entries[j].long_name) == 0)
1198 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1199 parse_arg (context, group, &group->entries[j],
1200 NULL, option_name, error);
1201 g_free(option_name);
1203 add_pending_null (context, &((*argv)[*index]), NULL);
1208 gint len = strlen (group->entries[j].long_name);
1210 if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
1211 (arg[len] == '=' || arg[len] == 0))
1213 gchar *value = NULL;
1216 add_pending_null (context, &((*argv)[*index]), NULL);
1217 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1219 if (arg[len] == '=')
1220 value = arg + len + 1;
1221 else if (*index < *argc - 1)
1223 if (!(group->entries[j].flags & G_OPTION_FLAG_OPTIONAL_ARG))
1225 value = (*argv)[*index + 1];
1226 add_pending_null (context, &((*argv)[*index + 1]), NULL);
1231 if ((*argv)[*index + 1][0] == '-')
1234 retval = parse_arg (context, group, &group->entries[j],
1235 NULL, option_name, error);
1237 g_free (option_name);
1242 value = (*argv)[*index + 1];
1243 add_pending_null (context, &((*argv)[*index + 1]), NULL);
1248 else if (*index >= *argc - 1 &&
1249 group->entries[j].flags & G_OPTION_FLAG_OPTIONAL_ARG)
1252 retval = parse_arg (context, group, &group->entries[j],
1253 NULL, option_name, error);
1255 g_free (option_name);
1261 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1262 _("Missing argument for %s"), option_name);
1263 g_free (option_name);
1267 if (!parse_arg (context, group, &group->entries[j],
1268 value, option_name, error))
1270 g_free (option_name);
1274 g_free (option_name);
1284 parse_remaining_arg (GOptionContext *context,
1285 GOptionGroup *group,
1294 for (j = 0; j < group->n_entries; j++)
1296 if (*index >= *argc)
1299 if (group->entries[j].long_name[0])
1302 g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1303 group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1305 add_pending_null (context, &((*argv)[*index]), NULL);
1307 if (!parse_arg (context, group, &group->entries[j], (*argv)[*index], "", error))
1318 free_changes_list (GOptionContext *context,
1323 for (list = context->changes; list != NULL; list = list->next)
1325 Change *change = list->data;
1329 switch (change->arg_type)
1331 case G_OPTION_ARG_NONE:
1332 *(gboolean *)change->arg_data = change->prev.bool;
1334 case G_OPTION_ARG_INT:
1335 *(gint *)change->arg_data = change->prev.integer;
1337 case G_OPTION_ARG_STRING:
1338 case G_OPTION_ARG_FILENAME:
1339 g_free (change->allocated.str);
1340 *(gchar **)change->arg_data = change->prev.str;
1342 case G_OPTION_ARG_STRING_ARRAY:
1343 case G_OPTION_ARG_FILENAME_ARRAY:
1344 g_strfreev (change->allocated.array.data);
1345 *(gchar ***)change->arg_data = change->prev.array;
1347 case G_OPTION_ARG_DOUBLE:
1348 *(gdouble *)change->arg_data = change->prev.dbl;
1350 case G_OPTION_ARG_INT64:
1351 *(gint64 *)change->arg_data = change->prev.int64;
1354 g_assert_not_reached ();
1361 g_list_free (context->changes);
1362 context->changes = NULL;
1366 free_pending_nulls (GOptionContext *context,
1367 gboolean perform_nulls)
1371 for (list = context->pending_nulls; list != NULL; list = list->next)
1373 PendingNull *n = list->data;
1379 /* Copy back the short options */
1381 strcpy (*n->ptr + 1, n->value);
1391 g_list_free (context->pending_nulls);
1392 context->pending_nulls = NULL;
1396 * g_option_context_parse:
1397 * @context: a #GOptionContext
1398 * @argc: a pointer to the number of command line arguments
1399 * @argv: a pointer to the array of command line arguments
1400 * @error: a return location for errors
1402 * Parses the command line arguments, recognizing options
1403 * which have been added to @context. A side-effect of
1404 * calling this function is that g_set_prgname() will be
1407 * If the parsing is successful, any parsed arguments are
1408 * removed from the array and @argc and @argv are updated
1409 * accordingly. A '--' option is stripped from @argv
1410 * unless there are unparsed options before and after it,
1411 * or some of the options after it start with '-'. In case
1412 * of an error, @argc and @argv are left unmodified.
1414 * If automatic <option>--help</option> support is enabled
1415 * (see g_option_context_set_help_enabled()), and the
1416 * @argv array contains one of the recognized help options,
1417 * this function will produce help output to stdout and
1418 * call <literal>exit (0)</literal>.
1420 * Note that function depends on the
1421 * <link linkend="setlocale">current locale</link> for
1422 * automatic character set conversion of string and filename
1425 * Return value: %TRUE if the parsing was successful,
1426 * %FALSE if an error occurred
1431 g_option_context_parse (GOptionContext *context,
1439 /* Set program name */
1440 if (!g_get_prgname())
1442 if (argc && argv && *argc)
1446 prgname = g_path_get_basename ((*argv)[0]);
1447 g_set_prgname (prgname);
1451 g_set_prgname ("<unknown>");
1454 /* Call pre-parse hooks */
1455 list = context->groups;
1458 GOptionGroup *group = list->data;
1460 if (group->pre_parse_func)
1462 if (!(* group->pre_parse_func) (context, group,
1463 group->user_data, error))
1470 if (context->main_group && context->main_group->pre_parse_func)
1472 if (!(* context->main_group->pre_parse_func) (context, context->main_group,
1473 context->main_group->user_data, error))
1479 gboolean stop_parsing = FALSE;
1480 gboolean has_unknown = FALSE;
1481 gint separator_pos = 0;
1483 for (i = 1; i < *argc; i++)
1486 gboolean parsed = FALSE;
1488 if ((*argv)[i][0] == '-' && (*argv)[i][1] != '\0' && !stop_parsing)
1490 if ((*argv)[i][1] == '-')
1494 arg = (*argv)[i] + 2;
1496 /* '--' terminates list of arguments */
1500 stop_parsing = TRUE;
1504 /* Handle help options */
1505 if (context->help_enabled)
1507 if (strcmp (arg, "help") == 0)
1508 print_help (context, TRUE, NULL);
1509 else if (strcmp (arg, "help-all") == 0)
1510 print_help (context, FALSE, NULL);
1511 else if (strncmp (arg, "help-", 5) == 0)
1515 list = context->groups;
1519 GOptionGroup *group = list->data;
1521 if (strcmp (arg + 5, group->name) == 0)
1522 print_help (context, FALSE, group);
1529 if (context->main_group &&
1530 !parse_long_option (context, context->main_group, &i, arg,
1531 FALSE, argc, argv, error, &parsed))
1537 /* Try the groups */
1538 list = context->groups;
1541 GOptionGroup *group = list->data;
1543 if (!parse_long_option (context, group, &i, arg,
1544 FALSE, argc, argv, error, &parsed))
1556 /* Now look for --<group>-<option> */
1557 dash = strchr (arg, '-');
1560 /* Try the groups */
1561 list = context->groups;
1564 GOptionGroup *group = list->data;
1566 if (strncmp (group->name, arg, dash - arg) == 0)
1568 if (!parse_long_option (context, group, &i, dash + 1,
1569 TRUE, argc, argv, error, &parsed))
1580 if (context->ignore_unknown)
1584 { /* short option */
1585 gint j, new_i = i, arg_length;
1586 gboolean *nulled_out = NULL;
1587 arg = (*argv)[i] + 1;
1588 arg_length = strlen (arg);
1589 nulled_out = g_newa (gboolean, arg_length);
1590 memset (nulled_out, 0, arg_length * sizeof (gboolean));
1591 for (j = 0; j < arg_length; j++)
1593 if (context->help_enabled && arg[j] == '?')
1594 print_help (context, TRUE, NULL);
1596 if (context->main_group &&
1597 !parse_short_option (context, context->main_group,
1599 argc, argv, error, &parsed))
1603 /* Try the groups */
1604 list = context->groups;
1607 GOptionGroup *group = list->data;
1608 if (!parse_short_option (context, group, i, &new_i, arg[j],
1609 argc, argv, error, &parsed))
1617 if (context->ignore_unknown && parsed)
1618 nulled_out[j] = TRUE;
1619 else if (context->ignore_unknown)
1623 /* !context->ignore_unknown && parsed */
1625 if (context->ignore_unknown)
1627 gchar *new_arg = NULL;
1629 for (j = 0; j < arg_length; j++)
1634 new_arg = g_malloc (arg_length + 1);
1635 new_arg[arg_index++] = arg[j];
1639 new_arg[arg_index] = '\0';
1640 add_pending_null (context, &((*argv)[i]), new_arg);
1644 add_pending_null (context, &((*argv)[i]), NULL);
1652 if (!parsed && !context->ignore_unknown)
1655 G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
1656 _("Unknown option %s"), (*argv)[i]);
1662 /* Collect remaining args */
1663 if (context->main_group &&
1664 !parse_remaining_arg (context, context->main_group, &i,
1665 argc, argv, error, &parsed))
1668 if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
1673 if (separator_pos > 0)
1674 add_pending_null (context, &((*argv)[separator_pos]), NULL);
1678 /* Call post-parse hooks */
1679 list = context->groups;
1682 GOptionGroup *group = list->data;
1684 if (group->post_parse_func)
1686 if (!(* group->post_parse_func) (context, group,
1687 group->user_data, error))
1694 if (context->main_group && context->main_group->post_parse_func)
1696 if (!(* context->main_group->post_parse_func) (context, context->main_group,
1697 context->main_group->user_data, error))
1703 free_pending_nulls (context, TRUE);
1705 for (i = 1; i < *argc; i++)
1707 for (k = i; k < *argc; k++)
1708 if ((*argv)[k] != NULL)
1714 for (j = i + k; j < *argc; j++)
1716 (*argv)[j-k] = (*argv)[j];
1728 /* Call error hooks */
1729 list = context->groups;
1732 GOptionGroup *group = list->data;
1734 if (group->error_func)
1735 (* group->error_func) (context, group,
1736 group->user_data, error);
1741 if (context->main_group && context->main_group->error_func)
1742 (* context->main_group->error_func) (context, context->main_group,
1743 context->main_group->user_data, error);
1745 free_changes_list (context, TRUE);
1746 free_pending_nulls (context, FALSE);
1752 * g_option_group_new:
1753 * @name: the name for the option group, this is used to provide
1754 * help for the options in this group with <option>--help-</option>@name
1755 * @description: a description for this group to be shown in
1756 * <option>--help</option>. This string is translated using the translation
1757 * domain or translation function of the group
1758 * @help_description: a description for the <option>--help-</option>@name option.
1759 * This string is translated using the translation domain or translation function
1761 * @user_data: user data that will be passed to the pre- and post-parse hooks,
1762 * the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
1763 * @destroy: a function that will be called to free @user_data, or %NULL
1765 * Creates a new #GOptionGroup.
1767 * Return value: a newly created option group. It should be added
1768 * to a #GOptionContext or freed with g_option_group_free().
1773 g_option_group_new (const gchar *name,
1774 const gchar *description,
1775 const gchar *help_description,
1777 GDestroyNotify destroy)
1780 GOptionGroup *group;
1782 group = g_new0 (GOptionGroup, 1);
1783 group->name = g_strdup (name);
1784 group->description = g_strdup (description);
1785 group->help_description = g_strdup (help_description);
1786 group->user_data = user_data;
1787 group->destroy_notify = destroy;
1794 * g_option_group_free:
1795 * @group: a #GOptionGroup
1797 * Frees a #GOptionGroup. Note that you must <emphasis>not</emphasis>
1798 * free groups which have been added to a #GOptionContext.
1803 g_option_group_free (GOptionGroup *group)
1805 g_return_if_fail (group != NULL);
1807 g_free (group->name);
1808 g_free (group->description);
1809 g_free (group->help_description);
1811 g_free (group->entries);
1813 if (group->destroy_notify)
1814 (* group->destroy_notify) (group->user_data);
1816 if (group->translate_notify)
1817 (* group->translate_notify) (group->translate_data);
1824 * g_option_group_add_entries:
1825 * @group: a #GOptionGroup
1826 * @entries: a %NULL-terminated array of #GOptionEntry<!-- -->s
1828 * Adds the options specified in @entries to @group.
1833 g_option_group_add_entries (GOptionGroup *group,
1834 const GOptionEntry *entries)
1838 g_return_if_fail (entries != NULL);
1840 for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++) ;
1842 group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
1844 memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
1846 for (i = group->n_entries; i < group->n_entries + n_entries; i++)
1848 gchar c = group->entries[i].short_name;
1852 if (c == '-' || !g_ascii_isprint (c))
1854 g_warning (G_STRLOC": ignoring invalid short option '%c' (%d)", c, c);
1855 group->entries[i].short_name = 0;
1860 group->n_entries += n_entries;
1864 * g_option_group_set_parse_hooks:
1865 * @group: a #GOptionGroup
1866 * @pre_parse_func: a function to call before parsing, or %NULL
1867 * @post_parse_func: a function to call after parsing, or %NULL
1869 * Associates two functions with @group which will be called
1870 * from g_option_context_parse() before the first option is parsed
1871 * and after the last option has been parsed, respectively.
1873 * Note that the user data to be passed to @pre_parse_func and
1874 * @post_parse_func can be specified when constructing the group
1875 * with g_option_group_new().
1880 g_option_group_set_parse_hooks (GOptionGroup *group,
1881 GOptionParseFunc pre_parse_func,
1882 GOptionParseFunc post_parse_func)
1884 g_return_if_fail (group != NULL);
1886 group->pre_parse_func = pre_parse_func;
1887 group->post_parse_func = post_parse_func;
1891 * g_option_group_set_error_hook:
1892 * @group: a #GOptionGroup
1893 * @error_func: a function to call when an error occurs
1895 * Associates a function with @group which will be called
1896 * from g_option_context_parse() when an error occurs.
1898 * Note that the user data to be passed to @pre_parse_func and
1899 * @post_parse_func can be specified when constructing the group
1900 * with g_option_group_new().
1905 g_option_group_set_error_hook (GOptionGroup *group,
1906 GOptionErrorFunc error_func)
1908 g_return_if_fail (group != NULL);
1910 group->error_func = error_func;
1915 * g_option_group_set_translate_func:
1916 * @group: a #GOptionGroup
1917 * @func: the #GTranslateFunc, or %NULL
1918 * @data: user data to pass to @func, or %NULL
1919 * @destroy_notify: a function which gets called to free @data, or %NULL
1921 * Sets the function which is used to translate user-visible
1922 * strings, for <option>--help</option> output. Different
1923 * groups can use different #GTranslateFunc<!-- -->s. If @func
1924 * is %NULL, strings are not translated.
1926 * If you are using gettext(), you only need to set the translation
1927 * domain, see g_option_group_set_translation_domain().
1932 g_option_group_set_translate_func (GOptionGroup *group,
1933 GTranslateFunc func,
1935 GDestroyNotify destroy_notify)
1937 g_return_if_fail (group != NULL);
1939 if (group->translate_notify)
1940 group->translate_notify (group->translate_data);
1942 group->translate_func = func;
1943 group->translate_data = data;
1944 group->translate_notify = destroy_notify;
1948 dgettext_swapped (const gchar *msgid,
1949 const gchar *domainname)
1951 return dgettext (domainname, msgid);
1955 * g_option_group_set_translation_domain:
1956 * @group: a #GOptionGroup
1957 * @domain: the domain to use
1959 * A convenience function to use gettext() for translating
1960 * user-visible strings.
1965 g_option_group_set_translation_domain (GOptionGroup *group,
1966 const gchar *domain)
1968 g_return_if_fail (group != NULL);
1970 g_option_group_set_translate_func (group,
1971 (GTranslateFunc)dgettext_swapped,
1977 * g_option_context_set_translate_func:
1978 * @context: a #GOptionContext
1979 * @func: the #GTranslateFunc, or %NULL
1980 * @data: user data to pass to @func, or %NULL
1981 * @destroy_notify: a function which gets called to free @data, or %NULL
1983 * Sets the function which is used to translate the contexts
1984 * user-visible strings, for <option>--help</option> output.
1985 * If @func is %NULL, strings are not translated.
1987 * Note that option groups have their own translation functions,
1988 * this function only affects the @parameter_string (see g_option_context_nex()),
1989 * the summary (see g_option_context_set_summary()) and the description
1990 * (see g_option_context_set_description()).
1992 * If you are using gettext(), you only need to set the translation
1993 * domain, see g_context_group_set_translation_domain().
1998 g_option_context_set_translate_func (GOptionContext *context,
1999 GTranslateFunc func,
2001 GDestroyNotify destroy_notify)
2003 g_return_if_fail (context != NULL);
2005 if (context->translate_notify)
2006 context->translate_notify (context->translate_data);
2008 context->translate_func = func;
2009 context->translate_data = data;
2010 context->translate_notify = destroy_notify;
2014 * g_option_context_set_translation_domain:
2015 * @context: a #GOptionContext
2016 * @domain: the domain to use
2018 * A convenience function to use gettext() for translating
2019 * user-visible strings.
2024 g_option_context_set_translation_domain (GOptionContext *context,
2025 const gchar *domain)
2027 g_return_if_fail (context != NULL);
2029 g_option_context_set_translate_func (context,
2030 (GTranslateFunc)dgettext_swapped,
2036 * g_option_context_set_summary:
2037 * @context: a #GOptionContext
2038 * @summary: a string to be shown in <option>--help</option> output
2039 * before the list of options, or %NULL
2041 * Adds a string to be displayed in <option>--help</option> output
2042 * before the list of options. This is typically a summary of the
2043 * program functionality.
2045 * Note that the summary is translated (see
2046 * g_option_context_set_translate_func()).
2051 g_option_context_set_summary (GOptionContext *context,
2052 const gchar *summary)
2054 g_return_if_fail (context != NULL);
2056 g_free (context->summary);
2057 context->summary = g_strdup (summary);
2062 * g_option_context_get_summary:
2063 * @context: a #GOptionContext
2065 * Returns the summary. See g_option_context_set_summary().
2067 * Returns: the summary
2071 G_CONST_RETURN gchar *
2072 g_option_context_get_summary (GOptionContext *context)
2074 g_return_val_if_fail (context != NULL, NULL);
2076 return context->summary;
2080 * g_option_context_set_description:
2081 * @context: a #GOptionContext
2082 * @description: a string to be shown in <option>--help</option> output
2083 * after the list of options, or %NULL
2085 * Adds a string to be displayed in <option>--help</option> output
2086 * after the list of options. This text often includes a bug reporting
2089 * Note that the summary is translated (see
2090 * g_option_context_set_translate_func()).
2095 g_option_context_set_description (GOptionContext *context,
2096 const gchar *description)
2098 g_return_if_fail (context != NULL);
2100 g_free (context->description);
2101 context->description = g_strdup (description);
2106 * g_option_context_get_description:
2107 * @context: a #GOptionContext
2109 * Returns the description. See g_option_context_set_description().
2111 * Returns: the description
2115 G_CONST_RETURN gchar *
2116 g_option_context_get_description (GOptionContext *context)
2118 g_return_val_if_fail (context != NULL, NULL);
2120 return context->description;
2124 #define __G_OPTION_C__
2125 #include "galiasdef.c"