unicode: Simplify width table generation
[glib.git] / glib / goption.c
blob6438281200d255758b6feefd79b721db479a7245
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, see <http://www.gnu.org/licenses/>.
20 /**
21 * SECTION:option
22 * @Short_description: parses commandline options
23 * @Title: Commandline option parser
25 * The GOption commandline parser is intended to be a simpler replacement
26 * for the popt library. It supports short and long commandline options,
27 * as shown in the following example:
29 * `testtreemodel -r 1 --max-size 20 --rand --display=:1.0 -vb -- file1 file2`
31 * The example demonstrates a number of features of the GOption
32 * commandline parser:
34 * - Options can be single letters, prefixed by a single dash.
36 * - Multiple short options can be grouped behind a single dash.
38 * - Long options are prefixed by two consecutive dashes.
40 * - Options can have an extra argument, which can be a number, a string or
41 * a filename. For long options, the extra argument can be appended with
42 * an equals sign after the option name, which is useful if the extra
43 * argument starts with a dash, which would otherwise cause it to be
44 * interpreted as another option.
46 * - Non-option arguments are returned to the application as rest arguments.
48 * - An argument consisting solely of two dashes turns off further parsing,
49 * any remaining arguments (even those starting with a dash) are returned
50 * to the application as rest arguments.
52 * Another important feature of GOption is that it can automatically
53 * generate nicely formatted help output. Unless it is explicitly turned
54 * off with g_option_context_set_help_enabled(), GOption will recognize
55 * the `--help`, `-?`, `--help-all` and `--help-groupname` options
56 * (where `groupname` is the name of a #GOptionGroup) and write a text
57 * similar to the one shown in the following example to stdout.
59 * |[
60 * Usage:
61 * testtreemodel [OPTION...] - test tree model performance
63 * Help Options:
64 * -h, --help Show help options
65 * --help-all Show all help options
66 * --help-gtk Show GTK+ Options
68 * Application Options:
69 * -r, --repeats=N Average over N repetitions
70 * -m, --max-size=M Test up to 2^M items
71 * --display=DISPLAY X display to use
72 * -v, --verbose Be verbose
73 * -b, --beep Beep when done
74 * --rand Randomize the data
75 * ]|
77 * GOption groups options in #GOptionGroups, which makes it easy to
78 * incorporate options from multiple sources. The intended use for this is
79 * to let applications collect option groups from the libraries it uses,
80 * add them to their #GOptionContext, and parse all options by a single call
81 * to g_option_context_parse(). See gtk_get_option_group() for an example.
83 * If an option is declared to be of type string or filename, GOption takes
84 * care of converting it to the right encoding; strings are returned in
85 * UTF-8, filenames are returned in the GLib filename encoding. Note that
86 * this only works if setlocale() has been called before
87 * g_option_context_parse().
89 * Here is a complete example of setting up GOption to parse the example
90 * commandline above and produce the example help output.
91 * |[<!-- language="C" -->
92 * static gint repeats = 2;
93 * static gint max_size = 8;
94 * static gboolean verbose = FALSE;
95 * static gboolean beep = FALSE;
96 * static gboolean randomize = FALSE;
98 * static GOptionEntry entries[] =
99 * {
100 * { "repeats", 'r', 0, G_OPTION_ARG_INT, &repeats, "Average over N repetitions", "N" },
101 * { "max-size", 'm', 0, G_OPTION_ARG_INT, &max_size, "Test up to 2^M items", "M" },
102 * { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Be verbose", NULL },
103 * { "beep", 'b', 0, G_OPTION_ARG_NONE, &beep, "Beep when done", NULL },
104 * { "rand", 0, 0, G_OPTION_ARG_NONE, &randomize, "Randomize the data", NULL },
105 * { NULL }
106 * };
108 * int
109 * main (int argc, char *argv[])
111 * GError *error = NULL;
112 * GOptionContext *context;
114 * context = g_option_context_new ("- test tree model performance");
115 * g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
116 * g_option_context_add_group (context, gtk_get_option_group (TRUE));
117 * if (!g_option_context_parse (context, &argc, &argv, &error))
119 * g_print ("option parsing failed: %s\n", error->message);
120 * exit (1);
123 * ...
126 * ]|
128 * On UNIX systems, the argv that is passed to main() has no particular
129 * encoding, even to the extent that different parts of it may have
130 * different encodings. In general, normal arguments and flags will be
131 * in the current locale and filenames should be considered to be opaque
132 * byte strings. Proper use of %G_OPTION_ARG_FILENAME vs
133 * %G_OPTION_ARG_STRING is therefore important.
135 * Note that on Windows, filenames do have an encoding, but using
136 * #GOptionContext with the argv as passed to main() will result in a
137 * program that can only accept commandline arguments with characters
138 * from the system codepage. This can cause problems when attempting to
139 * deal with filenames containing Unicode characters that fall outside
140 * of the codepage.
142 * A solution to this is to use g_win32_get_command_line() and
143 * g_option_context_parse_strv() which will properly handle full Unicode
144 * filenames. If you are using #GApplication, this is done
145 * automatically for you.
147 * The following example shows how you can use #GOptionContext directly
148 * in order to correctly deal with Unicode filenames on Windows:
150 * |[<!-- language="C" -->
151 * int
152 * main (int argc, char **argv)
154 * GError *error = NULL;
155 * GOptionContext *context;
156 * gchar **args;
158 * #ifdef G_OS_WIN32
159 * args = g_win32_get_command_line ();
160 * #else
161 * args = g_strdupv (argv);
162 * #endif
164 * // set up context
166 * if (!g_option_context_parse_strv (context, &args, &error))
168 * // error happened
171 * ...
173 * g_strfreev (args);
175 * ...
177 * ]|
180 #include "config.h"
182 #include <string.h>
183 #include <stdlib.h>
184 #include <stdio.h>
185 #include <errno.h>
187 #if defined __OpenBSD__
188 #include <unistd.h>
189 #include <sys/sysctl.h>
190 #endif
192 #include "goption.h"
194 #include "gprintf.h"
195 #include "glibintl.h"
197 #define TRANSLATE(group, str) (((group)->translate_func ? (* (group)->translate_func) ((str), (group)->translate_data) : (str)))
199 #define NO_ARG(entry) ((entry)->arg == G_OPTION_ARG_NONE || \
200 ((entry)->arg == G_OPTION_ARG_CALLBACK && \
201 ((entry)->flags & G_OPTION_FLAG_NO_ARG)))
203 #define OPTIONAL_ARG(entry) ((entry)->arg == G_OPTION_ARG_CALLBACK && \
204 (entry)->flags & G_OPTION_FLAG_OPTIONAL_ARG)
206 typedef struct
208 GOptionArg arg_type;
209 gpointer arg_data;
210 union
212 gboolean bool;
213 gint integer;
214 gchar *str;
215 gchar **array;
216 gdouble dbl;
217 gint64 int64;
218 } prev;
219 union
221 gchar *str;
222 struct
224 gint len;
225 gchar **data;
226 } array;
227 } allocated;
228 } Change;
230 typedef struct
232 gchar **ptr;
233 gchar *value;
234 } PendingNull;
236 struct _GOptionContext
238 GList *groups;
240 gchar *parameter_string;
241 gchar *summary;
242 gchar *description;
244 GTranslateFunc translate_func;
245 GDestroyNotify translate_notify;
246 gpointer translate_data;
248 guint help_enabled : 1;
249 guint ignore_unknown : 1;
250 guint strv_mode : 1;
252 GOptionGroup *main_group;
254 /* We keep a list of change so we can revert them */
255 GList *changes;
257 /* We also keep track of all argv elements
258 * that should be NULLed or modified.
260 GList *pending_nulls;
263 struct _GOptionGroup
265 gchar *name;
266 gchar *description;
267 gchar *help_description;
269 GDestroyNotify destroy_notify;
270 gpointer user_data;
272 GTranslateFunc translate_func;
273 GDestroyNotify translate_notify;
274 gpointer translate_data;
276 GOptionEntry *entries;
277 gint n_entries;
279 GOptionParseFunc pre_parse_func;
280 GOptionParseFunc post_parse_func;
281 GOptionErrorFunc error_func;
284 static void free_changes_list (GOptionContext *context,
285 gboolean revert);
286 static void free_pending_nulls (GOptionContext *context,
287 gboolean perform_nulls);
290 static int
291 _g_unichar_get_width (gunichar c)
293 if (G_UNLIKELY (g_unichar_iszerowidth (c)))
294 return 0;
296 /* we ignore the fact that we should call g_unichar_iswide_cjk() under
297 * some locales (legacy East Asian ones) */
298 if (g_unichar_iswide (c))
299 return 2;
301 return 1;
304 static glong
305 _g_utf8_strwidth (const gchar *p)
307 glong len = 0;
308 g_return_val_if_fail (p != NULL, 0);
310 while (*p)
312 len += _g_unichar_get_width (g_utf8_get_char (p));
313 p = g_utf8_next_char (p);
316 return len;
319 G_DEFINE_QUARK (g-option-context-error-quark, g_option_error)
322 * g_option_context_new:
323 * @parameter_string: (allow-none): a string which is displayed in
324 * the first line of `--help` output, after the usage summary
325 * `programname [OPTION...]`
327 * Creates a new option context.
329 * The @parameter_string can serve multiple purposes. It can be used
330 * to add descriptions for "rest" arguments, which are not parsed by
331 * the #GOptionContext, typically something like "FILES" or
332 * "FILE1 FILE2...". If you are using #G_OPTION_REMAINING for
333 * collecting "rest" arguments, GLib handles this automatically by
334 * using the @arg_description of the corresponding #GOptionEntry in
335 * the usage summary.
337 * Another usage is to give a short summary of the program
338 * functionality, like " - frob the strings", which will be displayed
339 * in the same line as the usage. For a longer description of the
340 * program functionality that should be displayed as a paragraph
341 * below the usage line, use g_option_context_set_summary().
343 * Note that the @parameter_string is translated using the
344 * function set with g_option_context_set_translate_func(), so
345 * it should normally be passed untranslated.
347 * Returns: a newly created #GOptionContext, which must be
348 * freed with g_option_context_free() after use.
350 * Since: 2.6
352 GOptionContext *
353 g_option_context_new (const gchar *parameter_string)
356 GOptionContext *context;
358 context = g_new0 (GOptionContext, 1);
360 context->parameter_string = g_strdup (parameter_string);
361 context->help_enabled = TRUE;
362 context->ignore_unknown = FALSE;
364 return context;
368 * g_option_context_free:
369 * @context: a #GOptionContext
371 * Frees context and all the groups which have been
372 * added to it.
374 * Please note that parsed arguments need to be freed separately (see
375 * #GOptionEntry).
377 * Since: 2.6
379 void g_option_context_free (GOptionContext *context)
381 g_return_if_fail (context != NULL);
383 g_list_free_full (context->groups, (GDestroyNotify) g_option_group_free);
385 if (context->main_group)
386 g_option_group_free (context->main_group);
388 free_changes_list (context, FALSE);
389 free_pending_nulls (context, FALSE);
391 g_free (context->parameter_string);
392 g_free (context->summary);
393 g_free (context->description);
395 if (context->translate_notify)
396 (* context->translate_notify) (context->translate_data);
398 g_free (context);
403 * g_option_context_set_help_enabled:
404 * @context: a #GOptionContext
405 * @help_enabled: %TRUE to enable `--help`, %FALSE to disable it
407 * Enables or disables automatic generation of `--help` output.
408 * By default, g_option_context_parse() recognizes `--help`, `-h`,
409 * `-?`, `--help-all` and `--help-groupname` and creates suitable
410 * output to stdout.
412 * Since: 2.6
414 void g_option_context_set_help_enabled (GOptionContext *context,
415 gboolean help_enabled)
418 g_return_if_fail (context != NULL);
420 context->help_enabled = help_enabled;
424 * g_option_context_get_help_enabled:
425 * @context: a #GOptionContext
427 * Returns whether automatic `--help` generation
428 * is turned on for @context. See g_option_context_set_help_enabled().
430 * Returns: %TRUE if automatic help generation is turned on.
432 * Since: 2.6
434 gboolean
435 g_option_context_get_help_enabled (GOptionContext *context)
437 g_return_val_if_fail (context != NULL, FALSE);
439 return context->help_enabled;
443 * g_option_context_set_ignore_unknown_options:
444 * @context: a #GOptionContext
445 * @ignore_unknown: %TRUE to ignore unknown options, %FALSE to produce
446 * an error when unknown options are met
448 * Sets whether to ignore unknown options or not. If an argument is
449 * ignored, it is left in the @argv array after parsing. By default,
450 * g_option_context_parse() treats unknown options as error.
452 * This setting does not affect non-option arguments (i.e. arguments
453 * which don't start with a dash). But note that GOption cannot reliably
454 * determine whether a non-option belongs to a preceding unknown option.
456 * Since: 2.6
458 void
459 g_option_context_set_ignore_unknown_options (GOptionContext *context,
460 gboolean ignore_unknown)
462 g_return_if_fail (context != NULL);
464 context->ignore_unknown = ignore_unknown;
468 * g_option_context_get_ignore_unknown_options:
469 * @context: a #GOptionContext
471 * Returns whether unknown options are ignored or not. See
472 * g_option_context_set_ignore_unknown_options().
474 * Returns: %TRUE if unknown options are ignored.
476 * Since: 2.6
478 gboolean
479 g_option_context_get_ignore_unknown_options (GOptionContext *context)
481 g_return_val_if_fail (context != NULL, FALSE);
483 return context->ignore_unknown;
487 * g_option_context_add_group:
488 * @context: a #GOptionContext
489 * @group: the group to add
491 * Adds a #GOptionGroup to the @context, so that parsing with @context
492 * will recognize the options in the group. Note that the group will
493 * be freed together with the context when g_option_context_free() is
494 * called, so you must not free the group yourself after adding it
495 * to a context.
497 * Since: 2.6
499 void
500 g_option_context_add_group (GOptionContext *context,
501 GOptionGroup *group)
503 GList *list;
505 g_return_if_fail (context != NULL);
506 g_return_if_fail (group != NULL);
507 g_return_if_fail (group->name != NULL);
508 g_return_if_fail (group->description != NULL);
509 g_return_if_fail (group->help_description != NULL);
511 for (list = context->groups; list; list = list->next)
513 GOptionGroup *g = (GOptionGroup *)list->data;
515 if ((group->name == NULL && g->name == NULL) ||
516 (group->name && g->name && strcmp (group->name, g->name) == 0))
517 g_warning ("A group named \"%s\" is already part of this GOptionContext",
518 group->name);
521 context->groups = g_list_append (context->groups, group);
525 * g_option_context_set_main_group:
526 * @context: a #GOptionContext
527 * @group: the group to set as main group
529 * Sets a #GOptionGroup as main group of the @context.
530 * This has the same effect as calling g_option_context_add_group(),
531 * the only difference is that the options in the main group are
532 * treated differently when generating `--help` output.
534 * Since: 2.6
536 void
537 g_option_context_set_main_group (GOptionContext *context,
538 GOptionGroup *group)
540 g_return_if_fail (context != NULL);
541 g_return_if_fail (group != NULL);
543 if (context->main_group)
545 g_warning ("This GOptionContext already has a main group");
547 return;
550 context->main_group = group;
554 * g_option_context_get_main_group:
555 * @context: a #GOptionContext
557 * Returns a pointer to the main group of @context.
559 * Returns: the main group of @context, or %NULL if @context doesn't
560 * have a main group. Note that group belongs to @context and should
561 * not be modified or freed.
563 * Since: 2.6
565 GOptionGroup *
566 g_option_context_get_main_group (GOptionContext *context)
568 g_return_val_if_fail (context != NULL, NULL);
570 return context->main_group;
574 * g_option_context_add_main_entries:
575 * @context: a #GOptionContext
576 * @entries: a %NULL-terminated array of #GOptionEntrys
577 * @translation_domain: (allow-none): a translation domain to use for translating
578 * the `--help` output for the options in @entries
579 * with gettext(), or %NULL
581 * A convenience function which creates a main group if it doesn't
582 * exist, adds the @entries to it and sets the translation domain.
584 * Since: 2.6
586 void
587 g_option_context_add_main_entries (GOptionContext *context,
588 const GOptionEntry *entries,
589 const gchar *translation_domain)
591 g_return_if_fail (entries != NULL);
593 if (!context->main_group)
594 context->main_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
596 g_option_group_add_entries (context->main_group, entries);
597 g_option_group_set_translation_domain (context->main_group, translation_domain);
600 static gint
601 calculate_max_length (GOptionGroup *group,
602 GHashTable *aliases)
604 GOptionEntry *entry;
605 gint i, len, max_length;
606 const gchar *long_name;
608 max_length = 0;
610 for (i = 0; i < group->n_entries; i++)
612 entry = &group->entries[i];
614 if (entry->flags & G_OPTION_FLAG_HIDDEN)
615 continue;
617 long_name = g_hash_table_lookup (aliases, &entry->long_name);
618 if (!long_name)
619 long_name = entry->long_name;
620 len = _g_utf8_strwidth (long_name);
622 if (entry->short_name)
623 len += 4;
625 if (!NO_ARG (entry) && entry->arg_description)
626 len += 1 + _g_utf8_strwidth (TRANSLATE (group, entry->arg_description));
628 max_length = MAX (max_length, len);
631 return max_length;
634 static void
635 print_entry (GOptionGroup *group,
636 gint max_length,
637 const GOptionEntry *entry,
638 GString *string,
639 GHashTable *aliases)
641 GString *str;
642 const gchar *long_name;
644 if (entry->flags & G_OPTION_FLAG_HIDDEN)
645 return;
647 if (entry->long_name[0] == 0)
648 return;
650 long_name = g_hash_table_lookup (aliases, &entry->long_name);
651 if (!long_name)
652 long_name = entry->long_name;
654 str = g_string_new (NULL);
656 if (entry->short_name)
657 g_string_append_printf (str, " -%c, --%s", entry->short_name, long_name);
658 else
659 g_string_append_printf (str, " --%s", long_name);
661 if (entry->arg_description)
662 g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
664 g_string_append_printf (string, "%s%*s %s\n", str->str,
665 (int) (max_length + 4 - _g_utf8_strwidth (str->str)), "",
666 entry->description ? TRANSLATE (group, entry->description) : "");
667 g_string_free (str, TRUE);
670 static gboolean
671 group_has_visible_entries (GOptionContext *context,
672 GOptionGroup *group,
673 gboolean main_entries)
675 GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
676 GOptionEntry *entry;
677 gint i, l;
678 gboolean main_group = group == context->main_group;
680 if (!main_entries)
681 reject_filter |= G_OPTION_FLAG_IN_MAIN;
683 for (i = 0, l = (group ? group->n_entries : 0); i < l; i++)
685 entry = &group->entries[i];
687 if (main_entries && !main_group && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
688 continue;
689 if (entry->long_name[0] == 0) /* ignore rest entry */
690 continue;
691 if (!(entry->flags & reject_filter))
692 return TRUE;
695 return FALSE;
698 static gboolean
699 group_list_has_visible_entries (GOptionContext *context,
700 GList *group_list,
701 gboolean main_entries)
703 while (group_list)
705 if (group_has_visible_entries (context, group_list->data, main_entries))
706 return TRUE;
708 group_list = group_list->next;
711 return FALSE;
714 static gboolean
715 context_has_h_entry (GOptionContext *context)
717 gsize i;
718 GList *list;
720 if (context->main_group)
722 for (i = 0; i < context->main_group->n_entries; i++)
724 if (context->main_group->entries[i].short_name == 'h')
725 return TRUE;
729 for (list = context->groups; list != NULL; list = g_list_next (list))
731 GOptionGroup *group;
733 group = (GOptionGroup*)list->data;
734 for (i = 0; i < group->n_entries; i++)
736 if (group->entries[i].short_name == 'h')
737 return TRUE;
740 return FALSE;
744 * g_option_context_get_help:
745 * @context: a #GOptionContext
746 * @main_help: if %TRUE, only include the main group
747 * @group: (allow-none): the #GOptionGroup to create help for, or %NULL
749 * Returns a formatted, translated help text for the given context.
750 * To obtain the text produced by `--help`, call
751 * `g_option_context_get_help (context, TRUE, NULL)`.
752 * To obtain the text produced by `--help-all`, call
753 * `g_option_context_get_help (context, FALSE, NULL)`.
754 * To obtain the help text for an option group, call
755 * `g_option_context_get_help (context, FALSE, group)`.
757 * Returns: A newly allocated string containing the help text
759 * Since: 2.14
761 gchar *
762 g_option_context_get_help (GOptionContext *context,
763 gboolean main_help,
764 GOptionGroup *group)
766 GList *list;
767 gint max_length = 0, len;
768 gint i;
769 GOptionEntry *entry;
770 GHashTable *shadow_map;
771 GHashTable *aliases;
772 gboolean seen[256];
773 const gchar *rest_description;
774 GString *string;
775 guchar token;
777 string = g_string_sized_new (1024);
779 rest_description = NULL;
780 if (context->main_group)
783 for (i = 0; i < context->main_group->n_entries; i++)
785 entry = &context->main_group->entries[i];
786 if (entry->long_name[0] == 0)
788 rest_description = TRANSLATE (context->main_group, entry->arg_description);
789 break;
794 g_string_append_printf (string, "%s\n %s %s",
795 _("Usage:"), g_get_prgname(), _("[OPTION...]"));
797 if (rest_description)
799 g_string_append (string, " ");
800 g_string_append (string, rest_description);
803 if (context->parameter_string)
805 g_string_append (string, " ");
806 g_string_append (string, TRANSLATE (context, context->parameter_string));
809 g_string_append (string, "\n\n");
811 if (context->summary)
813 g_string_append (string, TRANSLATE (context, context->summary));
814 g_string_append (string, "\n\n");
817 memset (seen, 0, sizeof (gboolean) * 256);
818 shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
819 aliases = g_hash_table_new_full (NULL, NULL, NULL, g_free);
821 if (context->main_group)
823 for (i = 0; i < context->main_group->n_entries; i++)
825 entry = &context->main_group->entries[i];
826 g_hash_table_insert (shadow_map,
827 (gpointer)entry->long_name,
828 entry);
830 if (seen[(guchar)entry->short_name])
831 entry->short_name = 0;
832 else
833 seen[(guchar)entry->short_name] = TRUE;
837 list = context->groups;
838 while (list != NULL)
840 GOptionGroup *g = list->data;
841 for (i = 0; i < g->n_entries; i++)
843 entry = &g->entries[i];
844 if (g_hash_table_lookup (shadow_map, entry->long_name) &&
845 !(entry->flags & G_OPTION_FLAG_NOALIAS))
847 g_hash_table_insert (aliases, &entry->long_name,
848 g_strdup_printf ("%s-%s", g->name, entry->long_name));
850 else
851 g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
853 if (seen[(guchar)entry->short_name] &&
854 !(entry->flags & G_OPTION_FLAG_NOALIAS))
855 entry->short_name = 0;
856 else
857 seen[(guchar)entry->short_name] = TRUE;
859 list = list->next;
862 g_hash_table_destroy (shadow_map);
864 list = context->groups;
866 if (context->help_enabled)
868 max_length = _g_utf8_strwidth ("-?, --help");
870 if (list)
872 len = _g_utf8_strwidth ("--help-all");
873 max_length = MAX (max_length, len);
877 if (context->main_group)
879 len = calculate_max_length (context->main_group, aliases);
880 max_length = MAX (max_length, len);
883 while (list != NULL)
885 GOptionGroup *g = list->data;
887 if (context->help_enabled)
889 /* First, we check the --help-<groupname> options */
890 len = _g_utf8_strwidth ("--help-") + _g_utf8_strwidth (g->name);
891 max_length = MAX (max_length, len);
894 /* Then we go through the entries */
895 len = calculate_max_length (g, aliases);
896 max_length = MAX (max_length, len);
898 list = list->next;
901 /* Add a bit of padding */
902 max_length += 4;
904 if (!group && context->help_enabled)
906 list = context->groups;
908 token = context_has_h_entry (context) ? '?' : 'h';
910 g_string_append_printf (string, "%s\n -%c, --%-*s %s\n",
911 _("Help Options:"), token, max_length - 4, "help",
912 _("Show help options"));
914 /* We only want --help-all when there are groups */
915 if (list)
916 g_string_append_printf (string, " --%-*s %s\n",
917 max_length, "help-all",
918 _("Show all help options"));
920 while (list)
922 GOptionGroup *g = list->data;
924 if (group_has_visible_entries (context, g, FALSE))
925 g_string_append_printf (string, " --help-%-*s %s\n",
926 max_length - 5, g->name,
927 TRANSLATE (g, g->help_description));
929 list = list->next;
932 g_string_append (string, "\n");
935 if (group)
937 /* Print a certain group */
939 if (group_has_visible_entries (context, group, FALSE))
941 g_string_append (string, TRANSLATE (group, group->description));
942 g_string_append (string, "\n");
943 for (i = 0; i < group->n_entries; i++)
944 print_entry (group, max_length, &group->entries[i], string, aliases);
945 g_string_append (string, "\n");
948 else if (!main_help)
950 /* Print all groups */
952 list = context->groups;
954 while (list)
956 GOptionGroup *g = list->data;
958 if (group_has_visible_entries (context, g, FALSE))
960 g_string_append (string, g->description);
961 g_string_append (string, "\n");
962 for (i = 0; i < g->n_entries; i++)
963 if (!(g->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
964 print_entry (g, max_length, &g->entries[i], string, aliases);
966 g_string_append (string, "\n");
969 list = list->next;
973 /* Print application options if --help or --help-all has been specified */
974 if ((main_help || !group) &&
975 (group_has_visible_entries (context, context->main_group, TRUE) ||
976 group_list_has_visible_entries (context, context->groups, TRUE)))
978 list = context->groups;
980 g_string_append (string, _("Application Options:"));
981 g_string_append (string, "\n");
982 if (context->main_group)
983 for (i = 0; i < context->main_group->n_entries; i++)
984 print_entry (context->main_group, max_length,
985 &context->main_group->entries[i], string, aliases);
987 while (list != NULL)
989 GOptionGroup *g = list->data;
991 /* Print main entries from other groups */
992 for (i = 0; i < g->n_entries; i++)
993 if (g->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
994 print_entry (g, max_length, &g->entries[i], string, aliases);
996 list = list->next;
999 g_string_append (string, "\n");
1002 if (context->description)
1004 g_string_append (string, TRANSLATE (context, context->description));
1005 g_string_append (string, "\n");
1008 g_hash_table_destroy (aliases);
1010 return g_string_free (string, FALSE);
1013 G_GNUC_NORETURN
1014 static void
1015 print_help (GOptionContext *context,
1016 gboolean main_help,
1017 GOptionGroup *group)
1019 gchar *help;
1021 help = g_option_context_get_help (context, main_help, group);
1022 g_print ("%s", help);
1023 g_free (help);
1025 exit (0);
1028 static gboolean
1029 parse_int (const gchar *arg_name,
1030 const gchar *arg,
1031 gint *result,
1032 GError **error)
1034 gchar *end;
1035 glong tmp;
1037 errno = 0;
1038 tmp = strtol (arg, &end, 0);
1040 if (*arg == '\0' || *end != '\0')
1042 g_set_error (error,
1043 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1044 _("Cannot parse integer value '%s' for %s"),
1045 arg, arg_name);
1046 return FALSE;
1049 *result = tmp;
1050 if (*result != tmp || errno == ERANGE)
1052 g_set_error (error,
1053 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1054 _("Integer value '%s' for %s out of range"),
1055 arg, arg_name);
1056 return FALSE;
1059 return TRUE;
1063 static gboolean
1064 parse_double (const gchar *arg_name,
1065 const gchar *arg,
1066 gdouble *result,
1067 GError **error)
1069 gchar *end;
1070 gdouble tmp;
1072 errno = 0;
1073 tmp = g_strtod (arg, &end);
1075 if (*arg == '\0' || *end != '\0')
1077 g_set_error (error,
1078 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1079 _("Cannot parse double value '%s' for %s"),
1080 arg, arg_name);
1081 return FALSE;
1083 if (errno == ERANGE)
1085 g_set_error (error,
1086 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1087 _("Double value '%s' for %s out of range"),
1088 arg, arg_name);
1089 return FALSE;
1092 *result = tmp;
1094 return TRUE;
1098 static gboolean
1099 parse_int64 (const gchar *arg_name,
1100 const gchar *arg,
1101 gint64 *result,
1102 GError **error)
1104 gchar *end;
1105 gint64 tmp;
1107 errno = 0;
1108 tmp = g_ascii_strtoll (arg, &end, 0);
1110 if (*arg == '\0' || *end != '\0')
1112 g_set_error (error,
1113 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1114 _("Cannot parse integer value '%s' for %s"),
1115 arg, arg_name);
1116 return FALSE;
1118 if (errno == ERANGE)
1120 g_set_error (error,
1121 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1122 _("Integer value '%s' for %s out of range"),
1123 arg, arg_name);
1124 return FALSE;
1127 *result = tmp;
1129 return TRUE;
1133 static Change *
1134 get_change (GOptionContext *context,
1135 GOptionArg arg_type,
1136 gpointer arg_data)
1138 GList *list;
1139 Change *change = NULL;
1141 for (list = context->changes; list != NULL; list = list->next)
1143 change = list->data;
1145 if (change->arg_data == arg_data)
1146 goto found;
1149 change = g_new0 (Change, 1);
1150 change->arg_type = arg_type;
1151 change->arg_data = arg_data;
1153 context->changes = g_list_prepend (context->changes, change);
1155 found:
1157 return change;
1160 static void
1161 add_pending_null (GOptionContext *context,
1162 gchar **ptr,
1163 gchar *value)
1165 PendingNull *n;
1167 n = g_new0 (PendingNull, 1);
1168 n->ptr = ptr;
1169 n->value = value;
1171 context->pending_nulls = g_list_prepend (context->pending_nulls, n);
1174 static gboolean
1175 parse_arg (GOptionContext *context,
1176 GOptionGroup *group,
1177 GOptionEntry *entry,
1178 const gchar *value,
1179 const gchar *option_name,
1180 GError **error)
1183 Change *change;
1185 g_assert (value || OPTIONAL_ARG (entry) || NO_ARG (entry));
1187 switch (entry->arg)
1189 case G_OPTION_ARG_NONE:
1191 (void) get_change (context, G_OPTION_ARG_NONE,
1192 entry->arg_data);
1194 *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
1195 break;
1197 case G_OPTION_ARG_STRING:
1199 gchar *data;
1201 #ifdef G_OS_WIN32
1202 if (!context->strv_mode)
1203 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1204 else
1205 data = g_strdup (value);
1206 #else
1207 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1208 #endif
1210 if (!data)
1211 return FALSE;
1213 change = get_change (context, G_OPTION_ARG_STRING,
1214 entry->arg_data);
1215 g_free (change->allocated.str);
1217 change->prev.str = *(gchar **)entry->arg_data;
1218 change->allocated.str = data;
1220 *(gchar **)entry->arg_data = data;
1221 break;
1223 case G_OPTION_ARG_STRING_ARRAY:
1225 gchar *data;
1227 #ifdef G_OS_WIN32
1228 if (!context->strv_mode)
1229 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1230 else
1231 data = g_strdup (value);
1232 #else
1233 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1234 #endif
1236 if (!data)
1237 return FALSE;
1239 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1240 entry->arg_data);
1242 if (change->allocated.array.len == 0)
1244 change->prev.array = *(gchar ***)entry->arg_data;
1245 change->allocated.array.data = g_new (gchar *, 2);
1247 else
1248 change->allocated.array.data =
1249 g_renew (gchar *, change->allocated.array.data,
1250 change->allocated.array.len + 2);
1252 change->allocated.array.data[change->allocated.array.len] = data;
1253 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1255 change->allocated.array.len ++;
1257 *(gchar ***)entry->arg_data = change->allocated.array.data;
1259 break;
1262 case G_OPTION_ARG_FILENAME:
1264 gchar *data;
1266 #ifdef G_OS_WIN32
1267 if (!context->strv_mode)
1268 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1269 else
1270 data = g_strdup (value);
1272 if (!data)
1273 return FALSE;
1274 #else
1275 data = g_strdup (value);
1276 #endif
1277 change = get_change (context, G_OPTION_ARG_FILENAME,
1278 entry->arg_data);
1279 g_free (change->allocated.str);
1281 change->prev.str = *(gchar **)entry->arg_data;
1282 change->allocated.str = data;
1284 *(gchar **)entry->arg_data = data;
1285 break;
1288 case G_OPTION_ARG_FILENAME_ARRAY:
1290 gchar *data;
1292 #ifdef G_OS_WIN32
1293 if (!context->strv_mode)
1294 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1295 else
1296 data = g_strdup (value);
1298 if (!data)
1299 return FALSE;
1300 #else
1301 data = g_strdup (value);
1302 #endif
1303 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1304 entry->arg_data);
1306 if (change->allocated.array.len == 0)
1308 change->prev.array = *(gchar ***)entry->arg_data;
1309 change->allocated.array.data = g_new (gchar *, 2);
1311 else
1312 change->allocated.array.data =
1313 g_renew (gchar *, change->allocated.array.data,
1314 change->allocated.array.len + 2);
1316 change->allocated.array.data[change->allocated.array.len] = data;
1317 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1319 change->allocated.array.len ++;
1321 *(gchar ***)entry->arg_data = change->allocated.array.data;
1323 break;
1326 case G_OPTION_ARG_INT:
1328 gint data;
1330 if (!parse_int (option_name, value,
1331 &data,
1332 error))
1333 return FALSE;
1335 change = get_change (context, G_OPTION_ARG_INT,
1336 entry->arg_data);
1337 change->prev.integer = *(gint *)entry->arg_data;
1338 *(gint *)entry->arg_data = data;
1339 break;
1341 case G_OPTION_ARG_CALLBACK:
1343 gchar *data;
1344 gboolean retval;
1346 if (!value && entry->flags & G_OPTION_FLAG_OPTIONAL_ARG)
1347 data = NULL;
1348 else if (entry->flags & G_OPTION_FLAG_NO_ARG)
1349 data = NULL;
1350 else if (entry->flags & G_OPTION_FLAG_FILENAME)
1352 #ifdef G_OS_WIN32
1353 if (!context->strv_mode)
1354 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1355 else
1356 data = g_strdup (value);
1357 #else
1358 data = g_strdup (value);
1359 #endif
1361 else
1362 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1364 if (!(entry->flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG)) &&
1365 !data)
1366 return FALSE;
1368 retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
1370 if (!retval && error != NULL && *error == NULL)
1371 g_set_error (error,
1372 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1373 _("Error parsing option %s"), option_name);
1375 g_free (data);
1377 return retval;
1379 break;
1381 case G_OPTION_ARG_DOUBLE:
1383 gdouble data;
1385 if (!parse_double (option_name, value,
1386 &data,
1387 error))
1389 return FALSE;
1392 change = get_change (context, G_OPTION_ARG_DOUBLE,
1393 entry->arg_data);
1394 change->prev.dbl = *(gdouble *)entry->arg_data;
1395 *(gdouble *)entry->arg_data = data;
1396 break;
1398 case G_OPTION_ARG_INT64:
1400 gint64 data;
1402 if (!parse_int64 (option_name, value,
1403 &data,
1404 error))
1406 return FALSE;
1409 change = get_change (context, G_OPTION_ARG_INT64,
1410 entry->arg_data);
1411 change->prev.int64 = *(gint64 *)entry->arg_data;
1412 *(gint64 *)entry->arg_data = data;
1413 break;
1415 default:
1416 g_assert_not_reached ();
1419 return TRUE;
1422 static gboolean
1423 parse_short_option (GOptionContext *context,
1424 GOptionGroup *group,
1425 gint idx,
1426 gint *new_idx,
1427 gchar arg,
1428 gint *argc,
1429 gchar ***argv,
1430 GError **error,
1431 gboolean *parsed)
1433 gint j;
1435 for (j = 0; j < group->n_entries; j++)
1437 if (arg == group->entries[j].short_name)
1439 gchar *option_name;
1440 gchar *value = NULL;
1442 option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
1444 if (NO_ARG (&group->entries[j]))
1445 value = NULL;
1446 else
1448 if (*new_idx > idx)
1450 g_set_error (error,
1451 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1452 _("Error parsing option %s"), option_name);
1453 g_free (option_name);
1454 return FALSE;
1457 if (idx < *argc - 1)
1459 if (!OPTIONAL_ARG (&group->entries[j]))
1461 value = (*argv)[idx + 1];
1462 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1463 *new_idx = idx + 1;
1465 else
1467 if ((*argv)[idx + 1][0] == '-')
1468 value = NULL;
1469 else
1471 value = (*argv)[idx + 1];
1472 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1473 *new_idx = idx + 1;
1477 else if (idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1478 value = NULL;
1479 else
1481 g_set_error (error,
1482 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1483 _("Missing argument for %s"), option_name);
1484 g_free (option_name);
1485 return FALSE;
1489 if (!parse_arg (context, group, &group->entries[j],
1490 value, option_name, error))
1492 g_free (option_name);
1493 return FALSE;
1496 g_free (option_name);
1497 *parsed = TRUE;
1501 return TRUE;
1504 static gboolean
1505 parse_long_option (GOptionContext *context,
1506 GOptionGroup *group,
1507 gint *idx,
1508 gchar *arg,
1509 gboolean aliased,
1510 gint *argc,
1511 gchar ***argv,
1512 GError **error,
1513 gboolean *parsed)
1515 gint j;
1517 for (j = 0; j < group->n_entries; j++)
1519 if (*idx >= *argc)
1520 return TRUE;
1522 if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
1523 continue;
1525 if (NO_ARG (&group->entries[j]) &&
1526 strcmp (arg, group->entries[j].long_name) == 0)
1528 gchar *option_name;
1529 gboolean retval;
1531 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1532 retval = parse_arg (context, group, &group->entries[j],
1533 NULL, option_name, error);
1534 g_free (option_name);
1536 add_pending_null (context, &((*argv)[*idx]), NULL);
1537 *parsed = TRUE;
1539 return retval;
1541 else
1543 gint len = strlen (group->entries[j].long_name);
1545 if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
1546 (arg[len] == '=' || arg[len] == 0))
1548 gchar *value = NULL;
1549 gchar *option_name;
1551 add_pending_null (context, &((*argv)[*idx]), NULL);
1552 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1554 if (arg[len] == '=')
1555 value = arg + len + 1;
1556 else if (*idx < *argc - 1)
1558 if (!OPTIONAL_ARG (&group->entries[j]))
1560 value = (*argv)[*idx + 1];
1561 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1562 (*idx)++;
1564 else
1566 if ((*argv)[*idx + 1][0] == '-')
1568 gboolean retval;
1569 retval = parse_arg (context, group, &group->entries[j],
1570 NULL, option_name, error);
1571 *parsed = TRUE;
1572 g_free (option_name);
1573 return retval;
1575 else
1577 value = (*argv)[*idx + 1];
1578 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1579 (*idx)++;
1583 else if (*idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1585 gboolean retval;
1586 retval = parse_arg (context, group, &group->entries[j],
1587 NULL, option_name, error);
1588 *parsed = TRUE;
1589 g_free (option_name);
1590 return retval;
1592 else
1594 g_set_error (error,
1595 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1596 _("Missing argument for %s"), option_name);
1597 g_free (option_name);
1598 return FALSE;
1601 if (!parse_arg (context, group, &group->entries[j],
1602 value, option_name, error))
1604 g_free (option_name);
1605 return FALSE;
1608 g_free (option_name);
1609 *parsed = TRUE;
1614 return TRUE;
1617 static gboolean
1618 parse_remaining_arg (GOptionContext *context,
1619 GOptionGroup *group,
1620 gint *idx,
1621 gint *argc,
1622 gchar ***argv,
1623 GError **error,
1624 gboolean *parsed)
1626 gint j;
1628 for (j = 0; j < group->n_entries; j++)
1630 if (*idx >= *argc)
1631 return TRUE;
1633 if (group->entries[j].long_name[0])
1634 continue;
1636 g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_CALLBACK ||
1637 group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1638 group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1640 add_pending_null (context, &((*argv)[*idx]), NULL);
1642 if (!parse_arg (context, group, &group->entries[j], (*argv)[*idx], "", error))
1643 return FALSE;
1645 *parsed = TRUE;
1646 return TRUE;
1649 return TRUE;
1652 static void
1653 free_changes_list (GOptionContext *context,
1654 gboolean revert)
1656 GList *list;
1658 for (list = context->changes; list != NULL; list = list->next)
1660 Change *change = list->data;
1662 if (revert)
1664 switch (change->arg_type)
1666 case G_OPTION_ARG_NONE:
1667 *(gboolean *)change->arg_data = change->prev.bool;
1668 break;
1669 case G_OPTION_ARG_INT:
1670 *(gint *)change->arg_data = change->prev.integer;
1671 break;
1672 case G_OPTION_ARG_STRING:
1673 case G_OPTION_ARG_FILENAME:
1674 g_free (change->allocated.str);
1675 *(gchar **)change->arg_data = change->prev.str;
1676 break;
1677 case G_OPTION_ARG_STRING_ARRAY:
1678 case G_OPTION_ARG_FILENAME_ARRAY:
1679 g_strfreev (change->allocated.array.data);
1680 *(gchar ***)change->arg_data = change->prev.array;
1681 break;
1682 case G_OPTION_ARG_DOUBLE:
1683 *(gdouble *)change->arg_data = change->prev.dbl;
1684 break;
1685 case G_OPTION_ARG_INT64:
1686 *(gint64 *)change->arg_data = change->prev.int64;
1687 break;
1688 default:
1689 g_assert_not_reached ();
1693 g_free (change);
1696 g_list_free (context->changes);
1697 context->changes = NULL;
1700 static void
1701 free_pending_nulls (GOptionContext *context,
1702 gboolean perform_nulls)
1704 GList *list;
1706 for (list = context->pending_nulls; list != NULL; list = list->next)
1708 PendingNull *n = list->data;
1710 if (perform_nulls)
1712 if (n->value)
1714 /* Copy back the short options */
1715 *(n->ptr)[0] = '-';
1716 strcpy (*n->ptr + 1, n->value);
1718 else
1720 if (context->strv_mode)
1721 g_free (*n->ptr);
1723 *n->ptr = NULL;
1727 g_free (n->value);
1728 g_free (n);
1731 g_list_free (context->pending_nulls);
1732 context->pending_nulls = NULL;
1735 /* Use a platform-specific mechanism to look up the first argument to
1736 * the current process.
1737 * Note if you implement this for other platforms, also add it to
1738 * tests/option-argv0.c
1740 static char *
1741 platform_get_argv0 (void)
1743 #if defined __linux
1744 char *cmdline;
1745 char *base_arg0;
1746 gsize len;
1748 if (!g_file_get_contents ("/proc/self/cmdline",
1749 &cmdline,
1750 &len,
1751 NULL))
1752 return NULL;
1753 /* Sanity check for a NUL terminator. */
1754 if (!memchr (cmdline, 0, len))
1755 return NULL;
1756 /* We could just return cmdline, but I think it's better
1757 * to hold on to a smaller malloc block; the arguments
1758 * could be large.
1760 base_arg0 = g_path_get_basename (cmdline);
1761 g_free (cmdline);
1762 return base_arg0;
1763 #elif defined __OpenBSD__
1764 char **cmdline;
1765 char *base_arg0;
1766 gsize len;
1768 int mib[] = { CTL_KERN, KERN_PROC_ARGS, getpid(), KERN_PROC_ARGV };
1770 if (sysctl (mib, G_N_ELEMENTS (mib), NULL, &len, NULL, 0) == -1)
1771 return NULL;
1773 cmdline = g_malloc0 (len);
1775 if (sysctl (mib, G_N_ELEMENTS (mib), cmdline, &len, NULL, 0) == -1)
1777 g_free (cmdline);
1778 return NULL;
1781 /* We could just return cmdline, but I think it's better
1782 * to hold on to a smaller malloc block; the arguments
1783 * could be large.
1785 base_arg0 = g_path_get_basename (*cmdline);
1786 g_free (cmdline);
1787 return base_arg0;
1788 #endif
1790 return NULL;
1794 * g_option_context_parse:
1795 * @context: a #GOptionContext
1796 * @argc: (inout) (allow-none): a pointer to the number of command line arguments
1797 * @argv: (inout) (array length=argc) (allow-none): a pointer to the array of command line arguments
1798 * @error: a return location for errors
1800 * Parses the command line arguments, recognizing options
1801 * which have been added to @context. A side-effect of
1802 * calling this function is that g_set_prgname() will be
1803 * called.
1805 * If the parsing is successful, any parsed arguments are
1806 * removed from the array and @argc and @argv are updated
1807 * accordingly. A '--' option is stripped from @argv
1808 * unless there are unparsed options before and after it,
1809 * or some of the options after it start with '-'. In case
1810 * of an error, @argc and @argv are left unmodified.
1812 * If automatic `--help` support is enabled
1813 * (see g_option_context_set_help_enabled()), and the
1814 * @argv array contains one of the recognized help options,
1815 * this function will produce help output to stdout and
1816 * call `exit (0)`.
1818 * Note that function depends on the [current locale][setlocale] for
1819 * automatic character set conversion of string and filename
1820 * arguments.
1822 * Returns: %TRUE if the parsing was successful,
1823 * %FALSE if an error occurred
1825 * Since: 2.6
1827 gboolean
1828 g_option_context_parse (GOptionContext *context,
1829 gint *argc,
1830 gchar ***argv,
1831 GError **error)
1833 gint i, j, k;
1834 GList *list;
1836 /* Set program name */
1837 if (!g_get_prgname())
1839 gchar *prgname;
1841 if (argc && argv && *argc)
1842 prgname = g_path_get_basename ((*argv)[0]);
1843 else
1844 prgname = platform_get_argv0 ();
1846 if (prgname)
1847 g_set_prgname (prgname);
1848 else
1849 g_set_prgname ("<unknown>");
1851 g_free (prgname);
1854 /* Call pre-parse hooks */
1855 list = context->groups;
1856 while (list)
1858 GOptionGroup *group = list->data;
1860 if (group->pre_parse_func)
1862 if (!(* group->pre_parse_func) (context, group,
1863 group->user_data, error))
1864 goto fail;
1867 list = list->next;
1870 if (context->main_group && context->main_group->pre_parse_func)
1872 if (!(* context->main_group->pre_parse_func) (context, context->main_group,
1873 context->main_group->user_data, error))
1874 goto fail;
1877 if (argc && argv)
1879 gboolean stop_parsing = FALSE;
1880 gboolean has_unknown = FALSE;
1881 gint separator_pos = 0;
1883 for (i = 1; i < *argc; i++)
1885 gchar *arg, *dash;
1886 gboolean parsed = FALSE;
1888 if ((*argv)[i][0] == '-' && (*argv)[i][1] != '\0' && !stop_parsing)
1890 if ((*argv)[i][1] == '-')
1892 /* -- option */
1894 arg = (*argv)[i] + 2;
1896 /* '--' terminates list of arguments */
1897 if (*arg == 0)
1899 separator_pos = i;
1900 stop_parsing = TRUE;
1901 continue;
1904 /* Handle help options */
1905 if (context->help_enabled)
1907 if (strcmp (arg, "help") == 0)
1908 print_help (context, TRUE, NULL);
1909 else if (strcmp (arg, "help-all") == 0)
1910 print_help (context, FALSE, NULL);
1911 else if (strncmp (arg, "help-", 5) == 0)
1913 list = context->groups;
1915 while (list)
1917 GOptionGroup *group = list->data;
1919 if (strcmp (arg + 5, group->name) == 0)
1920 print_help (context, FALSE, group);
1922 list = list->next;
1927 if (context->main_group &&
1928 !parse_long_option (context, context->main_group, &i, arg,
1929 FALSE, argc, argv, error, &parsed))
1930 goto fail;
1932 if (parsed)
1933 continue;
1935 /* Try the groups */
1936 list = context->groups;
1937 while (list)
1939 GOptionGroup *group = list->data;
1941 if (!parse_long_option (context, group, &i, arg,
1942 FALSE, argc, argv, error, &parsed))
1943 goto fail;
1945 if (parsed)
1946 break;
1948 list = list->next;
1951 if (parsed)
1952 continue;
1954 /* Now look for --<group>-<option> */
1955 dash = strchr (arg, '-');
1956 if (dash)
1958 /* Try the groups */
1959 list = context->groups;
1960 while (list)
1962 GOptionGroup *group = list->data;
1964 if (strncmp (group->name, arg, dash - arg) == 0)
1966 if (!parse_long_option (context, group, &i, dash + 1,
1967 TRUE, argc, argv, error, &parsed))
1968 goto fail;
1970 if (parsed)
1971 break;
1974 list = list->next;
1978 if (context->ignore_unknown)
1979 continue;
1981 else
1982 { /* short option */
1983 gint new_i = i, arg_length;
1984 gboolean *nulled_out = NULL;
1985 gboolean has_h_entry = context_has_h_entry (context);
1986 arg = (*argv)[i] + 1;
1987 arg_length = strlen (arg);
1988 nulled_out = g_newa (gboolean, arg_length);
1989 memset (nulled_out, 0, arg_length * sizeof (gboolean));
1990 for (j = 0; j < arg_length; j++)
1992 if (context->help_enabled && (arg[j] == '?' ||
1993 (arg[j] == 'h' && !has_h_entry)))
1994 print_help (context, TRUE, NULL);
1995 parsed = FALSE;
1996 if (context->main_group &&
1997 !parse_short_option (context, context->main_group,
1998 i, &new_i, arg[j],
1999 argc, argv, error, &parsed))
2000 goto fail;
2001 if (!parsed)
2003 /* Try the groups */
2004 list = context->groups;
2005 while (list)
2007 GOptionGroup *group = list->data;
2008 if (!parse_short_option (context, group, i, &new_i, arg[j],
2009 argc, argv, error, &parsed))
2010 goto fail;
2011 if (parsed)
2012 break;
2013 list = list->next;
2017 if (context->ignore_unknown && parsed)
2018 nulled_out[j] = TRUE;
2019 else if (context->ignore_unknown)
2020 continue;
2021 else if (!parsed)
2022 break;
2023 /* !context->ignore_unknown && parsed */
2025 if (context->ignore_unknown)
2027 gchar *new_arg = NULL;
2028 gint arg_index = 0;
2029 for (j = 0; j < arg_length; j++)
2031 if (!nulled_out[j])
2033 if (!new_arg)
2034 new_arg = g_malloc (arg_length + 1);
2035 new_arg[arg_index++] = arg[j];
2038 if (new_arg)
2039 new_arg[arg_index] = '\0';
2040 add_pending_null (context, &((*argv)[i]), new_arg);
2041 i = new_i;
2043 else if (parsed)
2045 add_pending_null (context, &((*argv)[i]), NULL);
2046 i = new_i;
2050 if (!parsed)
2051 has_unknown = TRUE;
2053 if (!parsed && !context->ignore_unknown)
2055 g_set_error (error,
2056 G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
2057 _("Unknown option %s"), (*argv)[i]);
2058 goto fail;
2061 else
2063 /* Collect remaining args */
2064 if (context->main_group &&
2065 !parse_remaining_arg (context, context->main_group, &i,
2066 argc, argv, error, &parsed))
2067 goto fail;
2069 if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
2070 separator_pos = 0;
2074 if (separator_pos > 0)
2075 add_pending_null (context, &((*argv)[separator_pos]), NULL);
2079 /* Call post-parse hooks */
2080 list = context->groups;
2081 while (list)
2083 GOptionGroup *group = list->data;
2085 if (group->post_parse_func)
2087 if (!(* group->post_parse_func) (context, group,
2088 group->user_data, error))
2089 goto fail;
2092 list = list->next;
2095 if (context->main_group && context->main_group->post_parse_func)
2097 if (!(* context->main_group->post_parse_func) (context, context->main_group,
2098 context->main_group->user_data, error))
2099 goto fail;
2102 if (argc && argv)
2104 free_pending_nulls (context, TRUE);
2106 for (i = 1; i < *argc; i++)
2108 for (k = i; k < *argc; k++)
2109 if ((*argv)[k] != NULL)
2110 break;
2112 if (k > i)
2114 k -= i;
2115 for (j = i + k; j < *argc; j++)
2117 (*argv)[j-k] = (*argv)[j];
2118 (*argv)[j] = NULL;
2120 *argc -= k;
2125 return TRUE;
2127 fail:
2129 /* Call error hooks */
2130 list = context->groups;
2131 while (list)
2133 GOptionGroup *group = list->data;
2135 if (group->error_func)
2136 (* group->error_func) (context, group,
2137 group->user_data, error);
2139 list = list->next;
2142 if (context->main_group && context->main_group->error_func)
2143 (* context->main_group->error_func) (context, context->main_group,
2144 context->main_group->user_data, error);
2146 free_changes_list (context, TRUE);
2147 free_pending_nulls (context, FALSE);
2149 return FALSE;
2153 * g_option_group_new:
2154 * @name: the name for the option group, this is used to provide
2155 * help for the options in this group with `--help-`@name
2156 * @description: a description for this group to be shown in
2157 * `--help`. This string is translated using the translation
2158 * domain or translation function of the group
2159 * @help_description: a description for the `--help-`@name option.
2160 * This string is translated using the translation domain or translation function
2161 * of the group
2162 * @user_data: (allow-none): user data that will be passed to the pre- and post-parse hooks,
2163 * the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
2164 * @destroy: (allow-none): a function that will be called to free @user_data, or %NULL
2166 * Creates a new #GOptionGroup.
2168 * Returns: a newly created option group. It should be added
2169 * to a #GOptionContext or freed with g_option_group_free().
2171 * Since: 2.6
2173 GOptionGroup *
2174 g_option_group_new (const gchar *name,
2175 const gchar *description,
2176 const gchar *help_description,
2177 gpointer user_data,
2178 GDestroyNotify destroy)
2181 GOptionGroup *group;
2183 group = g_new0 (GOptionGroup, 1);
2184 group->name = g_strdup (name);
2185 group->description = g_strdup (description);
2186 group->help_description = g_strdup (help_description);
2187 group->user_data = user_data;
2188 group->destroy_notify = destroy;
2190 return group;
2195 * g_option_group_free:
2196 * @group: a #GOptionGroup
2198 * Frees a #GOptionGroup. Note that you must not free groups
2199 * which have been added to a #GOptionContext.
2201 * Since: 2.6
2203 void
2204 g_option_group_free (GOptionGroup *group)
2206 g_return_if_fail (group != NULL);
2208 g_free (group->name);
2209 g_free (group->description);
2210 g_free (group->help_description);
2212 g_free (group->entries);
2214 if (group->destroy_notify)
2215 (* group->destroy_notify) (group->user_data);
2217 if (group->translate_notify)
2218 (* group->translate_notify) (group->translate_data);
2220 g_free (group);
2225 * g_option_group_add_entries:
2226 * @group: a #GOptionGroup
2227 * @entries: a %NULL-terminated array of #GOptionEntrys
2229 * Adds the options specified in @entries to @group.
2231 * Since: 2.6
2233 void
2234 g_option_group_add_entries (GOptionGroup *group,
2235 const GOptionEntry *entries)
2237 gint i, n_entries;
2239 g_return_if_fail (entries != NULL);
2241 for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++) ;
2243 group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
2245 memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
2247 for (i = group->n_entries; i < group->n_entries + n_entries; i++)
2249 gchar c = group->entries[i].short_name;
2251 if (c == '-' || (c != 0 && !g_ascii_isprint (c)))
2253 g_warning (G_STRLOC ": ignoring invalid short option '%c' (%d) in entry %s:%s",
2254 c, c, group->name, group->entries[i].long_name);
2255 group->entries[i].short_name = '\0';
2258 if (group->entries[i].arg != G_OPTION_ARG_NONE &&
2259 (group->entries[i].flags & G_OPTION_FLAG_REVERSE) != 0)
2261 g_warning (G_STRLOC ": ignoring reverse flag on option of arg-type %d in entry %s:%s",
2262 group->entries[i].arg, group->name, group->entries[i].long_name);
2264 group->entries[i].flags &= ~G_OPTION_FLAG_REVERSE;
2267 if (group->entries[i].arg != G_OPTION_ARG_CALLBACK &&
2268 (group->entries[i].flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME)) != 0)
2270 g_warning (G_STRLOC ": ignoring no-arg, optional-arg or filename flags (%d) on option of arg-type %d in entry %s:%s",
2271 group->entries[i].flags, group->entries[i].arg, group->name, group->entries[i].long_name);
2273 group->entries[i].flags &= ~(G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME);
2277 group->n_entries += n_entries;
2281 * g_option_group_set_parse_hooks:
2282 * @group: a #GOptionGroup
2283 * @pre_parse_func: (allow-none): a function to call before parsing, or %NULL
2284 * @post_parse_func: (allow-none): a function to call after parsing, or %NULL
2286 * Associates two functions with @group which will be called
2287 * from g_option_context_parse() before the first option is parsed
2288 * and after the last option has been parsed, respectively.
2290 * Note that the user data to be passed to @pre_parse_func and
2291 * @post_parse_func can be specified when constructing the group
2292 * with g_option_group_new().
2294 * Since: 2.6
2296 void
2297 g_option_group_set_parse_hooks (GOptionGroup *group,
2298 GOptionParseFunc pre_parse_func,
2299 GOptionParseFunc post_parse_func)
2301 g_return_if_fail (group != NULL);
2303 group->pre_parse_func = pre_parse_func;
2304 group->post_parse_func = post_parse_func;
2308 * g_option_group_set_error_hook:
2309 * @group: a #GOptionGroup
2310 * @error_func: a function to call when an error occurs
2312 * Associates a function with @group which will be called
2313 * from g_option_context_parse() when an error occurs.
2315 * Note that the user data to be passed to @error_func can be
2316 * specified when constructing the group with g_option_group_new().
2318 * Since: 2.6
2320 void
2321 g_option_group_set_error_hook (GOptionGroup *group,
2322 GOptionErrorFunc error_func)
2324 g_return_if_fail (group != NULL);
2326 group->error_func = error_func;
2331 * g_option_group_set_translate_func:
2332 * @group: a #GOptionGroup
2333 * @func: (allow-none): the #GTranslateFunc, or %NULL
2334 * @data: (allow-none): user data to pass to @func, or %NULL
2335 * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2337 * Sets the function which is used to translate user-visible strings,
2338 * for `--help` output. Different groups can use different
2339 * #GTranslateFuncs. If @func is %NULL, strings are not translated.
2341 * If you are using gettext(), you only need to set the translation
2342 * domain, see g_option_group_set_translation_domain().
2344 * Since: 2.6
2346 void
2347 g_option_group_set_translate_func (GOptionGroup *group,
2348 GTranslateFunc func,
2349 gpointer data,
2350 GDestroyNotify destroy_notify)
2352 g_return_if_fail (group != NULL);
2354 if (group->translate_notify)
2355 group->translate_notify (group->translate_data);
2357 group->translate_func = func;
2358 group->translate_data = data;
2359 group->translate_notify = destroy_notify;
2362 static const gchar *
2363 dgettext_swapped (const gchar *msgid,
2364 const gchar *domainname)
2366 return g_dgettext (domainname, msgid);
2370 * g_option_group_set_translation_domain:
2371 * @group: a #GOptionGroup
2372 * @domain: the domain to use
2374 * A convenience function to use gettext() for translating
2375 * user-visible strings.
2377 * Since: 2.6
2379 void
2380 g_option_group_set_translation_domain (GOptionGroup *group,
2381 const gchar *domain)
2383 g_return_if_fail (group != NULL);
2385 g_option_group_set_translate_func (group,
2386 (GTranslateFunc)dgettext_swapped,
2387 g_strdup (domain),
2388 g_free);
2392 * g_option_context_set_translate_func:
2393 * @context: a #GOptionContext
2394 * @func: (allow-none): the #GTranslateFunc, or %NULL
2395 * @data: (allow-none): user data to pass to @func, or %NULL
2396 * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2398 * Sets the function which is used to translate the contexts
2399 * user-visible strings, for `--help` output. If @func is %NULL,
2400 * strings are not translated.
2402 * Note that option groups have their own translation functions,
2403 * this function only affects the @parameter_string (see g_option_context_new()),
2404 * the summary (see g_option_context_set_summary()) and the description
2405 * (see g_option_context_set_description()).
2407 * If you are using gettext(), you only need to set the translation
2408 * domain, see g_option_context_set_translation_domain().
2410 * Since: 2.12
2412 void
2413 g_option_context_set_translate_func (GOptionContext *context,
2414 GTranslateFunc func,
2415 gpointer data,
2416 GDestroyNotify destroy_notify)
2418 g_return_if_fail (context != NULL);
2420 if (context->translate_notify)
2421 context->translate_notify (context->translate_data);
2423 context->translate_func = func;
2424 context->translate_data = data;
2425 context->translate_notify = destroy_notify;
2429 * g_option_context_set_translation_domain:
2430 * @context: a #GOptionContext
2431 * @domain: the domain to use
2433 * A convenience function to use gettext() for translating
2434 * user-visible strings.
2436 * Since: 2.12
2438 void
2439 g_option_context_set_translation_domain (GOptionContext *context,
2440 const gchar *domain)
2442 g_return_if_fail (context != NULL);
2444 g_option_context_set_translate_func (context,
2445 (GTranslateFunc)dgettext_swapped,
2446 g_strdup (domain),
2447 g_free);
2451 * g_option_context_set_summary:
2452 * @context: a #GOptionContext
2453 * @summary: (allow-none): a string to be shown in `--help` output
2454 * before the list of options, or %NULL
2456 * Adds a string to be displayed in `--help` output before the list
2457 * of options. This is typically a summary of the program functionality.
2459 * Note that the summary is translated (see
2460 * g_option_context_set_translate_func() and
2461 * g_option_context_set_translation_domain()).
2463 * Since: 2.12
2465 void
2466 g_option_context_set_summary (GOptionContext *context,
2467 const gchar *summary)
2469 g_return_if_fail (context != NULL);
2471 g_free (context->summary);
2472 context->summary = g_strdup (summary);
2477 * g_option_context_get_summary:
2478 * @context: a #GOptionContext
2480 * Returns the summary. See g_option_context_set_summary().
2482 * Returns: the summary
2484 * Since: 2.12
2486 const gchar *
2487 g_option_context_get_summary (GOptionContext *context)
2489 g_return_val_if_fail (context != NULL, NULL);
2491 return context->summary;
2495 * g_option_context_set_description:
2496 * @context: a #GOptionContext
2497 * @description: (allow-none): a string to be shown in `--help` output
2498 * after the list of options, or %NULL
2500 * Adds a string to be displayed in `--help` output after the list
2501 * of options. This text often includes a bug reporting address.
2503 * Note that the summary is translated (see
2504 * g_option_context_set_translate_func()).
2506 * Since: 2.12
2508 void
2509 g_option_context_set_description (GOptionContext *context,
2510 const gchar *description)
2512 g_return_if_fail (context != NULL);
2514 g_free (context->description);
2515 context->description = g_strdup (description);
2520 * g_option_context_get_description:
2521 * @context: a #GOptionContext
2523 * Returns the description. See g_option_context_set_description().
2525 * Returns: the description
2527 * Since: 2.12
2529 const gchar *
2530 g_option_context_get_description (GOptionContext *context)
2532 g_return_val_if_fail (context != NULL, NULL);
2534 return context->description;
2538 * g_option_context_parse_strv:
2539 * @context: a #GOptionContext
2540 * @arguments: (inout) (array null-terminated=1): a pointer to the
2541 * command line arguments (which must be in UTF-8 on Windows)
2542 * @error: a return location for errors
2544 * Parses the command line arguments.
2546 * This function is similar to g_option_context_parse() except that it
2547 * respects the normal memory rules when dealing with a strv instead of
2548 * assuming that the passed-in array is the argv of the main function.
2550 * In particular, strings that are removed from the arguments list will
2551 * be freed using g_free().
2553 * On Windows, the strings are expected to be in UTF-8. This is in
2554 * contrast to g_option_context_parse() which expects them to be in the
2555 * system codepage, which is how they are passed as @argv to main().
2556 * See g_win32_get_command_line() for a solution.
2558 * This function is useful if you are trying to use #GOptionContext with
2559 * #GApplication.
2561 * Returns: %TRUE if the parsing was successful,
2562 * %FALSE if an error occurred
2564 * Since: 2.40
2566 gboolean
2567 g_option_context_parse_strv (GOptionContext *context,
2568 gchar ***arguments,
2569 GError **error)
2571 gboolean success;
2572 gint argc;
2574 context->strv_mode = TRUE;
2575 argc = g_strv_length (*arguments);
2576 success = g_option_context_parse (context, &argc, arguments, error);
2577 context->strv_mode = FALSE;
2579 return success;