1 /* gmarkup.c - Simple XML-like parser
3 * Copyright 2000, 2003 Red Hat, Inc.
4 * Copyright 2007, 2008 Ryan Lortie <desrt@desrt.ca>
6 * GLib is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation; either version 2 of the
9 * License, or (at your option) any later version.
11 * GLib 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 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with GLib; see the file COPYING.LIB. If not,
18 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 * Boston, MA 02111-1307, USA.
33 #include "gstrfuncs.h"
35 #include "gtestutils.h"
40 * @Title: Simple XML Subset Parser
41 * @Short_description: parses a subset of XML
42 * @See_also: <ulink url="http://www.w3.org/TR/REC-xml/">XML
43 * Specification</ulink>
45 * The "GMarkup" parser is intended to parse a simple markup format
46 * that's a subset of XML. This is a small, efficient, easy-to-use
47 * parser. It should not be used if you expect to interoperate with
48 * other applications generating full-scale XML. However, it's very
49 * useful for application data files, config files, etc. where you
50 * know your application will be the only one writing the file.
51 * Full-scale XML parsers should be able to parse the subset used by
52 * GMarkup, so you can easily migrate to full-scale XML at a later
53 * time if the need arises.
55 * GMarkup is not guaranteed to signal an error on all invalid XML;
56 * the parser may accept documents that an XML parser would not.
57 * However, XML documents which are not well-formed<footnote
58 * id="wellformed">Being wellformed is a weaker condition than being
59 * valid. See the <ulink url="http://www.w3.org/TR/REC-xml/">XML
60 * specification</ulink> for definitions of these terms.</footnote>
61 * are not considered valid GMarkup documents.
63 * Simplifications to XML include:
65 * <listitem>Only UTF-8 encoding is allowed</listitem>
66 * <listitem>No user-defined entities</listitem>
67 * <listitem>Processing instructions, comments and the doctype declaration
68 * are "passed through" but are not interpreted in any way</listitem>
69 * <listitem>No DTD or validation.</listitem>
72 * The markup format does support:
74 * <listitem>Elements</listitem>
75 * <listitem>Attributes</listitem>
76 * <listitem>5 standard entities:
77 * <literal>&amp; &lt; &gt; &quot; &apos;</literal>
79 * <listitem>Character references</listitem>
80 * <listitem>Sections marked as CDATA</listitem>
85 g_markup_error_quark (void)
87 return g_quark_from_static_string ("g-markup-error-quark");
93 STATE_AFTER_OPEN_ANGLE,
94 STATE_AFTER_CLOSE_ANGLE,
95 STATE_AFTER_ELISION_SLASH, /* the slash that obviates need for end element */
96 STATE_INSIDE_OPEN_TAG_NAME,
97 STATE_INSIDE_ATTRIBUTE_NAME,
98 STATE_AFTER_ATTRIBUTE_NAME,
99 STATE_BETWEEN_ATTRIBUTES,
100 STATE_AFTER_ATTRIBUTE_EQUALS_SIGN,
101 STATE_INSIDE_ATTRIBUTE_VALUE_SQ,
102 STATE_INSIDE_ATTRIBUTE_VALUE_DQ,
104 STATE_AFTER_CLOSE_TAG_SLASH,
105 STATE_INSIDE_CLOSE_TAG_NAME,
106 STATE_AFTER_CLOSE_TAG_NAME,
107 STATE_INSIDE_PASSTHROUGH,
113 const char *prev_element;
114 const GMarkupParser *prev_parser;
115 gpointer prev_user_data;
116 } GMarkupRecursionTracker;
118 struct _GMarkupParseContext
120 const GMarkupParser *parser;
122 GMarkupParseFlags flags;
128 GDestroyNotify dnotify;
130 /* A piece of character data or an element that
131 * hasn't "ended" yet so we haven't yet called
132 * the callback for it.
134 GString *partial_chunk;
135 GSList *spare_chunks;
137 GMarkupParseState state;
139 GSList *tag_stack_gstr;
140 GSList *spare_list_nodes;
142 GString **attr_names;
143 GString **attr_values;
147 const gchar *current_text;
148 gssize current_text_len;
149 const gchar *current_text_end;
151 /* used to save the start of the last interesting thingy */
156 guint document_empty : 1;
158 guint awaiting_pop : 1;
161 /* subparser support */
162 GSList *subparser_stack; /* (GMarkupRecursionTracker *) */
163 const char *subparser_element;
164 gpointer held_user_data;
168 * Helpers to reduce our allocation overhead, we have
169 * a well defined allocation lifecycle.
172 get_list_node (GMarkupParseContext *context, gpointer data)
175 if (context->spare_list_nodes != NULL)
177 node = context->spare_list_nodes;
178 context->spare_list_nodes = g_slist_remove_link (context->spare_list_nodes, node);
181 node = g_slist_alloc();
187 free_list_node (GMarkupParseContext *context, GSList *node)
190 context->spare_list_nodes = g_slist_concat (node, context->spare_list_nodes);
194 string_blank (GString *string)
196 string->str[0] = '\0';
201 * g_markup_parse_context_new:
202 * @parser: a #GMarkupParser
203 * @flags: one or more #GMarkupParseFlags
204 * @user_data: user data to pass to #GMarkupParser functions
205 * @user_data_dnotify: user data destroy notifier called when
206 * the parse context is freed
208 * Creates a new parse context. A parse context is used to parse
209 * marked-up documents. You can feed any number of documents into
210 * a context, as long as no errors occur; once an error occurs,
211 * the parse context can't continue to parse text (you have to
212 * free it and create a new parse context).
214 * Return value: a new #GMarkupParseContext
216 GMarkupParseContext *
217 g_markup_parse_context_new (const GMarkupParser *parser,
218 GMarkupParseFlags flags,
220 GDestroyNotify user_data_dnotify)
222 GMarkupParseContext *context;
224 g_return_val_if_fail (parser != NULL, NULL);
226 context = g_new (GMarkupParseContext, 1);
228 context->parser = parser;
229 context->flags = flags;
230 context->user_data = user_data;
231 context->dnotify = user_data_dnotify;
233 context->line_number = 1;
234 context->char_number = 1;
236 context->partial_chunk = NULL;
237 context->spare_chunks = NULL;
238 context->spare_list_nodes = NULL;
240 context->state = STATE_START;
241 context->tag_stack = NULL;
242 context->tag_stack_gstr = NULL;
243 context->attr_names = NULL;
244 context->attr_values = NULL;
245 context->cur_attr = -1;
246 context->alloc_attrs = 0;
248 context->current_text = NULL;
249 context->current_text_len = -1;
250 context->current_text_end = NULL;
252 context->start = NULL;
253 context->iter = NULL;
255 context->document_empty = TRUE;
256 context->parsing = FALSE;
258 context->awaiting_pop = FALSE;
259 context->subparser_stack = NULL;
260 context->subparser_element = NULL;
262 /* this is only looked at if awaiting_pop = TRUE. initialise anyway. */
263 context->held_user_data = NULL;
265 context->balance = 0;
271 string_full_free (gpointer ptr)
273 g_string_free (ptr, TRUE);
276 static void clear_attributes (GMarkupParseContext *context);
279 * g_markup_parse_context_free:
280 * @context: a #GMarkupParseContext
282 * Frees a #GMarkupParseContext.
284 * This function can't be called from inside one of the
285 * #GMarkupParser functions or while a subparser is pushed.
288 g_markup_parse_context_free (GMarkupParseContext *context)
290 g_return_if_fail (context != NULL);
291 g_return_if_fail (!context->parsing);
292 g_return_if_fail (!context->subparser_stack);
293 g_return_if_fail (!context->awaiting_pop);
295 if (context->dnotify)
296 (* context->dnotify) (context->user_data);
298 clear_attributes (context);
299 g_free (context->attr_names);
300 g_free (context->attr_values);
302 g_slist_free_full (context->tag_stack_gstr, string_full_free);
303 g_slist_free (context->tag_stack);
305 g_slist_free_full (context->spare_chunks, string_full_free);
306 g_slist_free (context->spare_list_nodes);
308 if (context->partial_chunk)
309 g_string_free (context->partial_chunk, TRUE);
314 static void pop_subparser_stack (GMarkupParseContext *context);
317 mark_error (GMarkupParseContext *context,
320 context->state = STATE_ERROR;
322 if (context->parser->error)
323 (*context->parser->error) (context, error, context->user_data);
325 /* report the error all the way up to free all the user-data */
326 while (context->subparser_stack)
328 pop_subparser_stack (context);
329 context->awaiting_pop = FALSE; /* already been freed */
331 if (context->parser->error)
332 (*context->parser->error) (context, error, context->user_data);
337 set_error (GMarkupParseContext *context,
341 ...) G_GNUC_PRINTF (4, 5);
344 set_error_literal (GMarkupParseContext *context,
347 const gchar *message)
351 tmp_error = g_error_new_literal (G_MARKUP_ERROR, code, message);
353 g_prefix_error (&tmp_error,
354 _("Error on line %d char %d: "),
355 context->line_number,
356 context->char_number);
358 mark_error (context, tmp_error);
360 g_propagate_error (error, tmp_error);
364 set_error (GMarkupParseContext *context,
374 va_start (args, format);
375 s = g_strdup_vprintf (format, args);
378 /* Make sure that the GError message is valid UTF-8
379 * even if it is complaining about invalid UTF-8 in the markup
381 s_valid = _g_utf8_make_valid (s);
382 set_error_literal (context, error, code, s);
389 propagate_error (GMarkupParseContext *context,
393 if (context->flags & G_MARKUP_PREFIX_ERROR_POSITION)
394 g_prefix_error (&src,
395 _("Error on line %d char %d: "),
396 context->line_number,
397 context->char_number);
399 mark_error (context, src);
401 g_propagate_error (dest, src);
404 #define IS_COMMON_NAME_END_CHAR(c) \
405 ((c) == '=' || (c) == '/' || (c) == '>' || (c) == ' ')
408 slow_name_validate (GMarkupParseContext *context,
412 const gchar *p = name;
414 if (!g_utf8_validate (name, strlen (name), NULL))
416 set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
417 _("Invalid UTF-8 encoded text in name - not valid '%s'"), name);
421 if (!(g_ascii_isalpha (*p) ||
422 (!IS_COMMON_NAME_END_CHAR (*p) &&
425 g_unichar_isalpha (g_utf8_get_char (p))))))
427 set_error (context, error, G_MARKUP_ERROR_PARSE,
428 _("'%s' is not a valid name "), name);
432 for (p = g_utf8_next_char (name); *p != '\0'; p = g_utf8_next_char (p))
435 if (!(g_ascii_isalnum (*p) ||
436 (!IS_COMMON_NAME_END_CHAR (*p) &&
441 g_unichar_isalpha (g_utf8_get_char (p))))))
443 set_error (context, error, G_MARKUP_ERROR_PARSE,
444 _("'%s' is not a valid name: '%c' "), name, *p);
452 * Use me for elements, attributes etc.
455 name_validate (GMarkupParseContext *context,
462 /* name start char */
464 if (G_UNLIKELY (IS_COMMON_NAME_END_CHAR (*p) ||
465 !(g_ascii_isalpha (*p) || *p == '_' || *p == ':')))
468 for (mask = *p++; *p != '\0'; p++)
473 if (G_UNLIKELY (!(g_ascii_isalnum (*p) ||
474 (!IS_COMMON_NAME_END_CHAR (*p) &&
482 if (mask & 0x80) /* un-common / non-ascii */
488 return slow_name_validate (context, name, error);
492 text_validate (GMarkupParseContext *context,
497 if (!g_utf8_validate (p, len, NULL))
499 set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
500 _("Invalid UTF-8 encoded text in name - not valid '%s'"), p);
508 char_str (gunichar c,
512 g_unichar_to_utf8 (c, buf);
517 utf8_str (const gchar *utf8,
520 char_str (g_utf8_get_char (utf8), buf);
525 set_unescape_error (GMarkupParseContext *context,
527 const gchar *remaining_text,
535 gint remaining_newlines;
538 remaining_newlines = 0;
543 ++remaining_newlines;
547 va_start (args, format);
548 s = g_strdup_vprintf (format, args);
551 tmp_error = g_error_new (G_MARKUP_ERROR,
553 _("Error on line %d: %s"),
554 context->line_number - remaining_newlines,
559 mark_error (context, tmp_error);
561 g_propagate_error (error, tmp_error);
565 * re-write the GString in-place, unescaping anything that escaped.
566 * most XML does not contain entities, or escaping.
569 unescape_gstring_inplace (GMarkupParseContext *context,
577 gboolean normalize_attribute;
581 /* are we unescaping an attribute or not ? */
582 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
583 context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
584 normalize_attribute = TRUE;
586 normalize_attribute = FALSE;
589 * Meeks' theorum: unescaping can only shrink text.
590 * for < etc. this is obvious, for  more
591 * thought is required, but this is patently so.
594 for (from = to = string->str; *from != '\0'; from++, to++)
601 if (normalize_attribute && (*to == '\t' || *to == '\n'))
605 *to = normalize_attribute ? ' ' : '\n';
614 gboolean is_hex = FALSE;
626 /* digit is between start and p */
629 l = strtoul (from, &end, 16);
631 l = strtoul (from, &end, 10);
633 if (end == from || errno != 0)
635 set_unescape_error (context, error,
636 from, G_MARKUP_ERROR_PARSE,
637 _("Failed to parse '%-.*s', which "
638 "should have been a digit "
639 "inside a character reference "
640 "(ê for example) - perhaps "
641 "the digit is too large"),
645 else if (*end != ';')
647 set_unescape_error (context, error,
648 from, G_MARKUP_ERROR_PARSE,
649 _("Character reference did not end with a "
651 "most likely you used an ampersand "
652 "character without intending to start "
653 "an entity - escape ampersand as &"));
658 /* characters XML 1.1 permits */
659 if ((0 < l && l <= 0xD7FF) ||
660 (0xE000 <= l && l <= 0xFFFD) ||
661 (0x10000 <= l && l <= 0x10FFFF))
666 to += strlen (buf) - 1;
668 if (l >= 0x80) /* not ascii */
673 set_unescape_error (context, error,
674 from, G_MARKUP_ERROR_PARSE,
675 _("Character reference '%-.*s' does not "
676 "encode a permitted character"),
683 else if (strncmp (from, "lt;", 3) == 0)
688 else if (strncmp (from, "gt;", 3) == 0)
693 else if (strncmp (from, "amp;", 4) == 0)
698 else if (strncmp (from, "quot;", 5) == 0)
703 else if (strncmp (from, "apos;", 5) == 0)
711 set_unescape_error (context, error,
712 from, G_MARKUP_ERROR_PARSE,
713 _("Empty entity '&;' seen; valid "
714 "entities are: & " < > '"));
717 const char *end = strchr (from, ';');
719 set_unescape_error (context, error,
720 from, G_MARKUP_ERROR_PARSE,
721 _("Entity name '%-.*s' is not known"),
724 set_unescape_error (context, error,
725 from, G_MARKUP_ERROR_PARSE,
726 _("Entity did not end with a semicolon; "
727 "most likely you used an ampersand "
728 "character without intending to start "
729 "an entity - escape ampersand as &"));
736 g_assert (to - string->str <= string->len);
737 if (to - string->str != string->len)
738 g_string_truncate (string, to - string->str);
740 *is_ascii = !(mask & 0x80);
745 static inline gboolean
746 advance_char (GMarkupParseContext *context)
749 context->char_number++;
751 if (G_UNLIKELY (context->iter == context->current_text_end))
754 else if (G_UNLIKELY (*context->iter == '\n'))
756 context->line_number++;
757 context->char_number = 1;
763 static inline gboolean
766 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
770 skip_spaces (GMarkupParseContext *context)
774 if (!xml_isspace (*context->iter))
777 while (advance_char (context));
781 advance_to_name_end (GMarkupParseContext *context)
785 if (IS_COMMON_NAME_END_CHAR (*(context->iter)))
787 if (xml_isspace (*(context->iter)))
790 while (advance_char (context));
794 release_chunk (GMarkupParseContext *context, GString *str)
799 if (str->allocated_len > 256)
800 { /* large strings are unusual and worth freeing */
801 g_string_free (str, TRUE);
805 node = get_list_node (context, str);
806 context->spare_chunks = g_slist_concat (node, context->spare_chunks);
810 add_to_partial (GMarkupParseContext *context,
811 const gchar *text_start,
812 const gchar *text_end)
814 if (context->partial_chunk == NULL)
815 { /* allocate a new chunk to parse into */
817 if (context->spare_chunks != NULL)
819 GSList *node = context->spare_chunks;
820 context->spare_chunks = g_slist_remove_link (context->spare_chunks, node);
821 context->partial_chunk = node->data;
822 free_list_node (context, node);
825 context->partial_chunk = g_string_sized_new (MAX (28, text_end - text_start));
828 if (text_start != text_end)
829 g_string_insert_len (context->partial_chunk, -1,
830 text_start, text_end - text_start);
834 truncate_partial (GMarkupParseContext *context)
836 if (context->partial_chunk != NULL)
837 string_blank (context->partial_chunk);
840 static inline const gchar*
841 current_element (GMarkupParseContext *context)
843 return context->tag_stack->data;
847 pop_subparser_stack (GMarkupParseContext *context)
849 GMarkupRecursionTracker *tracker;
851 g_assert (context->subparser_stack);
853 tracker = context->subparser_stack->data;
855 context->awaiting_pop = TRUE;
856 context->held_user_data = context->user_data;
858 context->user_data = tracker->prev_user_data;
859 context->parser = tracker->prev_parser;
860 context->subparser_element = tracker->prev_element;
861 g_slice_free (GMarkupRecursionTracker, tracker);
863 context->subparser_stack = g_slist_delete_link (context->subparser_stack,
864 context->subparser_stack);
868 push_partial_as_tag (GMarkupParseContext *context)
870 GString *str = context->partial_chunk;
871 /* sadly, this is exported by gmarkup_get_element_stack as-is */
872 context->tag_stack = g_slist_concat (get_list_node (context, str->str), context->tag_stack);
873 context->tag_stack_gstr = g_slist_concat (get_list_node (context, str), context->tag_stack_gstr);
874 context->partial_chunk = NULL;
878 pop_tag (GMarkupParseContext *context)
880 GSList *nodea, *nodeb;
882 nodea = context->tag_stack;
883 nodeb = context->tag_stack_gstr;
884 release_chunk (context, nodeb->data);
885 context->tag_stack = g_slist_remove_link (context->tag_stack, nodea);
886 context->tag_stack_gstr = g_slist_remove_link (context->tag_stack_gstr, nodeb);
887 free_list_node (context, nodea);
888 free_list_node (context, nodeb);
892 possibly_finish_subparser (GMarkupParseContext *context)
894 if (current_element (context) == context->subparser_element)
895 pop_subparser_stack (context);
899 ensure_no_outstanding_subparser (GMarkupParseContext *context)
901 if (context->awaiting_pop)
902 g_critical ("During the first end_element call after invoking a "
903 "subparser you must pop the subparser stack and handle "
904 "the freeing of the subparser user_data. This can be "
905 "done by calling the end function of the subparser. "
906 "Very probably, your program just leaked memory.");
908 /* let valgrind watch the pointer disappear... */
909 context->held_user_data = NULL;
910 context->awaiting_pop = FALSE;
914 current_attribute (GMarkupParseContext *context)
916 g_assert (context->cur_attr >= 0);
917 return context->attr_names[context->cur_attr]->str;
921 add_attribute (GMarkupParseContext *context, GString *str)
923 if (context->cur_attr + 2 >= context->alloc_attrs)
925 context->alloc_attrs += 5; /* silly magic number */
926 context->attr_names = g_realloc (context->attr_names, sizeof(GString*)*context->alloc_attrs);
927 context->attr_values = g_realloc (context->attr_values, sizeof(GString*)*context->alloc_attrs);
930 context->attr_names[context->cur_attr] = str;
931 context->attr_values[context->cur_attr] = NULL;
932 context->attr_names[context->cur_attr+1] = NULL;
933 context->attr_values[context->cur_attr+1] = NULL;
937 clear_attributes (GMarkupParseContext *context)
939 /* Go ahead and free the attributes. */
940 for (; context->cur_attr >= 0; context->cur_attr--)
942 int pos = context->cur_attr;
943 release_chunk (context, context->attr_names[pos]);
944 release_chunk (context, context->attr_values[pos]);
945 context->attr_names[pos] = context->attr_values[pos] = NULL;
947 g_assert (context->cur_attr == -1);
948 g_assert (context->attr_names == NULL ||
949 context->attr_names[0] == NULL);
950 g_assert (context->attr_values == NULL ||
951 context->attr_values[0] == NULL);
954 /* This has to be a separate function to ensure the alloca's
955 * are unwound on exit - otherwise we grow & blow the stack
956 * with large documents
959 emit_start_element (GMarkupParseContext *context,
963 const gchar *start_name;
964 const gchar **attr_names;
965 const gchar **attr_values;
968 attr_names = g_newa (const gchar *, context->cur_attr + 2);
969 attr_values = g_newa (const gchar *, context->cur_attr + 2);
970 for (i = 0; i < context->cur_attr + 1; i++)
972 attr_names[i] = context->attr_names[i]->str;
973 attr_values[i] = context->attr_values[i]->str;
975 attr_names[i] = NULL;
976 attr_values[i] = NULL;
978 /* Call user callback for element start */
980 start_name = current_element (context);
982 if (context->parser->start_element &&
983 name_validate (context, start_name, error))
984 (* context->parser->start_element) (context,
986 (const gchar **)attr_names,
987 (const gchar **)attr_values,
990 clear_attributes (context);
992 if (tmp_error != NULL)
993 propagate_error (context, error, tmp_error);
997 * g_markup_parse_context_parse:
998 * @context: a #GMarkupParseContext
999 * @text: chunk of text to parse
1000 * @text_len: length of @text in bytes
1001 * @error: return location for a #GError
1003 * Feed some data to the #GMarkupParseContext.
1005 * The data need not be valid UTF-8; an error will be signaled if
1006 * it's invalid. The data need not be an entire document; you can
1007 * feed a document into the parser incrementally, via multiple calls
1008 * to this function. Typically, as you receive data from a network
1009 * connection or file, you feed each received chunk of data into this
1010 * function, aborting the process if an error occurs. Once an error
1011 * is reported, no further data may be fed to the #GMarkupParseContext;
1012 * all errors are fatal.
1014 * Return value: %FALSE if an error occurred, %TRUE on success
1017 g_markup_parse_context_parse (GMarkupParseContext *context,
1022 g_return_val_if_fail (context != NULL, FALSE);
1023 g_return_val_if_fail (text != NULL, FALSE);
1024 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1025 g_return_val_if_fail (!context->parsing, FALSE);
1028 text_len = strlen (text);
1033 context->parsing = TRUE;
1036 context->current_text = text;
1037 context->current_text_len = text_len;
1038 context->current_text_end = context->current_text + text_len;
1039 context->iter = context->current_text;
1040 context->start = context->iter;
1042 if (context->current_text_len == 0)
1045 while (context->iter != context->current_text_end)
1047 switch (context->state)
1050 /* Possible next state: AFTER_OPEN_ANGLE */
1052 g_assert (context->tag_stack == NULL);
1054 /* whitespace is ignored outside of any elements */
1055 skip_spaces (context);
1057 if (context->iter != context->current_text_end)
1059 if (*context->iter == '<')
1061 /* Move after the open angle */
1062 advance_char (context);
1064 context->state = STATE_AFTER_OPEN_ANGLE;
1066 /* this could start a passthrough */
1067 context->start = context->iter;
1069 /* document is now non-empty */
1070 context->document_empty = FALSE;
1074 set_error_literal (context,
1076 G_MARKUP_ERROR_PARSE,
1077 _("Document must begin with an element (e.g. <book>)"));
1082 case STATE_AFTER_OPEN_ANGLE:
1083 /* Possible next states: INSIDE_OPEN_TAG_NAME,
1084 * AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1086 if (*context->iter == '?' ||
1087 *context->iter == '!')
1089 /* include < in the passthrough */
1090 const gchar *openangle = "<";
1091 add_to_partial (context, openangle, openangle + 1);
1092 context->start = context->iter;
1093 context->balance = 1;
1094 context->state = STATE_INSIDE_PASSTHROUGH;
1096 else if (*context->iter == '/')
1099 advance_char (context);
1101 context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1103 else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1105 context->state = STATE_INSIDE_OPEN_TAG_NAME;
1107 /* start of tag name */
1108 context->start = context->iter;
1116 G_MARKUP_ERROR_PARSE,
1117 _("'%s' is not a valid character following "
1118 "a '<' character; it may not begin an "
1120 utf8_str (context->iter, buf));
1124 /* The AFTER_CLOSE_ANGLE state is actually sort of
1125 * broken, because it doesn't correspond to a range
1126 * of characters in the input stream as the others do,
1127 * and thus makes things harder to conceptualize
1129 case STATE_AFTER_CLOSE_ANGLE:
1130 /* Possible next states: INSIDE_TEXT, STATE_START */
1131 if (context->tag_stack == NULL)
1133 context->start = NULL;
1134 context->state = STATE_START;
1138 context->start = context->iter;
1139 context->state = STATE_INSIDE_TEXT;
1143 case STATE_AFTER_ELISION_SLASH:
1144 /* Possible next state: AFTER_CLOSE_ANGLE */
1147 /* We need to pop the tag stack and call the end_element
1148 * function, since this is the close tag
1150 GError *tmp_error = NULL;
1152 g_assert (context->tag_stack != NULL);
1154 possibly_finish_subparser (context);
1157 if (context->parser->end_element)
1158 (* context->parser->end_element) (context,
1159 current_element (context),
1163 ensure_no_outstanding_subparser (context);
1167 mark_error (context, tmp_error);
1168 g_propagate_error (error, tmp_error);
1172 if (*context->iter == '>')
1174 /* move after the close angle */
1175 advance_char (context);
1176 context->state = STATE_AFTER_CLOSE_ANGLE;
1184 G_MARKUP_ERROR_PARSE,
1185 _("Odd character '%s', expected a '>' character "
1186 "to end the empty-element tag '%s'"),
1187 utf8_str (context->iter, buf),
1188 current_element (context));
1195 case STATE_INSIDE_OPEN_TAG_NAME:
1196 /* Possible next states: BETWEEN_ATTRIBUTES */
1198 /* if there's a partial chunk then it's the first part of the
1199 * tag name. If there's a context->start then it's the start
1200 * of the tag name in current_text, the partial chunk goes
1201 * before that start though.
1203 advance_to_name_end (context);
1205 if (context->iter == context->current_text_end)
1207 /* The name hasn't necessarily ended. Merge with
1208 * partial chunk, leave state unchanged.
1210 add_to_partial (context, context->start, context->iter);
1214 /* The name has ended. Combine it with the partial chunk
1215 * if any; push it on the stack; enter next state.
1217 add_to_partial (context, context->start, context->iter);
1218 push_partial_as_tag (context);
1220 context->state = STATE_BETWEEN_ATTRIBUTES;
1221 context->start = NULL;
1225 case STATE_INSIDE_ATTRIBUTE_NAME:
1226 /* Possible next states: AFTER_ATTRIBUTE_NAME */
1228 advance_to_name_end (context);
1229 add_to_partial (context, context->start, context->iter);
1231 /* read the full name, if we enter the equals sign state
1232 * then add the attribute to the list (without the value),
1233 * otherwise store a partial chunk to be prepended later.
1235 if (context->iter != context->current_text_end)
1236 context->state = STATE_AFTER_ATTRIBUTE_NAME;
1239 case STATE_AFTER_ATTRIBUTE_NAME:
1240 /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1242 skip_spaces (context);
1244 if (context->iter != context->current_text_end)
1246 /* The name has ended. Combine it with the partial chunk
1247 * if any; push it on the stack; enter next state.
1249 if (!name_validate (context, context->partial_chunk->str, error))
1252 add_attribute (context, context->partial_chunk);
1254 context->partial_chunk = NULL;
1255 context->start = NULL;
1257 if (*context->iter == '=')
1259 advance_char (context);
1260 context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1268 G_MARKUP_ERROR_PARSE,
1269 _("Odd character '%s', expected a '=' after "
1270 "attribute name '%s' of element '%s'"),
1271 utf8_str (context->iter, buf),
1272 current_attribute (context),
1273 current_element (context));
1279 case STATE_BETWEEN_ATTRIBUTES:
1280 /* Possible next states: AFTER_CLOSE_ANGLE,
1281 * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1283 skip_spaces (context);
1285 if (context->iter != context->current_text_end)
1287 if (*context->iter == '/')
1289 advance_char (context);
1290 context->state = STATE_AFTER_ELISION_SLASH;
1292 else if (*context->iter == '>')
1294 advance_char (context);
1295 context->state = STATE_AFTER_CLOSE_ANGLE;
1297 else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1299 context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1300 /* start of attribute name */
1301 context->start = context->iter;
1309 G_MARKUP_ERROR_PARSE,
1310 _("Odd character '%s', expected a '>' or '/' "
1311 "character to end the start tag of "
1312 "element '%s', or optionally an attribute; "
1313 "perhaps you used an invalid character in "
1314 "an attribute name"),
1315 utf8_str (context->iter, buf),
1316 current_element (context));
1319 /* If we're done with attributes, invoke
1320 * the start_element callback
1322 if (context->state == STATE_AFTER_ELISION_SLASH ||
1323 context->state == STATE_AFTER_CLOSE_ANGLE)
1324 emit_start_element (context, error);
1328 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1329 /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1331 skip_spaces (context);
1333 if (context->iter != context->current_text_end)
1335 if (*context->iter == '"')
1337 advance_char (context);
1338 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1339 context->start = context->iter;
1341 else if (*context->iter == '\'')
1343 advance_char (context);
1344 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1345 context->start = context->iter;
1353 G_MARKUP_ERROR_PARSE,
1354 _("Odd character '%s', expected an open quote mark "
1355 "after the equals sign when giving value for "
1356 "attribute '%s' of element '%s'"),
1357 utf8_str (context->iter, buf),
1358 current_attribute (context),
1359 current_element (context));
1364 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1365 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1366 /* Possible next states: BETWEEN_ATTRIBUTES */
1370 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ)
1381 if (*context->iter == delim)
1384 while (advance_char (context));
1386 if (context->iter == context->current_text_end)
1388 /* The value hasn't necessarily ended. Merge with
1389 * partial chunk, leave state unchanged.
1391 add_to_partial (context, context->start, context->iter);
1396 /* The value has ended at the quote mark. Combine it
1397 * with the partial chunk if any; set it for the current
1400 add_to_partial (context, context->start, context->iter);
1402 g_assert (context->cur_attr >= 0);
1404 if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1405 (is_ascii || text_validate (context, context->partial_chunk->str,
1406 context->partial_chunk->len, error)))
1408 /* success, advance past quote and set state. */
1409 context->attr_values[context->cur_attr] = context->partial_chunk;
1410 context->partial_chunk = NULL;
1411 advance_char (context);
1412 context->state = STATE_BETWEEN_ATTRIBUTES;
1413 context->start = NULL;
1416 truncate_partial (context);
1420 case STATE_INSIDE_TEXT:
1421 /* Possible next states: AFTER_OPEN_ANGLE */
1424 if (*context->iter == '<')
1427 while (advance_char (context));
1429 /* The text hasn't necessarily ended. Merge with
1430 * partial chunk, leave state unchanged.
1433 add_to_partial (context, context->start, context->iter);
1435 if (context->iter != context->current_text_end)
1439 /* The text has ended at the open angle. Call the text
1442 if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1443 (is_ascii || text_validate (context, context->partial_chunk->str,
1444 context->partial_chunk->len, error)))
1446 GError *tmp_error = NULL;
1448 if (context->parser->text)
1449 (*context->parser->text) (context,
1450 context->partial_chunk->str,
1451 context->partial_chunk->len,
1455 if (tmp_error == NULL)
1457 /* advance past open angle and set state. */
1458 advance_char (context);
1459 context->state = STATE_AFTER_OPEN_ANGLE;
1460 /* could begin a passthrough */
1461 context->start = context->iter;
1464 propagate_error (context, error, tmp_error);
1467 truncate_partial (context);
1471 case STATE_AFTER_CLOSE_TAG_SLASH:
1472 /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1473 if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1475 context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1477 /* start of tag name */
1478 context->start = context->iter;
1486 G_MARKUP_ERROR_PARSE,
1487 _("'%s' is not a valid character following "
1488 "the characters '</'; '%s' may not begin an "
1490 utf8_str (context->iter, buf),
1491 utf8_str (context->iter, buf));
1495 case STATE_INSIDE_CLOSE_TAG_NAME:
1496 /* Possible next state: AFTER_CLOSE_TAG_NAME */
1497 advance_to_name_end (context);
1498 add_to_partial (context, context->start, context->iter);
1500 if (context->iter != context->current_text_end)
1501 context->state = STATE_AFTER_CLOSE_TAG_NAME;
1504 case STATE_AFTER_CLOSE_TAG_NAME:
1505 /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1507 skip_spaces (context);
1509 if (context->iter != context->current_text_end)
1511 GString *close_name;
1513 close_name = context->partial_chunk;
1514 context->partial_chunk = NULL;
1516 if (*context->iter != '>')
1522 G_MARKUP_ERROR_PARSE,
1523 _("'%s' is not a valid character following "
1524 "the close element name '%s'; the allowed "
1525 "character is '>'"),
1526 utf8_str (context->iter, buf),
1529 else if (context->tag_stack == NULL)
1533 G_MARKUP_ERROR_PARSE,
1534 _("Element '%s' was closed, no element "
1535 "is currently open"),
1538 else if (strcmp (close_name->str, current_element (context)) != 0)
1542 G_MARKUP_ERROR_PARSE,
1543 _("Element '%s' was closed, but the currently "
1544 "open element is '%s'"),
1546 current_element (context));
1551 advance_char (context);
1552 context->state = STATE_AFTER_CLOSE_ANGLE;
1553 context->start = NULL;
1555 possibly_finish_subparser (context);
1557 /* call the end_element callback */
1559 if (context->parser->end_element)
1560 (* context->parser->end_element) (context,
1565 ensure_no_outstanding_subparser (context);
1569 propagate_error (context, error, tmp_error);
1571 context->partial_chunk = close_name;
1572 truncate_partial (context);
1576 case STATE_INSIDE_PASSTHROUGH:
1577 /* Possible next state: AFTER_CLOSE_ANGLE */
1580 if (*context->iter == '<')
1582 if (*context->iter == '>')
1588 add_to_partial (context, context->start, context->iter);
1589 context->start = context->iter;
1591 str = context->partial_chunk->str;
1592 len = context->partial_chunk->len;
1594 if (str[1] == '?' && str[len - 1] == '?')
1596 if (strncmp (str, "<!--", 4) == 0 &&
1597 strcmp (str + len - 2, "--") == 0)
1599 if (strncmp (str, "<![CDATA[", 9) == 0 &&
1600 strcmp (str + len - 2, "]]") == 0)
1602 if (strncmp (str, "<!DOCTYPE", 9) == 0 &&
1603 context->balance == 0)
1607 while (advance_char (context));
1609 if (context->iter == context->current_text_end)
1611 /* The passthrough hasn't necessarily ended. Merge with
1612 * partial chunk, leave state unchanged.
1614 add_to_partial (context, context->start, context->iter);
1618 /* The passthrough has ended at the close angle. Combine
1619 * it with the partial chunk if any. Call the passthrough
1620 * callback. Note that the open/close angles are
1621 * included in the text of the passthrough.
1623 GError *tmp_error = NULL;
1625 advance_char (context); /* advance past close angle */
1626 add_to_partial (context, context->start, context->iter);
1628 if (context->flags & G_MARKUP_TREAT_CDATA_AS_TEXT &&
1629 strncmp (context->partial_chunk->str, "<![CDATA[", 9) == 0)
1631 if (context->parser->text &&
1632 text_validate (context,
1633 context->partial_chunk->str + 9,
1634 context->partial_chunk->len - 12,
1636 (*context->parser->text) (context,
1637 context->partial_chunk->str + 9,
1638 context->partial_chunk->len - 12,
1642 else if (context->parser->passthrough &&
1643 text_validate (context,
1644 context->partial_chunk->str,
1645 context->partial_chunk->len,
1647 (*context->parser->passthrough) (context,
1648 context->partial_chunk->str,
1649 context->partial_chunk->len,
1653 truncate_partial (context);
1655 if (tmp_error == NULL)
1657 context->state = STATE_AFTER_CLOSE_ANGLE;
1658 context->start = context->iter; /* could begin text */
1661 propagate_error (context, error, tmp_error);
1670 g_assert_not_reached ();
1676 context->parsing = FALSE;
1678 return context->state != STATE_ERROR;
1682 * g_markup_parse_context_end_parse:
1683 * @context: a #GMarkupParseContext
1684 * @error: return location for a #GError
1686 * Signals to the #GMarkupParseContext that all data has been
1687 * fed into the parse context with g_markup_parse_context_parse().
1689 * This function reports an error if the document isn't complete,
1690 * for example if elements are still open.
1692 * Return value: %TRUE on success, %FALSE if an error was set
1695 g_markup_parse_context_end_parse (GMarkupParseContext *context,
1698 g_return_val_if_fail (context != NULL, FALSE);
1699 g_return_val_if_fail (!context->parsing, FALSE);
1700 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1702 if (context->partial_chunk != NULL)
1704 g_string_free (context->partial_chunk, TRUE);
1705 context->partial_chunk = NULL;
1708 if (context->document_empty)
1710 set_error_literal (context, error, G_MARKUP_ERROR_EMPTY,
1711 _("Document was empty or contained only whitespace"));
1715 context->parsing = TRUE;
1717 switch (context->state)
1723 case STATE_AFTER_OPEN_ANGLE:
1724 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1725 _("Document ended unexpectedly just after an open angle bracket '<'"));
1728 case STATE_AFTER_CLOSE_ANGLE:
1729 if (context->tag_stack != NULL)
1731 /* Error message the same as for INSIDE_TEXT */
1732 set_error (context, error, G_MARKUP_ERROR_PARSE,
1733 _("Document ended unexpectedly with elements still open - "
1734 "'%s' was the last element opened"),
1735 current_element (context));
1739 case STATE_AFTER_ELISION_SLASH:
1740 set_error (context, error, G_MARKUP_ERROR_PARSE,
1741 _("Document ended unexpectedly, expected to see a close angle "
1742 "bracket ending the tag <%s/>"), current_element (context));
1745 case STATE_INSIDE_OPEN_TAG_NAME:
1746 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1747 _("Document ended unexpectedly inside an element name"));
1750 case STATE_INSIDE_ATTRIBUTE_NAME:
1751 case STATE_AFTER_ATTRIBUTE_NAME:
1752 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1753 _("Document ended unexpectedly inside an attribute name"));
1756 case STATE_BETWEEN_ATTRIBUTES:
1757 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1758 _("Document ended unexpectedly inside an element-opening "
1762 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1763 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1764 _("Document ended unexpectedly after the equals sign "
1765 "following an attribute name; no attribute value"));
1768 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1769 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1770 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1771 _("Document ended unexpectedly while inside an attribute "
1775 case STATE_INSIDE_TEXT:
1776 g_assert (context->tag_stack != NULL);
1777 set_error (context, error, G_MARKUP_ERROR_PARSE,
1778 _("Document ended unexpectedly with elements still open - "
1779 "'%s' was the last element opened"),
1780 current_element (context));
1783 case STATE_AFTER_CLOSE_TAG_SLASH:
1784 case STATE_INSIDE_CLOSE_TAG_NAME:
1785 case STATE_AFTER_CLOSE_TAG_NAME:
1786 set_error (context, error, G_MARKUP_ERROR_PARSE,
1787 _("Document ended unexpectedly inside the close tag for "
1788 "element '%s'"), current_element (context));
1791 case STATE_INSIDE_PASSTHROUGH:
1792 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1793 _("Document ended unexpectedly inside a comment or "
1794 "processing instruction"));
1799 g_assert_not_reached ();
1803 context->parsing = FALSE;
1805 return context->state != STATE_ERROR;
1809 * g_markup_parse_context_get_element:
1810 * @context: a #GMarkupParseContext
1812 * Retrieves the name of the currently open element.
1814 * If called from the start_element or end_element handlers this will
1815 * give the element_name as passed to those functions. For the parent
1816 * elements, see g_markup_parse_context_get_element_stack().
1818 * Returns: the name of the currently open element, or %NULL
1823 g_markup_parse_context_get_element (GMarkupParseContext *context)
1825 g_return_val_if_fail (context != NULL, NULL);
1827 if (context->tag_stack == NULL)
1830 return current_element (context);
1834 * g_markup_parse_context_get_element_stack:
1835 * @context: a #GMarkupParseContext
1837 * Retrieves the element stack from the internal state of the parser.
1839 * The returned #GSList is a list of strings where the first item is
1840 * the currently open tag (as would be returned by
1841 * g_markup_parse_context_get_element()) and the next item is its
1844 * This function is intended to be used in the start_element and
1845 * end_element handlers where g_markup_parse_context_get_element()
1846 * would merely return the name of the element that is being
1849 * Returns: the element stack, which must not be modified
1854 g_markup_parse_context_get_element_stack (GMarkupParseContext *context)
1856 g_return_val_if_fail (context != NULL, NULL);
1857 return context->tag_stack;
1861 * g_markup_parse_context_get_position:
1862 * @context: a #GMarkupParseContext
1863 * @line_number: (allow-none): return location for a line number, or %NULL
1864 * @char_number: (allow-none): return location for a char-on-line number, or %NULL
1866 * Retrieves the current line number and the number of the character on
1867 * that line. Intended for use in error messages; there are no strict
1868 * semantics for what constitutes the "current" line number other than
1869 * "the best number we could come up with for error messages."
1872 g_markup_parse_context_get_position (GMarkupParseContext *context,
1876 g_return_if_fail (context != NULL);
1879 *line_number = context->line_number;
1882 *char_number = context->char_number;
1886 * g_markup_parse_context_get_user_data:
1887 * @context: a #GMarkupParseContext
1889 * Returns the user_data associated with @context.
1891 * This will either be the user_data that was provided to
1892 * g_markup_parse_context_new() or to the most recent call
1893 * of g_markup_parse_context_push().
1895 * Returns: the provided user_data. The returned data belongs to
1896 * the markup context and will be freed when g_markup_context_free()
1902 g_markup_parse_context_get_user_data (GMarkupParseContext *context)
1904 return context->user_data;
1908 * g_markup_parse_context_push:
1909 * @context: a #GMarkupParseContext
1910 * @parser: a #GMarkupParser
1911 * @user_data: user data to pass to #GMarkupParser functions
1913 * Temporarily redirects markup data to a sub-parser.
1915 * This function may only be called from the start_element handler of
1916 * a #GMarkupParser. It must be matched with a corresponding call to
1917 * g_markup_parse_context_pop() in the matching end_element handler
1918 * (except in the case that the parser aborts due to an error).
1920 * All tags, text and other data between the matching tags is
1921 * redirected to the subparser given by @parser. @user_data is used
1922 * as the user_data for that parser. @user_data is also passed to the
1923 * error callback in the event that an error occurs. This includes
1924 * errors that occur in subparsers of the subparser.
1926 * The end tag matching the start tag for which this call was made is
1927 * handled by the previous parser (which is given its own user_data)
1928 * which is why g_markup_parse_context_pop() is provided to allow "one
1929 * last access" to the @user_data provided to this function. In the
1930 * case of error, the @user_data provided here is passed directly to
1931 * the error callback of the subparser and g_markup_parse_context()
1932 * should not be called. In either case, if @user_data was allocated
1933 * then it ought to be freed from both of these locations.
1935 * This function is not intended to be directly called by users
1936 * interested in invoking subparsers. Instead, it is intended to be
1937 * used by the subparsers themselves to implement a higher-level
1940 * As an example, see the following implementation of a simple
1941 * parser that counts the number of tags encountered.
1950 * counter_start_element (GMarkupParseContext *context,
1951 * const gchar *element_name,
1952 * const gchar **attribute_names,
1953 * const gchar **attribute_values,
1954 * gpointer user_data,
1957 * CounterData *data = user_data;
1959 * data->tag_count++;
1963 * counter_error (GMarkupParseContext *context,
1965 * gpointer user_data)
1967 * CounterData *data = user_data;
1969 * g_slice_free (CounterData, data);
1972 * static GMarkupParser counter_subparser =
1974 * counter_start_element,
1982 * In order to allow this parser to be easily used as a subparser, the
1983 * following interface is provided:
1987 * start_counting (GMarkupParseContext *context)
1989 * CounterData *data = g_slice_new (CounterData);
1991 * data->tag_count = 0;
1992 * g_markup_parse_context_push (context, &counter_subparser, data);
1996 * end_counting (GMarkupParseContext *context)
1998 * CounterData *data = g_markup_parse_context_pop (context);
2001 * result = data->tag_count;
2002 * g_slice_free (CounterData, data);
2008 * The subparser would then be used as follows:
2011 * static void start_element (context, element_name, ...)
2013 * if (strcmp (element_name, "count-these") == 0)
2014 * start_counting (context);
2016 * /* else, handle other tags... */
2019 * static void end_element (context, element_name, ...)
2021 * if (strcmp (element_name, "count-these") == 0)
2022 * g_print ("Counted %d tags\n", end_counting (context));
2024 * /* else, handle other tags... */
2031 g_markup_parse_context_push (GMarkupParseContext *context,
2032 const GMarkupParser *parser,
2035 GMarkupRecursionTracker *tracker;
2037 tracker = g_slice_new (GMarkupRecursionTracker);
2038 tracker->prev_element = context->subparser_element;
2039 tracker->prev_parser = context->parser;
2040 tracker->prev_user_data = context->user_data;
2042 context->subparser_element = current_element (context);
2043 context->parser = parser;
2044 context->user_data = user_data;
2046 context->subparser_stack = g_slist_prepend (context->subparser_stack,
2051 * g_markup_parse_context_pop:
2052 * @context: a #GMarkupParseContext
2054 * Completes the process of a temporary sub-parser redirection.
2056 * This function exists to collect the user_data allocated by a
2057 * matching call to g_markup_parse_context_push(). It must be called
2058 * in the end_element handler corresponding to the start_element
2059 * handler during which g_markup_parse_context_push() was called.
2060 * You must not call this function from the error callback -- the
2061 * @user_data is provided directly to the callback in that case.
2063 * This function is not intended to be directly called by users
2064 * interested in invoking subparsers. Instead, it is intended to
2065 * be used by the subparsers themselves to implement a higher-level
2068 * Returns: the user data passed to g_markup_parse_context_push()
2073 g_markup_parse_context_pop (GMarkupParseContext *context)
2077 if (!context->awaiting_pop)
2078 possibly_finish_subparser (context);
2080 g_assert (context->awaiting_pop);
2082 context->awaiting_pop = FALSE;
2084 /* valgrind friendliness */
2085 user_data = context->held_user_data;
2086 context->held_user_data = NULL;
2092 append_escaped_text (GString *str,
2101 end = text + length;
2106 next = g_utf8_next_char (p);
2111 g_string_append (str, "&");
2115 g_string_append (str, "<");
2119 g_string_append (str, ">");
2123 g_string_append (str, "'");
2127 g_string_append (str, """);
2131 c = g_utf8_get_char (p);
2132 if ((0x1 <= c && c <= 0x8) ||
2133 (0xb <= c && c <= 0xc) ||
2134 (0xe <= c && c <= 0x1f) ||
2135 (0x7f <= c && c <= 0x84) ||
2136 (0x86 <= c && c <= 0x9f))
2137 g_string_append_printf (str, "&#x%x;", c);
2139 g_string_append_len (str, p, next - p);
2148 * g_markup_escape_text:
2149 * @text: some valid UTF-8 text
2150 * @length: length of @text in bytes, or -1 if the text is nul-terminated
2152 * Escapes text so that the markup parser will parse it verbatim.
2153 * Less than, greater than, ampersand, etc. are replaced with the
2154 * corresponding entities. This function would typically be used
2155 * when writing out a file to be parsed with the markup parser.
2157 * Note that this function doesn't protect whitespace and line endings
2158 * from being processed according to the XML rules for normalization
2159 * of line endings and attribute values.
2161 * Note also that this function will produce character references in
2162 * the range of &#x1; ... &#x1f; for all control sequences
2163 * except for tabstop, newline and carriage return. The character
2164 * references in this range are not valid XML 1.0, but they are
2165 * valid XML 1.1 and will be accepted by the GMarkup parser.
2167 * Return value: a newly allocated string with the escaped text
2170 g_markup_escape_text (const gchar *text,
2175 g_return_val_if_fail (text != NULL, NULL);
2178 length = strlen (text);
2180 /* prealloc at least as long as original text */
2181 str = g_string_sized_new (length);
2182 append_escaped_text (str, text, length);
2184 return g_string_free (str, FALSE);
2189 * @format: a printf-style format string
2190 * @after: location to store a pointer to the character after
2191 * the returned conversion. On a %NULL return, returns the
2192 * pointer to the trailing NUL in the string
2194 * Find the next conversion in a printf-style format string.
2195 * Partially based on code from printf-parser.c,
2196 * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
2198 * Return value: pointer to the next conversion in @format,
2199 * or %NULL, if none.
2202 find_conversion (const char *format,
2205 const char *start = format;
2208 while (*start != '\0' && *start != '%')
2225 /* Test for positional argument. */
2226 if (*cp >= '0' && *cp <= '9')
2230 for (np = cp; *np >= '0' && *np <= '9'; np++)
2236 /* Skip the flags. */
2250 /* Skip the field width. */
2255 /* Test for positional argument. */
2256 if (*cp >= '0' && *cp <= '9')
2260 for (np = cp; *np >= '0' && *np <= '9'; np++)
2268 for (; *cp >= '0' && *cp <= '9'; cp++)
2272 /* Skip the precision. */
2278 /* Test for positional argument. */
2279 if (*cp >= '0' && *cp <= '9')
2283 for (np = cp; *np >= '0' && *np <= '9'; np++)
2291 for (; *cp >= '0' && *cp <= '9'; cp++)
2296 /* Skip argument type/size specifiers. */
2297 while (*cp == 'h' ||
2306 /* Skip the conversion character. */
2314 * g_markup_vprintf_escaped:
2315 * @format: printf() style format string
2316 * @args: variable argument list, similar to vprintf()
2318 * Formats the data in @args according to @format, escaping
2319 * all string and character arguments in the fashion
2320 * of g_markup_escape_text(). See g_markup_printf_escaped().
2322 * Return value: newly allocated result from formatting
2323 * operation. Free with g_free().
2328 g_markup_vprintf_escaped (const gchar *format,
2333 GString *result = NULL;
2334 gchar *output1 = NULL;
2335 gchar *output2 = NULL;
2336 const char *p, *op1, *op2;
2339 /* The technique here, is that we make two format strings that
2340 * have the identical conversions in the identical order to the
2341 * original strings, but differ in the text in-between. We
2342 * then use the normal g_strdup_vprintf() to format the arguments
2343 * with the two new format strings. By comparing the results,
2344 * we can figure out what segments of the output come from
2345 * the the original format string, and what from the arguments,
2346 * and thus know what portions of the string to escape.
2348 * For instance, for:
2350 * g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2352 * We form the two format strings "%sX%dX" and %sY%sY". The results
2353 * of formatting with those two strings are
2355 * "%sX%dX" => "Susan & FredX5X"
2356 * "%sY%dY" => "Susan & FredY5Y"
2358 * To find the span of the first argument, we find the first position
2359 * where the two arguments differ, which tells us that the first
2360 * argument formatted to "Susan & Fred". We then escape that
2361 * to "Susan & Fred" and join up with the intermediate portions
2362 * of the format string and the second argument to get
2363 * "Susan & Fred ate 5 apples".
2366 /* Create the two modified format strings
2368 format1 = g_string_new (NULL);
2369 format2 = g_string_new (NULL);
2374 const char *conv = find_conversion (p, &after);
2378 g_string_append_len (format1, conv, after - conv);
2379 g_string_append_c (format1, 'X');
2380 g_string_append_len (format2, conv, after - conv);
2381 g_string_append_c (format2, 'Y');
2386 /* Use them to format the arguments
2388 G_VA_COPY (args2, args);
2390 output1 = g_strdup_vprintf (format1->str, args);
2397 output2 = g_strdup_vprintf (format2->str, args2);
2402 result = g_string_new (NULL);
2404 /* Iterate through the original format string again,
2405 * copying the non-conversion portions and the escaped
2406 * converted arguments to the output string.
2414 const char *output_start;
2415 const char *conv = find_conversion (p, &after);
2418 if (!conv) /* The end, after points to the trailing \0 */
2420 g_string_append_len (result, p, after - p);
2424 g_string_append_len (result, p, conv - p);
2426 while (*op1 == *op2)
2432 escaped = g_markup_escape_text (output_start, op1 - output_start);
2433 g_string_append (result, escaped);
2442 g_string_free (format1, TRUE);
2443 g_string_free (format2, TRUE);
2448 return g_string_free (result, FALSE);
2454 * g_markup_printf_escaped:
2455 * @format: printf() style format string
2456 * @Varargs: the arguments to insert in the format string
2458 * Formats arguments according to @format, escaping
2459 * all string and character arguments in the fashion
2460 * of g_markup_escape_text(). This is useful when you
2461 * want to insert literal strings into XML-style markup
2462 * output, without having to worry that the strings
2463 * might themselves contain markup.
2466 * const char *store = "Fortnum & Mason";
2467 * const char *item = "Tea";
2470 * output = g_markup_printf_escaped ("<purchase>"
2471 * "<store>%s</store>"
2472 * "<item>%s</item>"
2473 * "</purchase>",
2477 * Return value: newly allocated result from formatting
2478 * operation. Free with g_free().
2483 g_markup_printf_escaped (const gchar *format, ...)
2488 va_start (args, format);
2489 result = g_markup_vprintf_escaped (format, args);
2496 g_markup_parse_boolean (const char *string,
2499 char const * const falses[] = { "false", "f", "no", "n", "0" };
2500 char const * const trues[] = { "true", "t", "yes", "y", "1" };
2503 for (i = 0; i < G_N_ELEMENTS (falses); i++)
2505 if (g_ascii_strcasecmp (string, falses[i]) == 0)
2514 for (i = 0; i < G_N_ELEMENTS (trues); i++)
2516 if (g_ascii_strcasecmp (string, trues[i]) == 0)
2529 * GMarkupCollectType:
2530 * @G_MARKUP_COLLECT_INVALID: used to terminate the list of attributes
2532 * @G_MARKUP_COLLECT_STRING: collect the string pointer directly from
2533 * the attribute_values[] array. Expects a parameter of type (const
2534 * char **). If %G_MARKUP_COLLECT_OPTIONAL is specified and the
2535 * attribute isn't present then the pointer will be set to %NULL
2536 * @G_MARKUP_COLLECT_STRDUP: as with %G_MARKUP_COLLECT_STRING, but
2537 * expects a parameter of type (char **) and g_strdup()s the
2538 * returned pointer. The pointer must be freed with g_free()
2539 * @G_MARKUP_COLLECT_BOOLEAN: expects a parameter of type (gboolean *)
2540 * and parses the attribute value as a boolean. Sets %FALSE if the
2541 * attribute isn't present. Valid boolean values consist of
2542 * (case-insensitive) "false", "f", "no", "n", "0" and "true", "t",
2544 * @G_MARKUP_COLLECT_TRISTATE: as with %G_MARKUP_COLLECT_BOOLEAN, but
2545 * in the case of a missing attribute a value is set that compares
2546 * equal to neither %FALSE nor %TRUE G_MARKUP_COLLECT_OPTIONAL is
2548 * @G_MARKUP_COLLECT_OPTIONAL: can be bitwise ORed with the other fields.
2549 * If present, allows the attribute not to appear. A default value
2550 * is set depending on what value type is used
2552 * A mixed enumerated type and flags field. You must specify one type
2553 * (string, strdup, boolean, tristate). Additionally, you may optionally
2554 * bitwise OR the type with the flag %G_MARKUP_COLLECT_OPTIONAL.
2556 * It is likely that this enum will be extended in the future to
2557 * support other types.
2561 * g_markup_collect_attributes:
2562 * @element_name: the current tag name
2563 * @attribute_names: the attribute names
2564 * @attribute_values: the attribute values
2565 * @error: a pointer to a #GError or %NULL
2566 * @first_type: the #GMarkupCollectType of the first attribute
2567 * @first_attr: the name of the first attribute
2568 * @...: a pointer to the storage location of the first attribute
2569 * (or %NULL), followed by more types names and pointers, ending
2570 * with %G_MARKUP_COLLECT_INVALID
2572 * Collects the attributes of the element from the data passed to the
2573 * #GMarkupParser start_element function, dealing with common error
2574 * conditions and supporting boolean values.
2576 * This utility function is not required to write a parser but can save
2579 * The @element_name, @attribute_names, @attribute_values and @error
2580 * parameters passed to the start_element callback should be passed
2581 * unmodified to this function.
2583 * Following these arguments is a list of "supported" attributes to collect.
2584 * It is an error to specify multiple attributes with the same name. If any
2585 * attribute not in the list appears in the @attribute_names array then an
2586 * unknown attribute error will result.
2588 * The #GMarkupCollectType field allows specifying the type of collection
2589 * to perform and if a given attribute must appear or is optional.
2591 * The attribute name is simply the name of the attribute to collect.
2593 * The pointer should be of the appropriate type (see the descriptions
2594 * under #GMarkupCollectType) and may be %NULL in case a particular
2595 * attribute is to be allowed but ignored.
2597 * This function deals with issuing errors for missing attributes
2598 * (of type %G_MARKUP_ERROR_MISSING_ATTRIBUTE), unknown attributes
2599 * (of type %G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE) and duplicate
2600 * attributes (of type %G_MARKUP_ERROR_INVALID_CONTENT) as well
2601 * as parse errors for boolean-valued attributes (again of type
2602 * %G_MARKUP_ERROR_INVALID_CONTENT). In all of these cases %FALSE
2603 * will be returned and @error will be set as appropriate.
2605 * Return value: %TRUE if successful
2610 g_markup_collect_attributes (const gchar *element_name,
2611 const gchar **attribute_names,
2612 const gchar **attribute_values,
2614 GMarkupCollectType first_type,
2615 const gchar *first_attr,
2618 GMarkupCollectType type;
2630 va_start (ap, first_attr);
2631 while (type != G_MARKUP_COLLECT_INVALID)
2636 mandatory = !(type & G_MARKUP_COLLECT_OPTIONAL);
2637 type &= (G_MARKUP_COLLECT_OPTIONAL - 1);
2639 /* tristate records a value != TRUE and != FALSE
2640 * for the case where the attribute is missing
2642 if (type == G_MARKUP_COLLECT_TRISTATE)
2645 for (i = 0; attribute_names[i]; i++)
2646 if (i >= 40 || !(collected & (G_GUINT64_CONSTANT(1) << i)))
2647 if (!strcmp (attribute_names[i], attr))
2650 /* ISO C99 only promises that the user can pass up to 127 arguments.
2651 * Subtracting the first 4 arguments plus the final NULL and dividing
2652 * by 3 arguments per collected attribute, we are left with a maximum
2653 * number of supported attributes of (127 - 5) / 3 = 40.
2655 * In reality, nobody is ever going to call us with anywhere close to
2656 * 40 attributes to collect, so it is safe to assume that if i > 40
2657 * then the user has given some invalid or repeated arguments. These
2658 * problems will be caught and reported at the end of the function.
2660 * We know at this point that we have an error, but we don't know
2661 * what error it is, so just continue...
2664 collected |= (G_GUINT64_CONSTANT(1) << i);
2666 value = attribute_values[i];
2668 if (value == NULL && mandatory)
2670 g_set_error (error, G_MARKUP_ERROR,
2671 G_MARKUP_ERROR_MISSING_ATTRIBUTE,
2672 "element '%s' requires attribute '%s'",
2673 element_name, attr);
2681 case G_MARKUP_COLLECT_STRING:
2683 const char **str_ptr;
2685 str_ptr = va_arg (ap, const char **);
2687 if (str_ptr != NULL)
2692 case G_MARKUP_COLLECT_STRDUP:
2696 str_ptr = va_arg (ap, char **);
2698 if (str_ptr != NULL)
2699 *str_ptr = g_strdup (value);
2703 case G_MARKUP_COLLECT_BOOLEAN:
2704 case G_MARKUP_COLLECT_TRISTATE:
2709 bool_ptr = va_arg (ap, gboolean *);
2711 if (bool_ptr != NULL)
2713 if (type == G_MARKUP_COLLECT_TRISTATE)
2714 /* constructivists rejoice!
2715 * neither false nor true...
2719 else /* G_MARKUP_COLLECT_BOOLEAN */
2725 if (!g_markup_parse_boolean (value, va_arg (ap, gboolean *)))
2727 g_set_error (error, G_MARKUP_ERROR,
2728 G_MARKUP_ERROR_INVALID_CONTENT,
2729 "element '%s', attribute '%s', value '%s' "
2730 "cannot be parsed as a boolean value",
2731 element_name, attr, value);
2741 g_assert_not_reached ();
2744 type = va_arg (ap, GMarkupCollectType);
2745 attr = va_arg (ap, const char *);
2750 /* ensure we collected all the arguments */
2751 for (i = 0; attribute_names[i]; i++)
2752 if ((collected & (G_GUINT64_CONSTANT(1) << i)) == 0)
2754 /* attribute not collected: could be caused by two things.
2756 * 1) it doesn't exist in our list of attributes
2757 * 2) it existed but was matched by a duplicate attribute earlier
2763 for (j = 0; j < i; j++)
2764 if (strcmp (attribute_names[i], attribute_names[j]) == 0)
2768 /* j is now the first occurrence of attribute_names[i] */
2770 g_set_error (error, G_MARKUP_ERROR,
2771 G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
2772 "attribute '%s' invalid for element '%s'",
2773 attribute_names[i], element_name);
2775 g_set_error (error, G_MARKUP_ERROR,
2776 G_MARKUP_ERROR_INVALID_CONTENT,
2777 "attribute '%s' given multiple times for element '%s'",
2778 attribute_names[i], element_name);
2786 /* replay the above to free allocations */
2790 va_start (ap, first_attr);
2791 while (type != G_MARKUP_COLLECT_INVALID)
2795 ptr = va_arg (ap, gpointer);
2799 switch (type & (G_MARKUP_COLLECT_OPTIONAL - 1))
2801 case G_MARKUP_COLLECT_STRDUP:
2803 g_free (*(char **) ptr);
2805 case G_MARKUP_COLLECT_STRING:
2806 *(char **) ptr = NULL;
2809 case G_MARKUP_COLLECT_BOOLEAN:
2810 *(gboolean *) ptr = FALSE;
2813 case G_MARKUP_COLLECT_TRISTATE:
2814 *(gboolean *) ptr = -1;
2819 type = va_arg (ap, GMarkupCollectType);
2820 attr = va_arg (ap, const char *);