1 /* gmarkup.c - Simple XML-like parser
3 * Copyright 2000, 2003 Red Hat, Inc.
4 * Copyright 2007, 2008 Ryan Lortie <desrt@desrt.ca>
6 * SPDX-License-Identifier: LGPL-2.1-or-later
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this library; if not, see <http://www.gnu.org/licenses/>.
35 #include "gstrfuncs.h"
37 #include "gtestutils.h"
43 * @Title: Simple XML Subset Parser
44 * @Short_description: parses a subset of XML
45 * @See_also: [XML Specification](http://www.w3.org/TR/REC-xml/)
47 * The "GMarkup" parser is intended to parse a simple markup format
48 * that's a subset of XML. This is a small, efficient, easy-to-use
49 * parser. It should not be used if you expect to interoperate with
50 * other applications generating full-scale XML, and must not be used if you
51 * expect to parse untrusted input. However, it's very
52 * useful for application data files, config files, etc. where you
53 * know your application will be the only one writing the file.
54 * Full-scale XML parsers should be able to parse the subset used by
55 * GMarkup, so you can easily migrate to full-scale XML at a later
56 * time if the need arises.
58 * GMarkup is not guaranteed to signal an error on all invalid XML;
59 * the parser may accept documents that an XML parser would not.
60 * However, XML documents which are not well-formed (which is a
61 * weaker condition than being valid. See the
62 * [XML specification](http://www.w3.org/TR/REC-xml/)
63 * for definitions of these terms.) are not considered valid GMarkup
66 * Simplifications to XML include:
68 * - Only UTF-8 encoding is allowed
70 * - No user-defined entities
72 * - Processing instructions, comments and the doctype declaration
73 * are "passed through" but are not interpreted in any way
75 * - No DTD or validation
77 * The markup format does support:
83 * - 5 standard entities: & < > " '
85 * - Character references
87 * - Sections marked as CDATA
90 G_DEFINE_QUARK (g-markup-error-quark, g_markup_error)
95 STATE_AFTER_OPEN_ANGLE,
96 STATE_AFTER_CLOSE_ANGLE,
97 STATE_AFTER_ELISION_SLASH, /* the slash that obviates need for end element */
98 STATE_INSIDE_OPEN_TAG_NAME,
99 STATE_INSIDE_ATTRIBUTE_NAME,
100 STATE_AFTER_ATTRIBUTE_NAME,
101 STATE_BETWEEN_ATTRIBUTES,
102 STATE_AFTER_ATTRIBUTE_EQUALS_SIGN,
103 STATE_INSIDE_ATTRIBUTE_VALUE_SQ,
104 STATE_INSIDE_ATTRIBUTE_VALUE_DQ,
106 STATE_AFTER_CLOSE_TAG_SLASH,
107 STATE_INSIDE_CLOSE_TAG_NAME,
108 STATE_AFTER_CLOSE_TAG_NAME,
109 STATE_INSIDE_PASSTHROUGH,
115 const char *prev_element;
116 const GMarkupParser *prev_parser;
117 gpointer prev_user_data;
118 } GMarkupRecursionTracker;
120 struct _GMarkupParseContext
122 const GMarkupParser *parser;
124 gint ref_count; /* (atomic) */
126 GMarkupParseFlags flags;
131 GMarkupParseState state;
134 GDestroyNotify dnotify;
136 /* A piece of character data or an element that
137 * hasn't "ended" yet so we haven't yet called
138 * the callback for it.
140 GString *partial_chunk;
141 GSList *spare_chunks;
144 GSList *tag_stack_gstr;
145 GSList *spare_list_nodes;
147 GString **attr_names;
148 GString **attr_values;
152 const gchar *current_text;
153 gssize current_text_len;
154 const gchar *current_text_end;
156 /* used to save the start of the last interesting thingy */
161 guint document_empty : 1;
163 guint awaiting_pop : 1;
166 /* subparser support */
167 GSList *subparser_stack; /* (GMarkupRecursionTracker *) */
168 const char *subparser_element;
169 gpointer held_user_data;
173 * Helpers to reduce our allocation overhead, we have
174 * a well defined allocation lifecycle.
177 get_list_node (GMarkupParseContext *context, gpointer data)
180 if (context->spare_list_nodes != NULL)
182 node = context->spare_list_nodes;
183 context->spare_list_nodes = g_slist_remove_link (context->spare_list_nodes, node);
186 node = g_slist_alloc();
192 free_list_node (GMarkupParseContext *context, GSList *node)
195 context->spare_list_nodes = g_slist_concat (node, context->spare_list_nodes);
199 string_blank (GString *string)
201 string->str[0] = '\0';
206 * g_markup_parse_context_new:
207 * @parser: a #GMarkupParser
208 * @flags: one or more #GMarkupParseFlags
209 * @user_data: user data to pass to #GMarkupParser functions
210 * @user_data_dnotify: user data destroy notifier called when
211 * the parse context is freed
213 * Creates a new parse context. A parse context is used to parse
214 * marked-up documents. You can feed any number of documents into
215 * a context, as long as no errors occur; once an error occurs,
216 * the parse context can't continue to parse text (you have to
217 * free it and create a new parse context).
219 * Returns: a new #GMarkupParseContext
221 GMarkupParseContext *
222 g_markup_parse_context_new (const GMarkupParser *parser,
223 GMarkupParseFlags flags,
225 GDestroyNotify user_data_dnotify)
227 GMarkupParseContext *context;
229 g_return_val_if_fail (parser != NULL, NULL);
231 context = g_new (GMarkupParseContext, 1);
233 context->ref_count = 1;
234 context->parser = parser;
235 context->flags = flags;
236 context->user_data = user_data;
237 context->dnotify = user_data_dnotify;
239 context->line_number = 1;
240 context->char_number = 1;
242 context->partial_chunk = NULL;
243 context->spare_chunks = NULL;
244 context->spare_list_nodes = NULL;
246 context->state = STATE_START;
247 context->tag_stack = NULL;
248 context->tag_stack_gstr = NULL;
249 context->attr_names = NULL;
250 context->attr_values = NULL;
251 context->cur_attr = -1;
252 context->alloc_attrs = 0;
254 context->current_text = NULL;
255 context->current_text_len = -1;
256 context->current_text_end = NULL;
258 context->start = NULL;
259 context->iter = NULL;
261 context->document_empty = TRUE;
262 context->parsing = FALSE;
264 context->awaiting_pop = FALSE;
265 context->subparser_stack = NULL;
266 context->subparser_element = NULL;
268 /* this is only looked at if awaiting_pop = TRUE. initialise anyway. */
269 context->held_user_data = NULL;
271 context->balance = 0;
277 * g_markup_parse_context_ref:
278 * @context: a #GMarkupParseContext
280 * Increases the reference count of @context.
282 * Returns: the same @context
286 GMarkupParseContext *
287 g_markup_parse_context_ref (GMarkupParseContext *context)
289 g_return_val_if_fail (context != NULL, NULL);
290 g_return_val_if_fail (context->ref_count > 0, NULL);
292 g_atomic_int_inc (&context->ref_count);
298 * g_markup_parse_context_unref:
299 * @context: a #GMarkupParseContext
301 * Decreases the reference count of @context. When its reference count
302 * drops to 0, it is freed.
307 g_markup_parse_context_unref (GMarkupParseContext *context)
309 g_return_if_fail (context != NULL);
310 g_return_if_fail (context->ref_count > 0);
312 if (g_atomic_int_dec_and_test (&context->ref_count))
313 g_markup_parse_context_free (context);
317 string_full_free (gpointer ptr)
319 g_string_free (ptr, TRUE);
322 static void clear_attributes (GMarkupParseContext *context);
325 * g_markup_parse_context_free:
326 * @context: a #GMarkupParseContext
328 * Frees a #GMarkupParseContext.
330 * This function can't be called from inside one of the
331 * #GMarkupParser functions or while a subparser is pushed.
334 g_markup_parse_context_free (GMarkupParseContext *context)
336 g_return_if_fail (context != NULL);
337 g_return_if_fail (!context->parsing);
338 g_return_if_fail (!context->subparser_stack);
339 g_return_if_fail (!context->awaiting_pop);
341 if (context->dnotify)
342 (* context->dnotify) (context->user_data);
344 clear_attributes (context);
345 g_free (context->attr_names);
346 g_free (context->attr_values);
348 g_slist_free_full (context->tag_stack_gstr, string_full_free);
349 g_slist_free (context->tag_stack);
351 g_slist_free_full (context->spare_chunks, string_full_free);
352 g_slist_free (context->spare_list_nodes);
354 if (context->partial_chunk)
355 g_string_free (context->partial_chunk, TRUE);
360 static void pop_subparser_stack (GMarkupParseContext *context);
363 mark_error (GMarkupParseContext *context,
366 context->state = STATE_ERROR;
368 if (context->parser->error)
369 (*context->parser->error) (context, error, context->user_data);
371 /* report the error all the way up to free all the user-data */
372 while (context->subparser_stack)
374 pop_subparser_stack (context);
375 context->awaiting_pop = FALSE; /* already been freed */
377 if (context->parser->error)
378 (*context->parser->error) (context, error, context->user_data);
383 set_error (GMarkupParseContext *context,
387 ...) G_GNUC_PRINTF (4, 5);
390 set_error_literal (GMarkupParseContext *context,
393 const gchar *message)
397 tmp_error = g_error_new_literal (G_MARKUP_ERROR, code, message);
399 g_prefix_error (&tmp_error,
400 _("Error on line %d char %d: "),
401 context->line_number,
402 context->char_number);
404 mark_error (context, tmp_error);
406 g_propagate_error (error, tmp_error);
411 set_error (GMarkupParseContext *context,
421 va_start (args, format);
422 s = g_strdup_vprintf (format, args);
425 /* Make sure that the GError message is valid UTF-8
426 * even if it is complaining about invalid UTF-8 in the markup
428 s_valid = g_utf8_make_valid (s, -1);
429 set_error_literal (context, error, code, s);
436 propagate_error (GMarkupParseContext *context,
440 if (context->flags & G_MARKUP_PREFIX_ERROR_POSITION)
441 g_prefix_error (&src,
442 _("Error on line %d char %d: "),
443 context->line_number,
444 context->char_number);
446 mark_error (context, src);
448 g_propagate_error (dest, src);
451 #define IS_COMMON_NAME_END_CHAR(c) \
452 ((c) == '=' || (c) == '/' || (c) == '>' || (c) == ' ')
455 slow_name_validate (GMarkupParseContext *context,
459 const gchar *p = name;
461 if (!g_utf8_validate (name, -1, NULL))
463 set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
464 _("Invalid UTF-8 encoded text in name — not valid “%s”"), name);
468 if (!(g_ascii_isalpha (*p) ||
469 (!IS_COMMON_NAME_END_CHAR (*p) &&
472 g_unichar_isalpha (g_utf8_get_char (p))))))
474 set_error (context, error, G_MARKUP_ERROR_PARSE,
475 _("“%s” is not a valid name"), name);
479 for (p = g_utf8_next_char (name); *p != '\0'; p = g_utf8_next_char (p))
482 if (!(g_ascii_isalnum (*p) ||
483 (!IS_COMMON_NAME_END_CHAR (*p) &&
488 g_unichar_isalpha (g_utf8_get_char (p))))))
490 set_error (context, error, G_MARKUP_ERROR_PARSE,
491 _("“%s” is not a valid name: “%c”"), name, *p);
499 * Use me for elements, attributes etc.
502 name_validate (GMarkupParseContext *context,
509 /* name start char */
511 if (G_UNLIKELY (IS_COMMON_NAME_END_CHAR (*p) ||
512 !(g_ascii_isalpha (*p) || *p == '_' || *p == ':')))
515 for (mask = *p++; *p != '\0'; p++)
520 if (G_UNLIKELY (!(g_ascii_isalnum (*p) ||
521 (!IS_COMMON_NAME_END_CHAR (*p) &&
529 if (mask & 0x80) /* un-common / non-ascii */
535 return slow_name_validate (context, name, error);
539 text_validate (GMarkupParseContext *context,
544 if (!g_utf8_validate_len (p, len, NULL))
546 set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
547 _("Invalid UTF-8 encoded text in name — not valid “%s”"), p);
555 char_str (gunichar c,
559 g_unichar_to_utf8 (c, buf);
563 /* Format the next UTF-8 character as a gchar* for printing in error output
564 * when we encounter a syntax error. This correctly handles invalid UTF-8,
565 * emitting it as hex escapes. */
567 utf8_str (const gchar *utf8,
571 gunichar c = g_utf8_get_char_validated (utf8, max_len);
572 if (c == (gunichar) -1 || c == (gunichar) -2)
574 guchar ch = (max_len > 0) ? (guchar) *utf8 : 0;
575 gchar *temp = g_strdup_printf ("\\x%02x", (guint) ch);
577 memcpy (buf, temp, strlen (temp));
587 set_unescape_error (GMarkupParseContext *context,
589 const gchar *remaining_text,
597 gint remaining_newlines;
600 remaining_newlines = 0;
605 ++remaining_newlines;
609 va_start (args, format);
610 s = g_strdup_vprintf (format, args);
613 tmp_error = g_error_new (G_MARKUP_ERROR,
615 _("Error on line %d: %s"),
616 context->line_number - remaining_newlines,
621 mark_error (context, tmp_error);
623 g_propagate_error (error, tmp_error);
627 * re-write the GString in-place, unescaping anything that escaped.
628 * most XML does not contain entities, or escaping.
631 unescape_gstring_inplace (GMarkupParseContext *context,
638 gboolean normalize_attribute;
642 /* are we unescaping an attribute or not ? */
643 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
644 context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
645 normalize_attribute = TRUE;
647 normalize_attribute = FALSE;
650 * Meeks' theorem: unescaping can only shrink text.
651 * for < etc. this is obvious, for  more
652 * thought is required, but this is patently so.
655 for (from = to = string->str; *from != '\0'; from++, to++)
660 if (normalize_attribute && (*to == '\t' || *to == '\n'))
664 *to = normalize_attribute ? ' ' : '\n';
686 l = strtoul (from, &end, base);
688 if (end == from || errno != 0)
690 set_unescape_error (context, error,
691 from, G_MARKUP_ERROR_PARSE,
692 _("Failed to parse “%-.*s”, which "
693 "should have been a digit "
694 "inside a character reference "
695 "(ê for example) — perhaps "
696 "the digit is too large"),
697 (int)(end - from), from);
700 else if (*end != ';')
702 set_unescape_error (context, error,
703 from, G_MARKUP_ERROR_PARSE,
704 _("Character reference did not end with a "
706 "most likely you used an ampersand "
707 "character without intending to start "
708 "an entity — escape ampersand as &"));
713 /* characters XML 1.1 permits */
714 if ((0 < l && l <= 0xD7FF) ||
715 (0xE000 <= l && l <= 0xFFFD) ||
716 (0x10000 <= l && l <= 0x10FFFF))
721 to += strlen (buf) - 1;
723 if (l >= 0x80) /* not ascii */
728 set_unescape_error (context, error,
729 from, G_MARKUP_ERROR_PARSE,
730 _("Character reference “%-.*s” does not "
731 "encode a permitted character"),
732 (int)(end - from), from);
738 else if (strncmp (from, "lt;", 3) == 0)
743 else if (strncmp (from, "gt;", 3) == 0)
748 else if (strncmp (from, "amp;", 4) == 0)
753 else if (strncmp (from, "quot;", 5) == 0)
758 else if (strncmp (from, "apos;", 5) == 0)
766 set_unescape_error (context, error,
767 from, G_MARKUP_ERROR_PARSE,
768 _("Empty entity “&;” seen; valid "
769 "entities are: & " < > '"));
772 const char *end = strchr (from, ';');
774 set_unescape_error (context, error,
775 from, G_MARKUP_ERROR_PARSE,
776 _("Entity name “%-.*s” is not known"),
777 (int)(end - from), from);
779 set_unescape_error (context, error,
780 from, G_MARKUP_ERROR_PARSE,
781 _("Entity did not end with a semicolon; "
782 "most likely you used an ampersand "
783 "character without intending to start "
784 "an entity — escape ampersand as &"));
791 g_assert (to - string->str <= (gssize) string->len);
792 if (to - string->str != (gssize) string->len)
793 g_string_truncate (string, to - string->str);
795 *is_ascii = !(mask & 0x80);
800 static inline gboolean
801 advance_char (GMarkupParseContext *context)
804 context->char_number++;
806 if (G_UNLIKELY (context->iter == context->current_text_end))
809 else if (G_UNLIKELY (*context->iter == '\n'))
811 context->line_number++;
812 context->char_number = 1;
818 static inline gboolean
821 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
825 skip_spaces (GMarkupParseContext *context)
829 if (!xml_isspace (*context->iter))
832 while (advance_char (context));
836 advance_to_name_end (GMarkupParseContext *context)
840 if (IS_COMMON_NAME_END_CHAR (*(context->iter)))
842 if (xml_isspace (*(context->iter)))
845 while (advance_char (context));
849 release_chunk (GMarkupParseContext *context, GString *str)
854 if (str->allocated_len > 256)
855 { /* large strings are unusual and worth freeing */
856 g_string_free (str, TRUE);
860 node = get_list_node (context, str);
861 context->spare_chunks = g_slist_concat (node, context->spare_chunks);
865 add_to_partial (GMarkupParseContext *context,
866 const gchar *text_start,
867 const gchar *text_end)
869 if (context->partial_chunk == NULL)
870 { /* allocate a new chunk to parse into */
872 if (context->spare_chunks != NULL)
874 GSList *node = context->spare_chunks;
875 context->spare_chunks = g_slist_remove_link (context->spare_chunks, node);
876 context->partial_chunk = node->data;
877 free_list_node (context, node);
880 context->partial_chunk = g_string_sized_new (MAX (28, text_end - text_start));
883 if (text_start != text_end)
884 g_string_insert_len (context->partial_chunk, -1,
885 text_start, text_end - text_start);
889 truncate_partial (GMarkupParseContext *context)
891 if (context->partial_chunk != NULL)
892 string_blank (context->partial_chunk);
895 static inline const gchar*
896 current_element (GMarkupParseContext *context)
898 return context->tag_stack->data;
902 pop_subparser_stack (GMarkupParseContext *context)
904 GMarkupRecursionTracker *tracker;
906 g_assert (context->subparser_stack);
908 tracker = context->subparser_stack->data;
910 context->awaiting_pop = TRUE;
911 context->held_user_data = context->user_data;
913 context->user_data = tracker->prev_user_data;
914 context->parser = tracker->prev_parser;
915 context->subparser_element = tracker->prev_element;
916 g_slice_free (GMarkupRecursionTracker, tracker);
918 context->subparser_stack = g_slist_delete_link (context->subparser_stack,
919 context->subparser_stack);
923 push_partial_as_tag (GMarkupParseContext *context)
925 GString *str = context->partial_chunk;
926 /* sadly, this is exported by gmarkup_get_element_stack as-is */
927 context->tag_stack = g_slist_concat (get_list_node (context, str->str), context->tag_stack);
928 context->tag_stack_gstr = g_slist_concat (get_list_node (context, str), context->tag_stack_gstr);
929 context->partial_chunk = NULL;
933 pop_tag (GMarkupParseContext *context)
935 GSList *nodea, *nodeb;
937 nodea = context->tag_stack;
938 nodeb = context->tag_stack_gstr;
939 release_chunk (context, nodeb->data);
940 context->tag_stack = g_slist_remove_link (context->tag_stack, nodea);
941 context->tag_stack_gstr = g_slist_remove_link (context->tag_stack_gstr, nodeb);
942 free_list_node (context, nodea);
943 free_list_node (context, nodeb);
947 possibly_finish_subparser (GMarkupParseContext *context)
949 if (current_element (context) == context->subparser_element)
950 pop_subparser_stack (context);
954 ensure_no_outstanding_subparser (GMarkupParseContext *context)
956 if (context->awaiting_pop)
957 g_critical ("During the first end_element call after invoking a "
958 "subparser you must pop the subparser stack and handle "
959 "the freeing of the subparser user_data. This can be "
960 "done by calling the end function of the subparser. "
961 "Very probably, your program just leaked memory.");
963 /* let valgrind watch the pointer disappear... */
964 context->held_user_data = NULL;
965 context->awaiting_pop = FALSE;
969 current_attribute (GMarkupParseContext *context)
971 g_assert (context->cur_attr >= 0);
972 return context->attr_names[context->cur_attr]->str;
976 add_attribute (GMarkupParseContext *context, GString *str)
978 /* Sanity check on the number of attributes. */
979 if (context->cur_attr >= 1000)
982 if (context->cur_attr + 2 >= context->alloc_attrs)
984 context->alloc_attrs += 5; /* silly magic number */
985 context->attr_names = g_realloc (context->attr_names, sizeof(GString*)*context->alloc_attrs);
986 context->attr_values = g_realloc (context->attr_values, sizeof(GString*)*context->alloc_attrs);
989 context->attr_names[context->cur_attr] = str;
990 context->attr_values[context->cur_attr] = NULL;
991 context->attr_names[context->cur_attr+1] = NULL;
992 context->attr_values[context->cur_attr+1] = NULL;
998 clear_attributes (GMarkupParseContext *context)
1000 /* Go ahead and free the attributes. */
1001 for (; context->cur_attr >= 0; context->cur_attr--)
1003 int pos = context->cur_attr;
1004 release_chunk (context, context->attr_names[pos]);
1005 release_chunk (context, context->attr_values[pos]);
1006 context->attr_names[pos] = context->attr_values[pos] = NULL;
1008 g_assert (context->cur_attr == -1);
1009 g_assert (context->attr_names == NULL ||
1010 context->attr_names[0] == NULL);
1011 g_assert (context->attr_values == NULL ||
1012 context->attr_values[0] == NULL);
1015 /* This has to be a separate function to ensure the alloca's
1016 * are unwound on exit - otherwise we grow & blow the stack
1017 * with large documents
1020 emit_start_element (GMarkupParseContext *context,
1024 const gchar *start_name;
1025 const gchar **attr_names;
1026 const gchar **attr_values;
1029 /* In case we want to ignore qualified tags and we see that we have
1030 * one here, we push a subparser. This will ignore all tags inside of
1031 * the qualified tag.
1033 * We deal with the end of the subparser from emit_end_element.
1035 if ((context->flags & G_MARKUP_IGNORE_QUALIFIED) && strchr (current_element (context), ':'))
1037 static const GMarkupParser ignore_parser = { 0 };
1038 g_markup_parse_context_push (context, &ignore_parser, NULL);
1039 clear_attributes (context);
1043 attr_names = g_newa (const gchar *, context->cur_attr + 2);
1044 attr_values = g_newa (const gchar *, context->cur_attr + 2);
1045 for (i = 0; i < context->cur_attr + 1; i++)
1047 /* Possibly omit qualified attribute names from the list */
1048 if ((context->flags & G_MARKUP_IGNORE_QUALIFIED) && strchr (context->attr_names[i]->str, ':'))
1051 attr_names[j] = context->attr_names[i]->str;
1052 attr_values[j] = context->attr_values[i]->str;
1055 attr_names[j] = NULL;
1056 attr_values[j] = NULL;
1058 /* Call user callback for element start */
1060 start_name = current_element (context);
1062 if (!name_validate (context, start_name, error))
1065 if (context->parser->start_element)
1066 (* context->parser->start_element) (context,
1068 (const gchar **)attr_names,
1069 (const gchar **)attr_values,
1072 clear_attributes (context);
1074 if (tmp_error != NULL)
1075 propagate_error (context, error, tmp_error);
1079 emit_end_element (GMarkupParseContext *context,
1082 /* We need to pop the tag stack and call the end_element
1083 * function, since this is the close tag
1085 GError *tmp_error = NULL;
1087 g_assert (context->tag_stack != NULL);
1089 possibly_finish_subparser (context);
1091 /* We might have just returned from our ignore subparser */
1092 if ((context->flags & G_MARKUP_IGNORE_QUALIFIED) && strchr (current_element (context), ':'))
1094 g_markup_parse_context_pop (context);
1100 if (context->parser->end_element)
1101 (* context->parser->end_element) (context,
1102 current_element (context),
1106 ensure_no_outstanding_subparser (context);
1110 mark_error (context, tmp_error);
1111 g_propagate_error (error, tmp_error);
1118 * g_markup_parse_context_parse:
1119 * @context: a #GMarkupParseContext
1120 * @text: chunk of text to parse
1121 * @text_len: length of @text in bytes
1122 * @error: return location for a #GError
1124 * Feed some data to the #GMarkupParseContext.
1126 * The data need not be valid UTF-8; an error will be signaled if
1127 * it's invalid. The data need not be an entire document; you can
1128 * feed a document into the parser incrementally, via multiple calls
1129 * to this function. Typically, as you receive data from a network
1130 * connection or file, you feed each received chunk of data into this
1131 * function, aborting the process if an error occurs. Once an error
1132 * is reported, no further data may be fed to the #GMarkupParseContext;
1133 * all errors are fatal.
1135 * Returns: %FALSE if an error occurred, %TRUE on success
1138 g_markup_parse_context_parse (GMarkupParseContext *context,
1143 g_return_val_if_fail (context != NULL, FALSE);
1144 g_return_val_if_fail (text != NULL, FALSE);
1145 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1146 g_return_val_if_fail (!context->parsing, FALSE);
1149 text_len = strlen (text);
1154 context->parsing = TRUE;
1157 context->current_text = text;
1158 context->current_text_len = text_len;
1159 context->current_text_end = context->current_text + text_len;
1160 context->iter = context->current_text;
1161 context->start = context->iter;
1163 while (context->iter != context->current_text_end)
1165 switch (context->state)
1168 /* Possible next state: AFTER_OPEN_ANGLE */
1170 g_assert (context->tag_stack == NULL);
1172 /* whitespace is ignored outside of any elements */
1173 skip_spaces (context);
1175 if (context->iter != context->current_text_end)
1177 if (*context->iter == '<')
1179 /* Move after the open angle */
1180 advance_char (context);
1182 context->state = STATE_AFTER_OPEN_ANGLE;
1184 /* this could start a passthrough */
1185 context->start = context->iter;
1187 /* document is now non-empty */
1188 context->document_empty = FALSE;
1192 set_error_literal (context,
1194 G_MARKUP_ERROR_PARSE,
1195 _("Document must begin with an element (e.g. <book>)"));
1200 case STATE_AFTER_OPEN_ANGLE:
1201 /* Possible next states: INSIDE_OPEN_TAG_NAME,
1202 * AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1204 if (*context->iter == '?' ||
1205 *context->iter == '!')
1207 /* include < in the passthrough */
1208 const gchar *openangle = "<";
1209 add_to_partial (context, openangle, openangle + 1);
1210 context->start = context->iter;
1211 context->balance = 1;
1212 context->state = STATE_INSIDE_PASSTHROUGH;
1214 else if (*context->iter == '/')
1217 advance_char (context);
1219 context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1221 else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1223 context->state = STATE_INSIDE_OPEN_TAG_NAME;
1225 /* start of tag name */
1226 context->start = context->iter;
1234 G_MARKUP_ERROR_PARSE,
1235 _("“%s” is not a valid character following "
1236 "a “<” character; it may not begin an "
1238 utf8_str (context->iter,
1239 context->current_text_end - context->iter, buf));
1243 /* The AFTER_CLOSE_ANGLE state is actually sort of
1244 * broken, because it doesn't correspond to a range
1245 * of characters in the input stream as the others do,
1246 * and thus makes things harder to conceptualize
1248 case STATE_AFTER_CLOSE_ANGLE:
1249 /* Possible next states: INSIDE_TEXT, STATE_START */
1250 if (context->tag_stack == NULL)
1252 context->start = NULL;
1253 context->state = STATE_START;
1257 context->start = context->iter;
1258 context->state = STATE_INSIDE_TEXT;
1262 case STATE_AFTER_ELISION_SLASH:
1263 /* Possible next state: AFTER_CLOSE_ANGLE */
1264 if (*context->iter == '>')
1266 /* move after the close angle */
1267 advance_char (context);
1268 context->state = STATE_AFTER_CLOSE_ANGLE;
1269 emit_end_element (context, error);
1277 G_MARKUP_ERROR_PARSE,
1278 _("Odd character “%s”, expected a “>” character "
1279 "to end the empty-element tag “%s”"),
1280 utf8_str (context->iter,
1281 context->current_text_end - context->iter, buf),
1282 current_element (context));
1286 case STATE_INSIDE_OPEN_TAG_NAME:
1287 /* Possible next states: BETWEEN_ATTRIBUTES */
1289 /* if there's a partial chunk then it's the first part of the
1290 * tag name. If there's a context->start then it's the start
1291 * of the tag name in current_text, the partial chunk goes
1292 * before that start though.
1294 advance_to_name_end (context);
1296 if (context->iter == context->current_text_end)
1298 /* The name hasn't necessarily ended. Merge with
1299 * partial chunk, leave state unchanged.
1301 add_to_partial (context, context->start, context->iter);
1305 /* The name has ended. Combine it with the partial chunk
1306 * if any; push it on the stack; enter next state.
1308 add_to_partial (context, context->start, context->iter);
1309 push_partial_as_tag (context);
1311 context->state = STATE_BETWEEN_ATTRIBUTES;
1312 context->start = NULL;
1316 case STATE_INSIDE_ATTRIBUTE_NAME:
1317 /* Possible next states: AFTER_ATTRIBUTE_NAME */
1319 advance_to_name_end (context);
1320 add_to_partial (context, context->start, context->iter);
1322 /* read the full name, if we enter the equals sign state
1323 * then add the attribute to the list (without the value),
1324 * otherwise store a partial chunk to be prepended later.
1326 if (context->iter != context->current_text_end)
1327 context->state = STATE_AFTER_ATTRIBUTE_NAME;
1330 case STATE_AFTER_ATTRIBUTE_NAME:
1331 /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1333 skip_spaces (context);
1335 if (context->iter != context->current_text_end)
1337 /* The name has ended. Combine it with the partial chunk
1338 * if any; push it on the stack; enter next state.
1340 if (!name_validate (context, context->partial_chunk->str, error))
1343 if (!add_attribute (context, context->partial_chunk))
1347 G_MARKUP_ERROR_PARSE,
1348 _("Too many attributes in element “%s”"),
1349 current_element (context));
1353 context->partial_chunk = NULL;
1354 context->start = NULL;
1356 if (*context->iter == '=')
1358 advance_char (context);
1359 context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1367 G_MARKUP_ERROR_PARSE,
1368 _("Odd character “%s”, expected a “=” after "
1369 "attribute name “%s” of element “%s”"),
1370 utf8_str (context->iter,
1371 context->current_text_end - context->iter, buf),
1372 current_attribute (context),
1373 current_element (context));
1379 case STATE_BETWEEN_ATTRIBUTES:
1380 /* Possible next states: AFTER_CLOSE_ANGLE,
1381 * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1383 skip_spaces (context);
1385 if (context->iter != context->current_text_end)
1387 if (*context->iter == '/')
1389 advance_char (context);
1390 context->state = STATE_AFTER_ELISION_SLASH;
1392 else if (*context->iter == '>')
1394 advance_char (context);
1395 context->state = STATE_AFTER_CLOSE_ANGLE;
1397 else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1399 context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1400 /* start of attribute name */
1401 context->start = context->iter;
1409 G_MARKUP_ERROR_PARSE,
1410 _("Odd character “%s”, expected a “>” or “/” "
1411 "character to end the start tag of "
1412 "element “%s”, or optionally an attribute; "
1413 "perhaps you used an invalid character in "
1414 "an attribute name"),
1415 utf8_str (context->iter,
1416 context->current_text_end - context->iter, buf),
1417 current_element (context));
1420 /* If we're done with attributes, invoke
1421 * the start_element callback
1423 if (context->state == STATE_AFTER_ELISION_SLASH ||
1424 context->state == STATE_AFTER_CLOSE_ANGLE)
1425 emit_start_element (context, error);
1429 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1430 /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1432 skip_spaces (context);
1434 if (context->iter != context->current_text_end)
1436 if (*context->iter == '"')
1438 advance_char (context);
1439 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1440 context->start = context->iter;
1442 else if (*context->iter == '\'')
1444 advance_char (context);
1445 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1446 context->start = context->iter;
1454 G_MARKUP_ERROR_PARSE,
1455 _("Odd character “%s”, expected an open quote mark "
1456 "after the equals sign when giving value for "
1457 "attribute “%s” of element “%s”"),
1458 utf8_str (context->iter,
1459 context->current_text_end - context->iter, buf),
1460 current_attribute (context),
1461 current_element (context));
1466 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1467 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1468 /* Possible next states: BETWEEN_ATTRIBUTES */
1472 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ)
1483 if (*context->iter == delim)
1486 while (advance_char (context));
1488 if (context->iter == context->current_text_end)
1490 /* The value hasn't necessarily ended. Merge with
1491 * partial chunk, leave state unchanged.
1493 add_to_partial (context, context->start, context->iter);
1498 /* The value has ended at the quote mark. Combine it
1499 * with the partial chunk if any; set it for the current
1502 add_to_partial (context, context->start, context->iter);
1504 g_assert (context->cur_attr >= 0);
1506 if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1507 (is_ascii || text_validate (context, context->partial_chunk->str,
1508 context->partial_chunk->len, error)))
1510 /* success, advance past quote and set state. */
1511 context->attr_values[context->cur_attr] = context->partial_chunk;
1512 context->partial_chunk = NULL;
1513 advance_char (context);
1514 context->state = STATE_BETWEEN_ATTRIBUTES;
1515 context->start = NULL;
1518 truncate_partial (context);
1522 case STATE_INSIDE_TEXT:
1523 /* Possible next states: AFTER_OPEN_ANGLE */
1526 if (*context->iter == '<')
1529 while (advance_char (context));
1531 /* The text hasn't necessarily ended. Merge with
1532 * partial chunk, leave state unchanged.
1535 add_to_partial (context, context->start, context->iter);
1537 if (context->iter != context->current_text_end)
1541 /* The text has ended at the open angle. Call the text
1544 if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1545 (is_ascii || text_validate (context, context->partial_chunk->str,
1546 context->partial_chunk->len, error)))
1548 GError *tmp_error = NULL;
1550 if (context->parser->text)
1551 (*context->parser->text) (context,
1552 context->partial_chunk->str,
1553 context->partial_chunk->len,
1557 if (tmp_error == NULL)
1559 /* advance past open angle and set state. */
1560 advance_char (context);
1561 context->state = STATE_AFTER_OPEN_ANGLE;
1562 /* could begin a passthrough */
1563 context->start = context->iter;
1566 propagate_error (context, error, tmp_error);
1569 truncate_partial (context);
1573 case STATE_AFTER_CLOSE_TAG_SLASH:
1574 /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1575 if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1577 context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1579 /* start of tag name */
1580 context->start = context->iter;
1588 G_MARKUP_ERROR_PARSE,
1589 _("“%s” is not a valid character following "
1590 "the characters “</”; “%s” may not begin an "
1592 utf8_str (context->iter,
1593 context->current_text_end - context->iter, buf),
1594 utf8_str (context->iter,
1595 context->current_text_end - context->iter, buf));
1599 case STATE_INSIDE_CLOSE_TAG_NAME:
1600 /* Possible next state: AFTER_CLOSE_TAG_NAME */
1601 advance_to_name_end (context);
1602 add_to_partial (context, context->start, context->iter);
1604 if (context->iter != context->current_text_end)
1605 context->state = STATE_AFTER_CLOSE_TAG_NAME;
1608 case STATE_AFTER_CLOSE_TAG_NAME:
1609 /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1611 skip_spaces (context);
1613 if (context->iter != context->current_text_end)
1615 GString *close_name;
1617 close_name = context->partial_chunk;
1618 context->partial_chunk = NULL;
1620 if (*context->iter != '>')
1626 G_MARKUP_ERROR_PARSE,
1627 _("“%s” is not a valid character following "
1628 "the close element name “%s”; the allowed "
1629 "character is “>”"),
1630 utf8_str (context->iter,
1631 context->current_text_end - context->iter, buf),
1634 else if (context->tag_stack == NULL)
1638 G_MARKUP_ERROR_PARSE,
1639 _("Element “%s” was closed, no element "
1640 "is currently open"),
1643 else if (strcmp (close_name->str, current_element (context)) != 0)
1647 G_MARKUP_ERROR_PARSE,
1648 _("Element “%s” was closed, but the currently "
1649 "open element is “%s”"),
1651 current_element (context));
1655 advance_char (context);
1656 context->state = STATE_AFTER_CLOSE_ANGLE;
1657 context->start = NULL;
1659 emit_end_element (context, error);
1661 context->partial_chunk = close_name;
1662 truncate_partial (context);
1666 case STATE_INSIDE_PASSTHROUGH:
1667 /* Possible next state: AFTER_CLOSE_ANGLE */
1670 if (*context->iter == '<')
1672 if (*context->iter == '>')
1678 add_to_partial (context, context->start, context->iter);
1679 context->start = context->iter;
1681 str = context->partial_chunk->str;
1682 len = context->partial_chunk->len;
1684 if (str[1] == '?' && str[len - 1] == '?')
1686 if (strncmp (str, "<!--", 4) == 0 &&
1687 strcmp (str + len - 2, "--") == 0)
1689 if (strncmp (str, "<![CDATA[", 9) == 0 &&
1690 strcmp (str + len - 2, "]]") == 0)
1692 if (strncmp (str, "<!DOCTYPE", 9) == 0 &&
1693 context->balance == 0)
1697 while (advance_char (context));
1699 if (context->iter == context->current_text_end)
1701 /* The passthrough hasn't necessarily ended. Merge with
1702 * partial chunk, leave state unchanged.
1704 add_to_partial (context, context->start, context->iter);
1708 /* The passthrough has ended at the close angle. Combine
1709 * it with the partial chunk if any. Call the passthrough
1710 * callback. Note that the open/close angles are
1711 * included in the text of the passthrough.
1713 GError *tmp_error = NULL;
1715 advance_char (context); /* advance past close angle */
1716 add_to_partial (context, context->start, context->iter);
1718 if (context->flags & G_MARKUP_TREAT_CDATA_AS_TEXT &&
1719 strncmp (context->partial_chunk->str, "<![CDATA[", 9) == 0)
1721 if (context->parser->text &&
1722 text_validate (context,
1723 context->partial_chunk->str + 9,
1724 context->partial_chunk->len - 12,
1726 (*context->parser->text) (context,
1727 context->partial_chunk->str + 9,
1728 context->partial_chunk->len - 12,
1732 else if (context->parser->passthrough &&
1733 text_validate (context,
1734 context->partial_chunk->str,
1735 context->partial_chunk->len,
1737 (*context->parser->passthrough) (context,
1738 context->partial_chunk->str,
1739 context->partial_chunk->len,
1743 truncate_partial (context);
1745 if (tmp_error == NULL)
1747 context->state = STATE_AFTER_CLOSE_ANGLE;
1748 context->start = context->iter; /* could begin text */
1751 propagate_error (context, error, tmp_error);
1760 g_assert_not_reached ();
1766 context->parsing = FALSE;
1768 return context->state != STATE_ERROR;
1772 * g_markup_parse_context_end_parse:
1773 * @context: a #GMarkupParseContext
1774 * @error: return location for a #GError
1776 * Signals to the #GMarkupParseContext that all data has been
1777 * fed into the parse context with g_markup_parse_context_parse().
1779 * This function reports an error if the document isn't complete,
1780 * for example if elements are still open.
1782 * Returns: %TRUE on success, %FALSE if an error was set
1785 g_markup_parse_context_end_parse (GMarkupParseContext *context,
1788 g_return_val_if_fail (context != NULL, FALSE);
1789 g_return_val_if_fail (!context->parsing, FALSE);
1790 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1792 if (context->partial_chunk != NULL)
1794 g_string_free (context->partial_chunk, TRUE);
1795 context->partial_chunk = NULL;
1798 if (context->document_empty)
1800 set_error_literal (context, error, G_MARKUP_ERROR_EMPTY,
1801 _("Document was empty or contained only whitespace"));
1805 context->parsing = TRUE;
1807 switch (context->state)
1813 case STATE_AFTER_OPEN_ANGLE:
1814 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1815 _("Document ended unexpectedly just after an open angle bracket “<”"));
1818 case STATE_AFTER_CLOSE_ANGLE:
1819 if (context->tag_stack != NULL)
1821 /* Error message the same as for INSIDE_TEXT */
1822 set_error (context, error, G_MARKUP_ERROR_PARSE,
1823 _("Document ended unexpectedly with elements still open — "
1824 "“%s” was the last element opened"),
1825 current_element (context));
1829 case STATE_AFTER_ELISION_SLASH:
1830 set_error (context, error, G_MARKUP_ERROR_PARSE,
1831 _("Document ended unexpectedly, expected to see a close angle "
1832 "bracket ending the tag <%s/>"), current_element (context));
1835 case STATE_INSIDE_OPEN_TAG_NAME:
1836 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1837 _("Document ended unexpectedly inside an element name"));
1840 case STATE_INSIDE_ATTRIBUTE_NAME:
1841 case STATE_AFTER_ATTRIBUTE_NAME:
1842 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1843 _("Document ended unexpectedly inside an attribute name"));
1846 case STATE_BETWEEN_ATTRIBUTES:
1847 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1848 _("Document ended unexpectedly inside an element-opening "
1852 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1853 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1854 _("Document ended unexpectedly after the equals sign "
1855 "following an attribute name; no attribute value"));
1858 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1859 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1860 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1861 _("Document ended unexpectedly while inside an attribute "
1865 case STATE_INSIDE_TEXT:
1866 g_assert (context->tag_stack != NULL);
1867 set_error (context, error, G_MARKUP_ERROR_PARSE,
1868 _("Document ended unexpectedly with elements still open — "
1869 "“%s” was the last element opened"),
1870 current_element (context));
1873 case STATE_AFTER_CLOSE_TAG_SLASH:
1874 case STATE_INSIDE_CLOSE_TAG_NAME:
1875 case STATE_AFTER_CLOSE_TAG_NAME:
1876 if (context->tag_stack != NULL)
1877 set_error (context, error, G_MARKUP_ERROR_PARSE,
1878 _("Document ended unexpectedly inside the close tag for "
1879 "element “%s”"), current_element (context));
1881 set_error (context, error, G_MARKUP_ERROR_PARSE,
1882 _("Document ended unexpectedly inside the close tag for an "
1883 "unopened element"));
1886 case STATE_INSIDE_PASSTHROUGH:
1887 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1888 _("Document ended unexpectedly inside a comment or "
1889 "processing instruction"));
1894 g_assert_not_reached ();
1898 context->parsing = FALSE;
1900 return context->state != STATE_ERROR;
1904 * g_markup_parse_context_get_element:
1905 * @context: a #GMarkupParseContext
1907 * Retrieves the name of the currently open element.
1909 * If called from the start_element or end_element handlers this will
1910 * give the element_name as passed to those functions. For the parent
1911 * elements, see g_markup_parse_context_get_element_stack().
1913 * Returns: the name of the currently open element, or %NULL
1918 g_markup_parse_context_get_element (GMarkupParseContext *context)
1920 g_return_val_if_fail (context != NULL, NULL);
1922 if (context->tag_stack == NULL)
1925 return current_element (context);
1929 * g_markup_parse_context_get_element_stack:
1930 * @context: a #GMarkupParseContext
1932 * Retrieves the element stack from the internal state of the parser.
1934 * The returned #GSList is a list of strings where the first item is
1935 * the currently open tag (as would be returned by
1936 * g_markup_parse_context_get_element()) and the next item is its
1939 * This function is intended to be used in the start_element and
1940 * end_element handlers where g_markup_parse_context_get_element()
1941 * would merely return the name of the element that is being
1944 * Returns: the element stack, which must not be modified
1949 g_markup_parse_context_get_element_stack (GMarkupParseContext *context)
1951 g_return_val_if_fail (context != NULL, NULL);
1952 return context->tag_stack;
1956 * g_markup_parse_context_get_position:
1957 * @context: a #GMarkupParseContext
1958 * @line_number: (out) (optional): return location for a line number, or %NULL
1959 * @char_number: (out) (optional): return location for a char-on-line number, or %NULL
1961 * Retrieves the current line number and the number of the character on
1962 * that line. Intended for use in error messages; there are no strict
1963 * semantics for what constitutes the "current" line number other than
1964 * "the best number we could come up with for error messages."
1967 g_markup_parse_context_get_position (GMarkupParseContext *context,
1971 g_return_if_fail (context != NULL);
1974 *line_number = context->line_number;
1977 *char_number = context->char_number;
1981 * g_markup_parse_context_get_user_data:
1982 * @context: a #GMarkupParseContext
1984 * Returns the user_data associated with @context.
1986 * This will either be the user_data that was provided to
1987 * g_markup_parse_context_new() or to the most recent call
1988 * of g_markup_parse_context_push().
1990 * Returns: the provided user_data. The returned data belongs to
1991 * the markup context and will be freed when
1992 * g_markup_parse_context_free() is called.
1997 g_markup_parse_context_get_user_data (GMarkupParseContext *context)
1999 return context->user_data;
2003 * g_markup_parse_context_push:
2004 * @context: a #GMarkupParseContext
2005 * @parser: a #GMarkupParser
2006 * @user_data: user data to pass to #GMarkupParser functions
2008 * Temporarily redirects markup data to a sub-parser.
2010 * This function may only be called from the start_element handler of
2011 * a #GMarkupParser. It must be matched with a corresponding call to
2012 * g_markup_parse_context_pop() in the matching end_element handler
2013 * (except in the case that the parser aborts due to an error).
2015 * All tags, text and other data between the matching tags is
2016 * redirected to the subparser given by @parser. @user_data is used
2017 * as the user_data for that parser. @user_data is also passed to the
2018 * error callback in the event that an error occurs. This includes
2019 * errors that occur in subparsers of the subparser.
2021 * The end tag matching the start tag for which this call was made is
2022 * handled by the previous parser (which is given its own user_data)
2023 * which is why g_markup_parse_context_pop() is provided to allow "one
2024 * last access" to the @user_data provided to this function. In the
2025 * case of error, the @user_data provided here is passed directly to
2026 * the error callback of the subparser and g_markup_parse_context_pop()
2027 * should not be called. In either case, if @user_data was allocated
2028 * then it ought to be freed from both of these locations.
2030 * This function is not intended to be directly called by users
2031 * interested in invoking subparsers. Instead, it is intended to be
2032 * used by the subparsers themselves to implement a higher-level
2035 * As an example, see the following implementation of a simple
2036 * parser that counts the number of tags encountered.
2038 * |[<!-- language="C" -->
2045 * counter_start_element (GMarkupParseContext *context,
2046 * const gchar *element_name,
2047 * const gchar **attribute_names,
2048 * const gchar **attribute_values,
2049 * gpointer user_data,
2052 * CounterData *data = user_data;
2054 * data->tag_count++;
2058 * counter_error (GMarkupParseContext *context,
2060 * gpointer user_data)
2062 * CounterData *data = user_data;
2064 * g_slice_free (CounterData, data);
2067 * static GMarkupParser counter_subparser =
2069 * counter_start_element,
2077 * In order to allow this parser to be easily used as a subparser, the
2078 * following interface is provided:
2080 * |[<!-- language="C" -->
2082 * start_counting (GMarkupParseContext *context)
2084 * CounterData *data = g_slice_new (CounterData);
2086 * data->tag_count = 0;
2087 * g_markup_parse_context_push (context, &counter_subparser, data);
2091 * end_counting (GMarkupParseContext *context)
2093 * CounterData *data = g_markup_parse_context_pop (context);
2096 * result = data->tag_count;
2097 * g_slice_free (CounterData, data);
2103 * The subparser would then be used as follows:
2105 * |[<!-- language="C" -->
2106 * static void start_element (context, element_name, ...)
2108 * if (strcmp (element_name, "count-these") == 0)
2109 * start_counting (context);
2111 * // else, handle other tags...
2114 * static void end_element (context, element_name, ...)
2116 * if (strcmp (element_name, "count-these") == 0)
2117 * g_print ("Counted %d tags\n", end_counting (context));
2119 * // else, handle other tags...
2126 g_markup_parse_context_push (GMarkupParseContext *context,
2127 const GMarkupParser *parser,
2130 GMarkupRecursionTracker *tracker;
2132 tracker = g_slice_new (GMarkupRecursionTracker);
2133 tracker->prev_element = context->subparser_element;
2134 tracker->prev_parser = context->parser;
2135 tracker->prev_user_data = context->user_data;
2137 context->subparser_element = current_element (context);
2138 context->parser = parser;
2139 context->user_data = user_data;
2141 context->subparser_stack = g_slist_prepend (context->subparser_stack,
2146 * g_markup_parse_context_pop:
2147 * @context: a #GMarkupParseContext
2149 * Completes the process of a temporary sub-parser redirection.
2151 * This function exists to collect the user_data allocated by a
2152 * matching call to g_markup_parse_context_push(). It must be called
2153 * in the end_element handler corresponding to the start_element
2154 * handler during which g_markup_parse_context_push() was called.
2155 * You must not call this function from the error callback -- the
2156 * @user_data is provided directly to the callback in that case.
2158 * This function is not intended to be directly called by users
2159 * interested in invoking subparsers. Instead, it is intended to
2160 * be used by the subparsers themselves to implement a higher-level
2163 * Returns: the user data passed to g_markup_parse_context_push()
2168 g_markup_parse_context_pop (GMarkupParseContext *context)
2172 if (!context->awaiting_pop)
2173 possibly_finish_subparser (context);
2175 g_assert (context->awaiting_pop);
2177 context->awaiting_pop = FALSE;
2179 /* valgrind friendliness */
2180 user_data = context->held_user_data;
2181 context->held_user_data = NULL;
2186 #define APPEND_TEXT_AND_SEEK(_str, _start, _end) \
2188 if (_end > _start) \
2189 g_string_append_len (_str, _start, _end - _start); \
2194 * https://www.w3.org/TR/REC-xml/ defines the set of valid
2196 * #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
2198 * That is, from non-ASCII UTF-8 character set, only 0xC27F - 0xC284 and
2199 * 0xC286 - 0xC29F have to be escaped (excluding the surrogate blocks).
2200 * Corresponding Unicode code points are [0x7F-0x84] and [0x86-0x9F].
2202 * So instead of using costly g_utf8_next_char or similar UTF8 functions, it's
2203 * better to read each byte, and make an exception for 0xC2XX.
2206 append_escaped_text (GString *str,
2210 const gchar *p, *pending;
2214 end = text + length;
2216 while (p < end && pending < end)
2218 guchar c = (guchar) *pending;
2223 APPEND_TEXT_AND_SEEK (str, p, pending);
2224 g_string_append (str, "&");
2228 APPEND_TEXT_AND_SEEK (str, p, pending);
2229 g_string_append (str, "<");
2233 APPEND_TEXT_AND_SEEK (str, p, pending);
2234 g_string_append (str, ">");
2238 APPEND_TEXT_AND_SEEK (str, p, pending);
2239 g_string_append (str, "'");
2243 APPEND_TEXT_AND_SEEK (str, p, pending);
2244 g_string_append (str, """);
2248 if ((0x1 <= c && c <= 0x8) ||
2249 (0xb <= c && c <= 0xc) ||
2250 (0xe <= c && c <= 0x1f) ||
2253 APPEND_TEXT_AND_SEEK (str, p, pending);
2254 g_string_append_printf (str, "&#x%x;", c);
2256 /* The utf-8 control characters to escape begins with 0xc2 byte */
2259 gunichar u = g_utf8_get_char (pending);
2261 if ((0x7f < u && u <= 0x84) ||
2262 (0x86 <= u && u <= 0x9f))
2264 APPEND_TEXT_AND_SEEK (str, p, pending);
2265 g_string_append_printf (str, "&#x%x;", u);
2268 * We have appended a two byte character above, which
2269 * is one byte ahead of what we read on every loop.
2270 * Increment to skip 0xc2 and point to the right location.
2284 g_string_append_len (str, p, pending - p);
2287 #undef APPEND_TEXT_AND_SEEK
2290 * g_markup_escape_text:
2291 * @text: some valid UTF-8 text
2292 * @length: length of @text in bytes, or -1 if the text is nul-terminated
2294 * Escapes text so that the markup parser will parse it verbatim.
2295 * Less than, greater than, ampersand, etc. are replaced with the
2296 * corresponding entities. This function would typically be used
2297 * when writing out a file to be parsed with the markup parser.
2299 * Note that this function doesn't protect whitespace and line endings
2300 * from being processed according to the XML rules for normalization
2301 * of line endings and attribute values.
2303 * Note also that this function will produce character references in
2304 * the range of  ...  for all control sequences
2305 * except for tabstop, newline and carriage return. The character
2306 * references in this range are not valid XML 1.0, but they are
2307 * valid XML 1.1 and will be accepted by the GMarkup parser.
2309 * Returns: a newly allocated string with the escaped text
2312 g_markup_escape_text (const gchar *text,
2317 g_return_val_if_fail (text != NULL, NULL);
2320 length = strlen (text);
2322 /* prealloc at least as long as original text */
2323 str = g_string_sized_new (length);
2324 append_escaped_text (str, text, length);
2326 return g_string_free (str, FALSE);
2331 * @format: a printf-style format string
2332 * @after: location to store a pointer to the character after
2333 * the returned conversion. On a %NULL return, returns the
2334 * pointer to the trailing NUL in the string
2336 * Find the next conversion in a printf-style format string.
2337 * Partially based on code from printf-parser.c,
2338 * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
2340 * Returns: pointer to the next conversion in @format,
2341 * or %NULL, if none.
2344 find_conversion (const char *format,
2347 const char *start = format;
2350 while (*start != '\0' && *start != '%')
2367 /* Test for positional argument. */
2368 if (*cp >= '0' && *cp <= '9')
2372 for (np = cp; *np >= '0' && *np <= '9'; np++)
2378 /* Skip the flags. */
2392 /* Skip the field width. */
2397 /* Test for positional argument. */
2398 if (*cp >= '0' && *cp <= '9')
2402 for (np = cp; *np >= '0' && *np <= '9'; np++)
2410 for (; *cp >= '0' && *cp <= '9'; cp++)
2414 /* Skip the precision. */
2420 /* Test for positional argument. */
2421 if (*cp >= '0' && *cp <= '9')
2425 for (np = cp; *np >= '0' && *np <= '9'; np++)
2433 for (; *cp >= '0' && *cp <= '9'; cp++)
2438 /* Skip argument type/size specifiers. */
2439 while (*cp == 'h' ||
2448 /* Skip the conversion character. */
2456 * g_markup_vprintf_escaped:
2457 * @format: printf() style format string
2458 * @args: variable argument list, similar to vprintf()
2460 * Formats the data in @args according to @format, escaping
2461 * all string and character arguments in the fashion
2462 * of g_markup_escape_text(). See g_markup_printf_escaped().
2464 * Returns: newly allocated result from formatting
2465 * operation. Free with g_free().
2469 #pragma GCC diagnostic push
2470 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2473 g_markup_vprintf_escaped (const gchar *format,
2478 GString *result = NULL;
2479 gchar *output1 = NULL;
2480 gchar *output2 = NULL;
2481 const char *p, *op1, *op2;
2484 /* The technique here, is that we make two format strings that
2485 * have the identical conversions in the identical order to the
2486 * original strings, but differ in the text in-between. We
2487 * then use the normal g_strdup_vprintf() to format the arguments
2488 * with the two new format strings. By comparing the results,
2489 * we can figure out what segments of the output come from
2490 * the original format string, and what from the arguments,
2491 * and thus know what portions of the string to escape.
2493 * For instance, for:
2495 * g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2497 * We form the two format strings "%sX%dX" and %sY%sY". The results
2498 * of formatting with those two strings are
2500 * "%sX%dX" => "Susan & FredX5X"
2501 * "%sY%dY" => "Susan & FredY5Y"
2503 * To find the span of the first argument, we find the first position
2504 * where the two arguments differ, which tells us that the first
2505 * argument formatted to "Susan & Fred". We then escape that
2506 * to "Susan & Fred" and join up with the intermediate portions
2507 * of the format string and the second argument to get
2508 * "Susan & Fred ate 5 apples".
2511 /* Create the two modified format strings
2513 format1 = g_string_new (NULL);
2514 format2 = g_string_new (NULL);
2519 const char *conv = find_conversion (p, &after);
2523 g_string_append_len (format1, conv, after - conv);
2524 g_string_append_c (format1, 'X');
2525 g_string_append_len (format2, conv, after - conv);
2526 g_string_append_c (format2, 'Y');
2531 /* Use them to format the arguments
2533 G_VA_COPY (args2, args);
2535 output1 = g_strdup_vprintf (format1->str, args);
2543 output2 = g_strdup_vprintf (format2->str, args2);
2547 result = g_string_new (NULL);
2549 /* Iterate through the original format string again,
2550 * copying the non-conversion portions and the escaped
2551 * converted arguments to the output string.
2559 const char *output_start;
2560 const char *conv = find_conversion (p, &after);
2563 if (!conv) /* The end, after points to the trailing \0 */
2565 g_string_append_len (result, p, after - p);
2569 g_string_append_len (result, p, conv - p);
2571 while (*op1 == *op2)
2577 escaped = g_markup_escape_text (output_start, op1 - output_start);
2578 g_string_append (result, escaped);
2587 g_string_free (format1, TRUE);
2588 g_string_free (format2, TRUE);
2593 return g_string_free (result, FALSE);
2598 #pragma GCC diagnostic pop
2601 * g_markup_printf_escaped:
2602 * @format: printf() style format string
2603 * @...: the arguments to insert in the format string
2605 * Formats arguments according to @format, escaping
2606 * all string and character arguments in the fashion
2607 * of g_markup_escape_text(). This is useful when you
2608 * want to insert literal strings into XML-style markup
2609 * output, without having to worry that the strings
2610 * might themselves contain markup.
2612 * |[<!-- language="C" -->
2613 * const char *store = "Fortnum & Mason";
2614 * const char *item = "Tea";
2617 * output = g_markup_printf_escaped ("<purchase>"
2618 * "<store>%s</store>"
2624 * Returns: newly allocated result from formatting
2625 * operation. Free with g_free().
2630 g_markup_printf_escaped (const gchar *format, ...)
2635 va_start (args, format);
2636 result = g_markup_vprintf_escaped (format, args);
2643 g_markup_parse_boolean (const char *string,
2646 char const * const falses[] = { "false", "f", "no", "n", "0" };
2647 char const * const trues[] = { "true", "t", "yes", "y", "1" };
2650 for (i = 0; i < G_N_ELEMENTS (falses); i++)
2652 if (g_ascii_strcasecmp (string, falses[i]) == 0)
2661 for (i = 0; i < G_N_ELEMENTS (trues); i++)
2663 if (g_ascii_strcasecmp (string, trues[i]) == 0)
2676 * GMarkupCollectType:
2677 * @G_MARKUP_COLLECT_INVALID: used to terminate the list of attributes
2679 * @G_MARKUP_COLLECT_STRING: collect the string pointer directly from
2680 * the attribute_values[] array. Expects a parameter of type (const
2681 * char **). If %G_MARKUP_COLLECT_OPTIONAL is specified and the
2682 * attribute isn't present then the pointer will be set to %NULL
2683 * @G_MARKUP_COLLECT_STRDUP: as with %G_MARKUP_COLLECT_STRING, but
2684 * expects a parameter of type (char **) and g_strdup()s the
2685 * returned pointer. The pointer must be freed with g_free()
2686 * @G_MARKUP_COLLECT_BOOLEAN: expects a parameter of type (gboolean *)
2687 * and parses the attribute value as a boolean. Sets %FALSE if the
2688 * attribute isn't present. Valid boolean values consist of
2689 * (case-insensitive) "false", "f", "no", "n", "0" and "true", "t",
2691 * @G_MARKUP_COLLECT_TRISTATE: as with %G_MARKUP_COLLECT_BOOLEAN, but
2692 * in the case of a missing attribute a value is set that compares
2693 * equal to neither %FALSE nor %TRUE G_MARKUP_COLLECT_OPTIONAL is
2695 * @G_MARKUP_COLLECT_OPTIONAL: can be bitwise ORed with the other fields.
2696 * If present, allows the attribute not to appear. A default value
2697 * is set depending on what value type is used
2699 * A mixed enumerated type and flags field. You must specify one type
2700 * (string, strdup, boolean, tristate). Additionally, you may optionally
2701 * bitwise OR the type with the flag %G_MARKUP_COLLECT_OPTIONAL.
2703 * It is likely that this enum will be extended in the future to
2704 * support other types.
2708 * g_markup_collect_attributes:
2709 * @element_name: the current tag name
2710 * @attribute_names: the attribute names
2711 * @attribute_values: the attribute values
2712 * @error: a pointer to a #GError or %NULL
2713 * @first_type: the #GMarkupCollectType of the first attribute
2714 * @first_attr: the name of the first attribute
2715 * @...: a pointer to the storage location of the first attribute
2716 * (or %NULL), followed by more types names and pointers, ending
2717 * with %G_MARKUP_COLLECT_INVALID
2719 * Collects the attributes of the element from the data passed to the
2720 * #GMarkupParser start_element function, dealing with common error
2721 * conditions and supporting boolean values.
2723 * This utility function is not required to write a parser but can save
2726 * The @element_name, @attribute_names, @attribute_values and @error
2727 * parameters passed to the start_element callback should be passed
2728 * unmodified to this function.
2730 * Following these arguments is a list of "supported" attributes to collect.
2731 * It is an error to specify multiple attributes with the same name. If any
2732 * attribute not in the list appears in the @attribute_names array then an
2733 * unknown attribute error will result.
2735 * The #GMarkupCollectType field allows specifying the type of collection
2736 * to perform and if a given attribute must appear or is optional.
2738 * The attribute name is simply the name of the attribute to collect.
2740 * The pointer should be of the appropriate type (see the descriptions
2741 * under #GMarkupCollectType) and may be %NULL in case a particular
2742 * attribute is to be allowed but ignored.
2744 * This function deals with issuing errors for missing attributes
2745 * (of type %G_MARKUP_ERROR_MISSING_ATTRIBUTE), unknown attributes
2746 * (of type %G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE) and duplicate
2747 * attributes (of type %G_MARKUP_ERROR_INVALID_CONTENT) as well
2748 * as parse errors for boolean-valued attributes (again of type
2749 * %G_MARKUP_ERROR_INVALID_CONTENT). In all of these cases %FALSE
2750 * will be returned and @error will be set as appropriate.
2752 * Returns: %TRUE if successful
2757 g_markup_collect_attributes (const gchar *element_name,
2758 const gchar **attribute_names,
2759 const gchar **attribute_values,
2761 GMarkupCollectType first_type,
2762 const gchar *first_attr,
2765 GMarkupCollectType type;
2777 va_start (ap, first_attr);
2778 while (type != G_MARKUP_COLLECT_INVALID)
2783 mandatory = !(type & G_MARKUP_COLLECT_OPTIONAL);
2784 type &= (G_MARKUP_COLLECT_OPTIONAL - 1);
2786 /* tristate records a value != TRUE and != FALSE
2787 * for the case where the attribute is missing
2789 if (type == G_MARKUP_COLLECT_TRISTATE)
2792 for (i = 0; attribute_names[i]; i++)
2793 if (i >= 40 || !(collected & (G_GUINT64_CONSTANT(1) << i)))
2794 if (!strcmp (attribute_names[i], attr))
2797 /* ISO C99 only promises that the user can pass up to 127 arguments.
2798 * Subtracting the first 4 arguments plus the final NULL and dividing
2799 * by 3 arguments per collected attribute, we are left with a maximum
2800 * number of supported attributes of (127 - 5) / 3 = 40.
2802 * In reality, nobody is ever going to call us with anywhere close to
2803 * 40 attributes to collect, so it is safe to assume that if i > 40
2804 * then the user has given some invalid or repeated arguments. These
2805 * problems will be caught and reported at the end of the function.
2807 * We know at this point that we have an error, but we don't know
2808 * what error it is, so just continue...
2811 collected |= (G_GUINT64_CONSTANT(1) << i);
2813 value = attribute_values[i];
2815 if (value == NULL && mandatory)
2817 g_set_error (error, G_MARKUP_ERROR,
2818 G_MARKUP_ERROR_MISSING_ATTRIBUTE,
2819 "element '%s' requires attribute '%s'",
2820 element_name, attr);
2828 case G_MARKUP_COLLECT_STRING:
2830 const char **str_ptr;
2832 str_ptr = va_arg (ap, const char **);
2834 if (str_ptr != NULL)
2839 case G_MARKUP_COLLECT_STRDUP:
2843 str_ptr = va_arg (ap, char **);
2845 if (str_ptr != NULL)
2846 *str_ptr = g_strdup (value);
2850 case G_MARKUP_COLLECT_BOOLEAN:
2851 case G_MARKUP_COLLECT_TRISTATE:
2856 bool_ptr = va_arg (ap, gboolean *);
2858 if (bool_ptr != NULL)
2860 if (type == G_MARKUP_COLLECT_TRISTATE)
2861 /* constructivists rejoice!
2862 * neither false nor true...
2866 else /* G_MARKUP_COLLECT_BOOLEAN */
2872 if (!g_markup_parse_boolean (value, va_arg (ap, gboolean *)))
2874 g_set_error (error, G_MARKUP_ERROR,
2875 G_MARKUP_ERROR_INVALID_CONTENT,
2876 "element '%s', attribute '%s', value '%s' "
2877 "cannot be parsed as a boolean value",
2878 element_name, attr, value);
2888 g_assert_not_reached ();
2892 type = va_arg (ap, GMarkupCollectType);
2893 if (type != G_MARKUP_COLLECT_INVALID)
2894 attr = va_arg (ap, const char *);
2898 /* ensure we collected all the arguments */
2899 for (i = 0; attribute_names[i]; i++)
2900 if ((collected & (G_GUINT64_CONSTANT(1) << i)) == 0)
2902 /* attribute not collected: could be caused by two things.
2904 * 1) it doesn't exist in our list of attributes
2905 * 2) it existed but was matched by a duplicate attribute earlier
2911 for (j = 0; j < i; j++)
2912 if (strcmp (attribute_names[i], attribute_names[j]) == 0)
2916 /* j is now the first occurrence of attribute_names[i] */
2918 g_set_error (error, G_MARKUP_ERROR,
2919 G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
2920 "attribute '%s' invalid for element '%s'",
2921 attribute_names[i], element_name);
2923 g_set_error (error, G_MARKUP_ERROR,
2924 G_MARKUP_ERROR_INVALID_CONTENT,
2925 "attribute '%s' given multiple times for element '%s'",
2926 attribute_names[i], element_name);
2934 /* replay the above to free allocations */
2937 va_start (ap, first_attr);
2938 while (type != G_MARKUP_COLLECT_INVALID)
2942 ptr = va_arg (ap, gpointer);
2946 switch (type & (G_MARKUP_COLLECT_OPTIONAL - 1))
2948 case G_MARKUP_COLLECT_STRDUP:
2950 g_free (*(char **) ptr);
2951 *(char **) ptr = NULL;
2954 case G_MARKUP_COLLECT_STRING:
2955 *(char **) ptr = NULL;
2958 case G_MARKUP_COLLECT_BOOLEAN:
2959 *(gboolean *) ptr = FALSE;
2962 case G_MARKUP_COLLECT_TRISTATE:
2963 *(gboolean *) ptr = -1;
2968 type = va_arg (ap, GMarkupCollectType);
2969 if (type != G_MARKUP_COLLECT_INVALID)
2971 attr = va_arg (ap, const char *);