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.
34 #include "gstrfuncs.h"
36 #include "gtestutils.h"
42 * @Title: Simple XML Subset Parser
43 * @Short_description: parses a subset of XML
44 * @See_also: <ulink url="http://www.w3.org/TR/REC-xml/">XML
45 * Specification</ulink>
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. However, it's very
51 * useful for application data files, config files, etc. where you
52 * know your application will be the only one writing the file.
53 * Full-scale XML parsers should be able to parse the subset used by
54 * GMarkup, so you can easily migrate to full-scale XML at a later
55 * time if the need arises.
57 * GMarkup is not guaranteed to signal an error on all invalid XML;
58 * the parser may accept documents that an XML parser would not.
59 * However, XML documents which are not well-formed<footnote
60 * id="wellformed">Being wellformed is a weaker condition than being
61 * valid. See the <ulink url="http://www.w3.org/TR/REC-xml/">XML
62 * specification</ulink> for definitions of these terms.</footnote>
63 * are not considered valid GMarkup documents.
65 * Simplifications to XML include:
67 * <listitem>Only UTF-8 encoding is allowed</listitem>
68 * <listitem>No user-defined entities</listitem>
69 * <listitem>Processing instructions, comments and the doctype declaration
70 * are "passed through" but are not interpreted in any way</listitem>
71 * <listitem>No DTD or validation.</listitem>
74 * The markup format does support:
76 * <listitem>Elements</listitem>
77 * <listitem>Attributes</listitem>
78 * <listitem>5 standard entities:
79 * <literal>&amp; &lt; &gt; &quot; &apos;</literal>
81 * <listitem>Character references</listitem>
82 * <listitem>Sections marked as CDATA</listitem>
86 G_DEFINE_QUARK (g-markup-error-quark, g_markup_error)
91 STATE_AFTER_OPEN_ANGLE,
92 STATE_AFTER_CLOSE_ANGLE,
93 STATE_AFTER_ELISION_SLASH, /* the slash that obviates need for end element */
94 STATE_INSIDE_OPEN_TAG_NAME,
95 STATE_INSIDE_ATTRIBUTE_NAME,
96 STATE_AFTER_ATTRIBUTE_NAME,
97 STATE_BETWEEN_ATTRIBUTES,
98 STATE_AFTER_ATTRIBUTE_EQUALS_SIGN,
99 STATE_INSIDE_ATTRIBUTE_VALUE_SQ,
100 STATE_INSIDE_ATTRIBUTE_VALUE_DQ,
102 STATE_AFTER_CLOSE_TAG_SLASH,
103 STATE_INSIDE_CLOSE_TAG_NAME,
104 STATE_AFTER_CLOSE_TAG_NAME,
105 STATE_INSIDE_PASSTHROUGH,
111 const char *prev_element;
112 const GMarkupParser *prev_parser;
113 gpointer prev_user_data;
114 } GMarkupRecursionTracker;
116 struct _GMarkupParseContext
118 const GMarkupParser *parser;
120 GMarkupParseFlags flags;
125 GMarkupParseState state;
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;
138 GSList *tag_stack_gstr;
139 GSList *spare_list_nodes;
141 GString **attr_names;
142 GString **attr_values;
146 const gchar *current_text;
147 gssize current_text_len;
148 const gchar *current_text_end;
150 /* used to save the start of the last interesting thingy */
155 guint document_empty : 1;
157 guint awaiting_pop : 1;
160 /* subparser support */
161 GSList *subparser_stack; /* (GMarkupRecursionTracker *) */
162 const char *subparser_element;
163 gpointer held_user_data;
167 * Helpers to reduce our allocation overhead, we have
168 * a well defined allocation lifecycle.
171 get_list_node (GMarkupParseContext *context, gpointer data)
174 if (context->spare_list_nodes != NULL)
176 node = context->spare_list_nodes;
177 context->spare_list_nodes = g_slist_remove_link (context->spare_list_nodes, node);
180 node = g_slist_alloc();
186 free_list_node (GMarkupParseContext *context, GSList *node)
189 context->spare_list_nodes = g_slist_concat (node, context->spare_list_nodes);
193 string_blank (GString *string)
195 string->str[0] = '\0';
200 * g_markup_parse_context_new:
201 * @parser: a #GMarkupParser
202 * @flags: one or more #GMarkupParseFlags
203 * @user_data: user data to pass to #GMarkupParser functions
204 * @user_data_dnotify: user data destroy notifier called when
205 * the parse context is freed
207 * Creates a new parse context. A parse context is used to parse
208 * marked-up documents. You can feed any number of documents into
209 * a context, as long as no errors occur; once an error occurs,
210 * the parse context can't continue to parse text (you have to
211 * free it and create a new parse context).
213 * Return value: a new #GMarkupParseContext
215 GMarkupParseContext *
216 g_markup_parse_context_new (const GMarkupParser *parser,
217 GMarkupParseFlags flags,
219 GDestroyNotify user_data_dnotify)
221 GMarkupParseContext *context;
223 g_return_val_if_fail (parser != NULL, NULL);
225 context = g_new (GMarkupParseContext, 1);
227 context->parser = parser;
228 context->flags = flags;
229 context->user_data = user_data;
230 context->dnotify = user_data_dnotify;
232 context->line_number = 1;
233 context->char_number = 1;
235 context->partial_chunk = NULL;
236 context->spare_chunks = NULL;
237 context->spare_list_nodes = NULL;
239 context->state = STATE_START;
240 context->tag_stack = NULL;
241 context->tag_stack_gstr = NULL;
242 context->attr_names = NULL;
243 context->attr_values = NULL;
244 context->cur_attr = -1;
245 context->alloc_attrs = 0;
247 context->current_text = NULL;
248 context->current_text_len = -1;
249 context->current_text_end = NULL;
251 context->start = NULL;
252 context->iter = NULL;
254 context->document_empty = TRUE;
255 context->parsing = FALSE;
257 context->awaiting_pop = FALSE;
258 context->subparser_stack = NULL;
259 context->subparser_element = NULL;
261 /* this is only looked at if awaiting_pop = TRUE. initialise anyway. */
262 context->held_user_data = NULL;
264 context->balance = 0;
270 string_full_free (gpointer ptr)
272 g_string_free (ptr, TRUE);
275 static void clear_attributes (GMarkupParseContext *context);
278 * g_markup_parse_context_free:
279 * @context: a #GMarkupParseContext
281 * Frees a #GMarkupParseContext.
283 * This function can't be called from inside one of the
284 * #GMarkupParser functions or while a subparser is pushed.
287 g_markup_parse_context_free (GMarkupParseContext *context)
289 g_return_if_fail (context != NULL);
290 g_return_if_fail (!context->parsing);
291 g_return_if_fail (!context->subparser_stack);
292 g_return_if_fail (!context->awaiting_pop);
294 if (context->dnotify)
295 (* context->dnotify) (context->user_data);
297 clear_attributes (context);
298 g_free (context->attr_names);
299 g_free (context->attr_values);
301 g_slist_free_full (context->tag_stack_gstr, string_full_free);
302 g_slist_free (context->tag_stack);
304 g_slist_free_full (context->spare_chunks, string_full_free);
305 g_slist_free (context->spare_list_nodes);
307 if (context->partial_chunk)
308 g_string_free (context->partial_chunk, TRUE);
313 static void pop_subparser_stack (GMarkupParseContext *context);
316 mark_error (GMarkupParseContext *context,
319 context->state = STATE_ERROR;
321 if (context->parser->error)
322 (*context->parser->error) (context, error, context->user_data);
324 /* report the error all the way up to free all the user-data */
325 while (context->subparser_stack)
327 pop_subparser_stack (context);
328 context->awaiting_pop = FALSE; /* already been freed */
330 if (context->parser->error)
331 (*context->parser->error) (context, error, context->user_data);
336 set_error (GMarkupParseContext *context,
340 ...) G_GNUC_PRINTF (4, 5);
343 set_error_literal (GMarkupParseContext *context,
346 const gchar *message)
350 tmp_error = g_error_new_literal (G_MARKUP_ERROR, code, message);
352 g_prefix_error (&tmp_error,
353 _("Error on line %d char %d: "),
354 context->line_number,
355 context->char_number);
357 mark_error (context, tmp_error);
359 g_propagate_error (error, tmp_error);
363 set_error (GMarkupParseContext *context,
373 va_start (args, format);
374 s = g_strdup_vprintf (format, args);
377 /* Make sure that the GError message is valid UTF-8
378 * even if it is complaining about invalid UTF-8 in the markup
380 s_valid = _g_utf8_make_valid (s);
381 set_error_literal (context, error, code, s);
388 propagate_error (GMarkupParseContext *context,
392 if (context->flags & G_MARKUP_PREFIX_ERROR_POSITION)
393 g_prefix_error (&src,
394 _("Error on line %d char %d: "),
395 context->line_number,
396 context->char_number);
398 mark_error (context, src);
400 g_propagate_error (dest, src);
403 #define IS_COMMON_NAME_END_CHAR(c) \
404 ((c) == '=' || (c) == '/' || (c) == '>' || (c) == ' ')
407 slow_name_validate (GMarkupParseContext *context,
411 const gchar *p = name;
413 if (!g_utf8_validate (name, strlen (name), NULL))
415 set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
416 _("Invalid UTF-8 encoded text in name - not valid '%s'"), name);
420 if (!(g_ascii_isalpha (*p) ||
421 (!IS_COMMON_NAME_END_CHAR (*p) &&
424 g_unichar_isalpha (g_utf8_get_char (p))))))
426 set_error (context, error, G_MARKUP_ERROR_PARSE,
427 _("'%s' is not a valid name"), name);
431 for (p = g_utf8_next_char (name); *p != '\0'; p = g_utf8_next_char (p))
434 if (!(g_ascii_isalnum (*p) ||
435 (!IS_COMMON_NAME_END_CHAR (*p) &&
440 g_unichar_isalpha (g_utf8_get_char (p))))))
442 set_error (context, error, G_MARKUP_ERROR_PARSE,
443 _("'%s' is not a valid name: '%c'"), name, *p);
451 * Use me for elements, attributes etc.
454 name_validate (GMarkupParseContext *context,
461 /* name start char */
463 if (G_UNLIKELY (IS_COMMON_NAME_END_CHAR (*p) ||
464 !(g_ascii_isalpha (*p) || *p == '_' || *p == ':')))
467 for (mask = *p++; *p != '\0'; p++)
472 if (G_UNLIKELY (!(g_ascii_isalnum (*p) ||
473 (!IS_COMMON_NAME_END_CHAR (*p) &&
481 if (mask & 0x80) /* un-common / non-ascii */
487 return slow_name_validate (context, name, error);
491 text_validate (GMarkupParseContext *context,
496 if (!g_utf8_validate (p, len, NULL))
498 set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
499 _("Invalid UTF-8 encoded text in name - not valid '%s'"), p);
507 char_str (gunichar c,
511 g_unichar_to_utf8 (c, buf);
516 utf8_str (const gchar *utf8,
519 char_str (g_utf8_get_char (utf8), buf);
524 set_unescape_error (GMarkupParseContext *context,
526 const gchar *remaining_text,
534 gint remaining_newlines;
537 remaining_newlines = 0;
542 ++remaining_newlines;
546 va_start (args, format);
547 s = g_strdup_vprintf (format, args);
550 tmp_error = g_error_new (G_MARKUP_ERROR,
552 _("Error on line %d: %s"),
553 context->line_number - remaining_newlines,
558 mark_error (context, tmp_error);
560 g_propagate_error (error, tmp_error);
564 * re-write the GString in-place, unescaping anything that escaped.
565 * most XML does not contain entities, or escaping.
568 unescape_gstring_inplace (GMarkupParseContext *context,
576 gboolean normalize_attribute;
580 /* are we unescaping an attribute or not ? */
581 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
582 context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
583 normalize_attribute = TRUE;
585 normalize_attribute = FALSE;
588 * Meeks' theorum: unescaping can only shrink text.
589 * for < etc. this is obvious, for  more
590 * thought is required, but this is patently so.
593 for (from = to = string->str; *from != '\0'; from++, to++)
600 if (normalize_attribute && (*to == '\t' || *to == '\n'))
604 *to = normalize_attribute ? ' ' : '\n';
613 gboolean is_hex = FALSE;
625 /* digit is between start and p */
628 l = strtoul (from, &end, 16);
630 l = strtoul (from, &end, 10);
632 if (end == from || errno != 0)
634 set_unescape_error (context, error,
635 from, G_MARKUP_ERROR_PARSE,
636 _("Failed to parse '%-.*s', which "
637 "should have been a digit "
638 "inside a character reference "
639 "(ê for example) - perhaps "
640 "the digit is too large"),
644 else if (*end != ';')
646 set_unescape_error (context, error,
647 from, G_MARKUP_ERROR_PARSE,
648 _("Character reference did not end with a "
650 "most likely you used an ampersand "
651 "character without intending to start "
652 "an entity - escape ampersand as &"));
657 /* characters XML 1.1 permits */
658 if ((0 < l && l <= 0xD7FF) ||
659 (0xE000 <= l && l <= 0xFFFD) ||
660 (0x10000 <= l && l <= 0x10FFFF))
665 to += strlen (buf) - 1;
667 if (l >= 0x80) /* not ascii */
672 set_unescape_error (context, error,
673 from, G_MARKUP_ERROR_PARSE,
674 _("Character reference '%-.*s' does not "
675 "encode a permitted character"),
682 else if (strncmp (from, "lt;", 3) == 0)
687 else if (strncmp (from, "gt;", 3) == 0)
692 else if (strncmp (from, "amp;", 4) == 0)
697 else if (strncmp (from, "quot;", 5) == 0)
702 else if (strncmp (from, "apos;", 5) == 0)
710 set_unescape_error (context, error,
711 from, G_MARKUP_ERROR_PARSE,
712 _("Empty entity '&;' seen; valid "
713 "entities are: & " < > '"));
716 const char *end = strchr (from, ';');
718 set_unescape_error (context, error,
719 from, G_MARKUP_ERROR_PARSE,
720 _("Entity name '%-.*s' is not known"),
723 set_unescape_error (context, error,
724 from, G_MARKUP_ERROR_PARSE,
725 _("Entity did not end with a semicolon; "
726 "most likely you used an ampersand "
727 "character without intending to start "
728 "an entity - escape ampersand as &"));
735 g_assert (to - string->str <= string->len);
736 if (to - string->str != string->len)
737 g_string_truncate (string, to - string->str);
739 *is_ascii = !(mask & 0x80);
744 static inline gboolean
745 advance_char (GMarkupParseContext *context)
748 context->char_number++;
750 if (G_UNLIKELY (context->iter == context->current_text_end))
753 else if (G_UNLIKELY (*context->iter == '\n'))
755 context->line_number++;
756 context->char_number = 1;
762 static inline gboolean
765 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
769 skip_spaces (GMarkupParseContext *context)
773 if (!xml_isspace (*context->iter))
776 while (advance_char (context));
780 advance_to_name_end (GMarkupParseContext *context)
784 if (IS_COMMON_NAME_END_CHAR (*(context->iter)))
786 if (xml_isspace (*(context->iter)))
789 while (advance_char (context));
793 release_chunk (GMarkupParseContext *context, GString *str)
798 if (str->allocated_len > 256)
799 { /* large strings are unusual and worth freeing */
800 g_string_free (str, TRUE);
804 node = get_list_node (context, str);
805 context->spare_chunks = g_slist_concat (node, context->spare_chunks);
809 add_to_partial (GMarkupParseContext *context,
810 const gchar *text_start,
811 const gchar *text_end)
813 if (context->partial_chunk == NULL)
814 { /* allocate a new chunk to parse into */
816 if (context->spare_chunks != NULL)
818 GSList *node = context->spare_chunks;
819 context->spare_chunks = g_slist_remove_link (context->spare_chunks, node);
820 context->partial_chunk = node->data;
821 free_list_node (context, node);
824 context->partial_chunk = g_string_sized_new (MAX (28, text_end - text_start));
827 if (text_start != text_end)
828 g_string_insert_len (context->partial_chunk, -1,
829 text_start, text_end - text_start);
833 truncate_partial (GMarkupParseContext *context)
835 if (context->partial_chunk != NULL)
836 string_blank (context->partial_chunk);
839 static inline const gchar*
840 current_element (GMarkupParseContext *context)
842 return context->tag_stack->data;
846 pop_subparser_stack (GMarkupParseContext *context)
848 GMarkupRecursionTracker *tracker;
850 g_assert (context->subparser_stack);
852 tracker = context->subparser_stack->data;
854 context->awaiting_pop = TRUE;
855 context->held_user_data = context->user_data;
857 context->user_data = tracker->prev_user_data;
858 context->parser = tracker->prev_parser;
859 context->subparser_element = tracker->prev_element;
860 g_slice_free (GMarkupRecursionTracker, tracker);
862 context->subparser_stack = g_slist_delete_link (context->subparser_stack,
863 context->subparser_stack);
867 push_partial_as_tag (GMarkupParseContext *context)
869 GString *str = context->partial_chunk;
870 /* sadly, this is exported by gmarkup_get_element_stack as-is */
871 context->tag_stack = g_slist_concat (get_list_node (context, str->str), context->tag_stack);
872 context->tag_stack_gstr = g_slist_concat (get_list_node (context, str), context->tag_stack_gstr);
873 context->partial_chunk = NULL;
877 pop_tag (GMarkupParseContext *context)
879 GSList *nodea, *nodeb;
881 nodea = context->tag_stack;
882 nodeb = context->tag_stack_gstr;
883 release_chunk (context, nodeb->data);
884 context->tag_stack = g_slist_remove_link (context->tag_stack, nodea);
885 context->tag_stack_gstr = g_slist_remove_link (context->tag_stack_gstr, nodeb);
886 free_list_node (context, nodea);
887 free_list_node (context, nodeb);
891 possibly_finish_subparser (GMarkupParseContext *context)
893 if (current_element (context) == context->subparser_element)
894 pop_subparser_stack (context);
898 ensure_no_outstanding_subparser (GMarkupParseContext *context)
900 if (context->awaiting_pop)
901 g_critical ("During the first end_element call after invoking a "
902 "subparser you must pop the subparser stack and handle "
903 "the freeing of the subparser user_data. This can be "
904 "done by calling the end function of the subparser. "
905 "Very probably, your program just leaked memory.");
907 /* let valgrind watch the pointer disappear... */
908 context->held_user_data = NULL;
909 context->awaiting_pop = FALSE;
913 current_attribute (GMarkupParseContext *context)
915 g_assert (context->cur_attr >= 0);
916 return context->attr_names[context->cur_attr]->str;
920 add_attribute (GMarkupParseContext *context, GString *str)
922 if (context->cur_attr + 2 >= context->alloc_attrs)
924 context->alloc_attrs += 5; /* silly magic number */
925 context->attr_names = g_realloc (context->attr_names, sizeof(GString*)*context->alloc_attrs);
926 context->attr_values = g_realloc (context->attr_values, sizeof(GString*)*context->alloc_attrs);
929 context->attr_names[context->cur_attr] = str;
930 context->attr_values[context->cur_attr] = NULL;
931 context->attr_names[context->cur_attr+1] = NULL;
932 context->attr_values[context->cur_attr+1] = NULL;
936 clear_attributes (GMarkupParseContext *context)
938 /* Go ahead and free the attributes. */
939 for (; context->cur_attr >= 0; context->cur_attr--)
941 int pos = context->cur_attr;
942 release_chunk (context, context->attr_names[pos]);
943 release_chunk (context, context->attr_values[pos]);
944 context->attr_names[pos] = context->attr_values[pos] = NULL;
946 g_assert (context->cur_attr == -1);
947 g_assert (context->attr_names == NULL ||
948 context->attr_names[0] == NULL);
949 g_assert (context->attr_values == NULL ||
950 context->attr_values[0] == NULL);
953 /* This has to be a separate function to ensure the alloca's
954 * are unwound on exit - otherwise we grow & blow the stack
955 * with large documents
958 emit_start_element (GMarkupParseContext *context,
962 const gchar *start_name;
963 const gchar **attr_names;
964 const gchar **attr_values;
967 attr_names = g_newa (const gchar *, context->cur_attr + 2);
968 attr_values = g_newa (const gchar *, context->cur_attr + 2);
969 for (i = 0; i < context->cur_attr + 1; i++)
971 attr_names[i] = context->attr_names[i]->str;
972 attr_values[i] = context->attr_values[i]->str;
974 attr_names[i] = NULL;
975 attr_values[i] = NULL;
977 /* Call user callback for element start */
979 start_name = current_element (context);
981 if (context->parser->start_element &&
982 name_validate (context, start_name, error))
983 (* context->parser->start_element) (context,
985 (const gchar **)attr_names,
986 (const gchar **)attr_values,
989 clear_attributes (context);
991 if (tmp_error != NULL)
992 propagate_error (context, error, tmp_error);
996 * g_markup_parse_context_parse:
997 * @context: a #GMarkupParseContext
998 * @text: chunk of text to parse
999 * @text_len: length of @text in bytes
1000 * @error: return location for a #GError
1002 * Feed some data to the #GMarkupParseContext.
1004 * The data need not be valid UTF-8; an error will be signaled if
1005 * it's invalid. The data need not be an entire document; you can
1006 * feed a document into the parser incrementally, via multiple calls
1007 * to this function. Typically, as you receive data from a network
1008 * connection or file, you feed each received chunk of data into this
1009 * function, aborting the process if an error occurs. Once an error
1010 * is reported, no further data may be fed to the #GMarkupParseContext;
1011 * all errors are fatal.
1013 * Return value: %FALSE if an error occurred, %TRUE on success
1016 g_markup_parse_context_parse (GMarkupParseContext *context,
1021 g_return_val_if_fail (context != NULL, FALSE);
1022 g_return_val_if_fail (text != NULL, FALSE);
1023 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1024 g_return_val_if_fail (!context->parsing, FALSE);
1027 text_len = strlen (text);
1032 context->parsing = TRUE;
1035 context->current_text = text;
1036 context->current_text_len = text_len;
1037 context->current_text_end = context->current_text + text_len;
1038 context->iter = context->current_text;
1039 context->start = context->iter;
1041 while (context->iter != context->current_text_end)
1043 switch (context->state)
1046 /* Possible next state: AFTER_OPEN_ANGLE */
1048 g_assert (context->tag_stack == NULL);
1050 /* whitespace is ignored outside of any elements */
1051 skip_spaces (context);
1053 if (context->iter != context->current_text_end)
1055 if (*context->iter == '<')
1057 /* Move after the open angle */
1058 advance_char (context);
1060 context->state = STATE_AFTER_OPEN_ANGLE;
1062 /* this could start a passthrough */
1063 context->start = context->iter;
1065 /* document is now non-empty */
1066 context->document_empty = FALSE;
1070 set_error_literal (context,
1072 G_MARKUP_ERROR_PARSE,
1073 _("Document must begin with an element (e.g. <book>)"));
1078 case STATE_AFTER_OPEN_ANGLE:
1079 /* Possible next states: INSIDE_OPEN_TAG_NAME,
1080 * AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1082 if (*context->iter == '?' ||
1083 *context->iter == '!')
1085 /* include < in the passthrough */
1086 const gchar *openangle = "<";
1087 add_to_partial (context, openangle, openangle + 1);
1088 context->start = context->iter;
1089 context->balance = 1;
1090 context->state = STATE_INSIDE_PASSTHROUGH;
1092 else if (*context->iter == '/')
1095 advance_char (context);
1097 context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1099 else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1101 context->state = STATE_INSIDE_OPEN_TAG_NAME;
1103 /* start of tag name */
1104 context->start = context->iter;
1112 G_MARKUP_ERROR_PARSE,
1113 _("'%s' is not a valid character following "
1114 "a '<' character; it may not begin an "
1116 utf8_str (context->iter, buf));
1120 /* The AFTER_CLOSE_ANGLE state is actually sort of
1121 * broken, because it doesn't correspond to a range
1122 * of characters in the input stream as the others do,
1123 * and thus makes things harder to conceptualize
1125 case STATE_AFTER_CLOSE_ANGLE:
1126 /* Possible next states: INSIDE_TEXT, STATE_START */
1127 if (context->tag_stack == NULL)
1129 context->start = NULL;
1130 context->state = STATE_START;
1134 context->start = context->iter;
1135 context->state = STATE_INSIDE_TEXT;
1139 case STATE_AFTER_ELISION_SLASH:
1140 /* Possible next state: AFTER_CLOSE_ANGLE */
1143 /* We need to pop the tag stack and call the end_element
1144 * function, since this is the close tag
1146 GError *tmp_error = NULL;
1148 g_assert (context->tag_stack != NULL);
1150 possibly_finish_subparser (context);
1153 if (context->parser->end_element)
1154 (* context->parser->end_element) (context,
1155 current_element (context),
1159 ensure_no_outstanding_subparser (context);
1163 mark_error (context, tmp_error);
1164 g_propagate_error (error, tmp_error);
1168 if (*context->iter == '>')
1170 /* move after the close angle */
1171 advance_char (context);
1172 context->state = STATE_AFTER_CLOSE_ANGLE;
1180 G_MARKUP_ERROR_PARSE,
1181 _("Odd character '%s', expected a '>' character "
1182 "to end the empty-element tag '%s'"),
1183 utf8_str (context->iter, buf),
1184 current_element (context));
1191 case STATE_INSIDE_OPEN_TAG_NAME:
1192 /* Possible next states: BETWEEN_ATTRIBUTES */
1194 /* if there's a partial chunk then it's the first part of the
1195 * tag name. If there's a context->start then it's the start
1196 * of the tag name in current_text, the partial chunk goes
1197 * before that start though.
1199 advance_to_name_end (context);
1201 if (context->iter == context->current_text_end)
1203 /* The name hasn't necessarily ended. Merge with
1204 * partial chunk, leave state unchanged.
1206 add_to_partial (context, context->start, context->iter);
1210 /* The name has ended. Combine it with the partial chunk
1211 * if any; push it on the stack; enter next state.
1213 add_to_partial (context, context->start, context->iter);
1214 push_partial_as_tag (context);
1216 context->state = STATE_BETWEEN_ATTRIBUTES;
1217 context->start = NULL;
1221 case STATE_INSIDE_ATTRIBUTE_NAME:
1222 /* Possible next states: AFTER_ATTRIBUTE_NAME */
1224 advance_to_name_end (context);
1225 add_to_partial (context, context->start, context->iter);
1227 /* read the full name, if we enter the equals sign state
1228 * then add the attribute to the list (without the value),
1229 * otherwise store a partial chunk to be prepended later.
1231 if (context->iter != context->current_text_end)
1232 context->state = STATE_AFTER_ATTRIBUTE_NAME;
1235 case STATE_AFTER_ATTRIBUTE_NAME:
1236 /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1238 skip_spaces (context);
1240 if (context->iter != context->current_text_end)
1242 /* The name has ended. Combine it with the partial chunk
1243 * if any; push it on the stack; enter next state.
1245 if (!name_validate (context, context->partial_chunk->str, error))
1248 add_attribute (context, context->partial_chunk);
1250 context->partial_chunk = NULL;
1251 context->start = NULL;
1253 if (*context->iter == '=')
1255 advance_char (context);
1256 context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1264 G_MARKUP_ERROR_PARSE,
1265 _("Odd character '%s', expected a '=' after "
1266 "attribute name '%s' of element '%s'"),
1267 utf8_str (context->iter, buf),
1268 current_attribute (context),
1269 current_element (context));
1275 case STATE_BETWEEN_ATTRIBUTES:
1276 /* Possible next states: AFTER_CLOSE_ANGLE,
1277 * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1279 skip_spaces (context);
1281 if (context->iter != context->current_text_end)
1283 if (*context->iter == '/')
1285 advance_char (context);
1286 context->state = STATE_AFTER_ELISION_SLASH;
1288 else if (*context->iter == '>')
1290 advance_char (context);
1291 context->state = STATE_AFTER_CLOSE_ANGLE;
1293 else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1295 context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1296 /* start of attribute name */
1297 context->start = context->iter;
1305 G_MARKUP_ERROR_PARSE,
1306 _("Odd character '%s', expected a '>' or '/' "
1307 "character to end the start tag of "
1308 "element '%s', or optionally an attribute; "
1309 "perhaps you used an invalid character in "
1310 "an attribute name"),
1311 utf8_str (context->iter, buf),
1312 current_element (context));
1315 /* If we're done with attributes, invoke
1316 * the start_element callback
1318 if (context->state == STATE_AFTER_ELISION_SLASH ||
1319 context->state == STATE_AFTER_CLOSE_ANGLE)
1320 emit_start_element (context, error);
1324 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1325 /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1327 skip_spaces (context);
1329 if (context->iter != context->current_text_end)
1331 if (*context->iter == '"')
1333 advance_char (context);
1334 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1335 context->start = context->iter;
1337 else if (*context->iter == '\'')
1339 advance_char (context);
1340 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1341 context->start = context->iter;
1349 G_MARKUP_ERROR_PARSE,
1350 _("Odd character '%s', expected an open quote mark "
1351 "after the equals sign when giving value for "
1352 "attribute '%s' of element '%s'"),
1353 utf8_str (context->iter, buf),
1354 current_attribute (context),
1355 current_element (context));
1360 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1361 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1362 /* Possible next states: BETWEEN_ATTRIBUTES */
1366 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ)
1377 if (*context->iter == delim)
1380 while (advance_char (context));
1382 if (context->iter == context->current_text_end)
1384 /* The value hasn't necessarily ended. Merge with
1385 * partial chunk, leave state unchanged.
1387 add_to_partial (context, context->start, context->iter);
1392 /* The value has ended at the quote mark. Combine it
1393 * with the partial chunk if any; set it for the current
1396 add_to_partial (context, context->start, context->iter);
1398 g_assert (context->cur_attr >= 0);
1400 if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1401 (is_ascii || text_validate (context, context->partial_chunk->str,
1402 context->partial_chunk->len, error)))
1404 /* success, advance past quote and set state. */
1405 context->attr_values[context->cur_attr] = context->partial_chunk;
1406 context->partial_chunk = NULL;
1407 advance_char (context);
1408 context->state = STATE_BETWEEN_ATTRIBUTES;
1409 context->start = NULL;
1412 truncate_partial (context);
1416 case STATE_INSIDE_TEXT:
1417 /* Possible next states: AFTER_OPEN_ANGLE */
1420 if (*context->iter == '<')
1423 while (advance_char (context));
1425 /* The text hasn't necessarily ended. Merge with
1426 * partial chunk, leave state unchanged.
1429 add_to_partial (context, context->start, context->iter);
1431 if (context->iter != context->current_text_end)
1435 /* The text has ended at the open angle. Call the text
1438 if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1439 (is_ascii || text_validate (context, context->partial_chunk->str,
1440 context->partial_chunk->len, error)))
1442 GError *tmp_error = NULL;
1444 if (context->parser->text)
1445 (*context->parser->text) (context,
1446 context->partial_chunk->str,
1447 context->partial_chunk->len,
1451 if (tmp_error == NULL)
1453 /* advance past open angle and set state. */
1454 advance_char (context);
1455 context->state = STATE_AFTER_OPEN_ANGLE;
1456 /* could begin a passthrough */
1457 context->start = context->iter;
1460 propagate_error (context, error, tmp_error);
1463 truncate_partial (context);
1467 case STATE_AFTER_CLOSE_TAG_SLASH:
1468 /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1469 if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1471 context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1473 /* start of tag name */
1474 context->start = context->iter;
1482 G_MARKUP_ERROR_PARSE,
1483 _("'%s' is not a valid character following "
1484 "the characters '</'; '%s' may not begin an "
1486 utf8_str (context->iter, buf),
1487 utf8_str (context->iter, buf));
1491 case STATE_INSIDE_CLOSE_TAG_NAME:
1492 /* Possible next state: AFTER_CLOSE_TAG_NAME */
1493 advance_to_name_end (context);
1494 add_to_partial (context, context->start, context->iter);
1496 if (context->iter != context->current_text_end)
1497 context->state = STATE_AFTER_CLOSE_TAG_NAME;
1500 case STATE_AFTER_CLOSE_TAG_NAME:
1501 /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1503 skip_spaces (context);
1505 if (context->iter != context->current_text_end)
1507 GString *close_name;
1509 close_name = context->partial_chunk;
1510 context->partial_chunk = NULL;
1512 if (*context->iter != '>')
1518 G_MARKUP_ERROR_PARSE,
1519 _("'%s' is not a valid character following "
1520 "the close element name '%s'; the allowed "
1521 "character is '>'"),
1522 utf8_str (context->iter, buf),
1525 else if (context->tag_stack == NULL)
1529 G_MARKUP_ERROR_PARSE,
1530 _("Element '%s' was closed, no element "
1531 "is currently open"),
1534 else if (strcmp (close_name->str, current_element (context)) != 0)
1538 G_MARKUP_ERROR_PARSE,
1539 _("Element '%s' was closed, but the currently "
1540 "open element is '%s'"),
1542 current_element (context));
1547 advance_char (context);
1548 context->state = STATE_AFTER_CLOSE_ANGLE;
1549 context->start = NULL;
1551 possibly_finish_subparser (context);
1553 /* call the end_element callback */
1555 if (context->parser->end_element)
1556 (* context->parser->end_element) (context,
1561 ensure_no_outstanding_subparser (context);
1565 propagate_error (context, error, tmp_error);
1567 context->partial_chunk = close_name;
1568 truncate_partial (context);
1572 case STATE_INSIDE_PASSTHROUGH:
1573 /* Possible next state: AFTER_CLOSE_ANGLE */
1576 if (*context->iter == '<')
1578 if (*context->iter == '>')
1584 add_to_partial (context, context->start, context->iter);
1585 context->start = context->iter;
1587 str = context->partial_chunk->str;
1588 len = context->partial_chunk->len;
1590 if (str[1] == '?' && str[len - 1] == '?')
1592 if (strncmp (str, "<!--", 4) == 0 &&
1593 strcmp (str + len - 2, "--") == 0)
1595 if (strncmp (str, "<![CDATA[", 9) == 0 &&
1596 strcmp (str + len - 2, "]]") == 0)
1598 if (strncmp (str, "<!DOCTYPE", 9) == 0 &&
1599 context->balance == 0)
1603 while (advance_char (context));
1605 if (context->iter == context->current_text_end)
1607 /* The passthrough hasn't necessarily ended. Merge with
1608 * partial chunk, leave state unchanged.
1610 add_to_partial (context, context->start, context->iter);
1614 /* The passthrough has ended at the close angle. Combine
1615 * it with the partial chunk if any. Call the passthrough
1616 * callback. Note that the open/close angles are
1617 * included in the text of the passthrough.
1619 GError *tmp_error = NULL;
1621 advance_char (context); /* advance past close angle */
1622 add_to_partial (context, context->start, context->iter);
1624 if (context->flags & G_MARKUP_TREAT_CDATA_AS_TEXT &&
1625 strncmp (context->partial_chunk->str, "<![CDATA[", 9) == 0)
1627 if (context->parser->text &&
1628 text_validate (context,
1629 context->partial_chunk->str + 9,
1630 context->partial_chunk->len - 12,
1632 (*context->parser->text) (context,
1633 context->partial_chunk->str + 9,
1634 context->partial_chunk->len - 12,
1638 else if (context->parser->passthrough &&
1639 text_validate (context,
1640 context->partial_chunk->str,
1641 context->partial_chunk->len,
1643 (*context->parser->passthrough) (context,
1644 context->partial_chunk->str,
1645 context->partial_chunk->len,
1649 truncate_partial (context);
1651 if (tmp_error == NULL)
1653 context->state = STATE_AFTER_CLOSE_ANGLE;
1654 context->start = context->iter; /* could begin text */
1657 propagate_error (context, error, tmp_error);
1666 g_assert_not_reached ();
1672 context->parsing = FALSE;
1674 return context->state != STATE_ERROR;
1678 * g_markup_parse_context_end_parse:
1679 * @context: a #GMarkupParseContext
1680 * @error: return location for a #GError
1682 * Signals to the #GMarkupParseContext that all data has been
1683 * fed into the parse context with g_markup_parse_context_parse().
1685 * This function reports an error if the document isn't complete,
1686 * for example if elements are still open.
1688 * Return value: %TRUE on success, %FALSE if an error was set
1691 g_markup_parse_context_end_parse (GMarkupParseContext *context,
1694 g_return_val_if_fail (context != NULL, FALSE);
1695 g_return_val_if_fail (!context->parsing, FALSE);
1696 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1698 if (context->partial_chunk != NULL)
1700 g_string_free (context->partial_chunk, TRUE);
1701 context->partial_chunk = NULL;
1704 if (context->document_empty)
1706 set_error_literal (context, error, G_MARKUP_ERROR_EMPTY,
1707 _("Document was empty or contained only whitespace"));
1711 context->parsing = TRUE;
1713 switch (context->state)
1719 case STATE_AFTER_OPEN_ANGLE:
1720 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1721 _("Document ended unexpectedly just after an open angle bracket '<'"));
1724 case STATE_AFTER_CLOSE_ANGLE:
1725 if (context->tag_stack != NULL)
1727 /* Error message the same as for INSIDE_TEXT */
1728 set_error (context, error, G_MARKUP_ERROR_PARSE,
1729 _("Document ended unexpectedly with elements still open - "
1730 "'%s' was the last element opened"),
1731 current_element (context));
1735 case STATE_AFTER_ELISION_SLASH:
1736 set_error (context, error, G_MARKUP_ERROR_PARSE,
1737 _("Document ended unexpectedly, expected to see a close angle "
1738 "bracket ending the tag <%s/>"), current_element (context));
1741 case STATE_INSIDE_OPEN_TAG_NAME:
1742 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1743 _("Document ended unexpectedly inside an element name"));
1746 case STATE_INSIDE_ATTRIBUTE_NAME:
1747 case STATE_AFTER_ATTRIBUTE_NAME:
1748 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1749 _("Document ended unexpectedly inside an attribute name"));
1752 case STATE_BETWEEN_ATTRIBUTES:
1753 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1754 _("Document ended unexpectedly inside an element-opening "
1758 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1759 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1760 _("Document ended unexpectedly after the equals sign "
1761 "following an attribute name; no attribute value"));
1764 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1765 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1766 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1767 _("Document ended unexpectedly while inside an attribute "
1771 case STATE_INSIDE_TEXT:
1772 g_assert (context->tag_stack != NULL);
1773 set_error (context, error, G_MARKUP_ERROR_PARSE,
1774 _("Document ended unexpectedly with elements still open - "
1775 "'%s' was the last element opened"),
1776 current_element (context));
1779 case STATE_AFTER_CLOSE_TAG_SLASH:
1780 case STATE_INSIDE_CLOSE_TAG_NAME:
1781 case STATE_AFTER_CLOSE_TAG_NAME:
1782 set_error (context, error, G_MARKUP_ERROR_PARSE,
1783 _("Document ended unexpectedly inside the close tag for "
1784 "element '%s'"), current_element (context));
1787 case STATE_INSIDE_PASSTHROUGH:
1788 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1789 _("Document ended unexpectedly inside a comment or "
1790 "processing instruction"));
1795 g_assert_not_reached ();
1799 context->parsing = FALSE;
1801 return context->state != STATE_ERROR;
1805 * g_markup_parse_context_get_element:
1806 * @context: a #GMarkupParseContext
1808 * Retrieves the name of the currently open element.
1810 * If called from the start_element or end_element handlers this will
1811 * give the element_name as passed to those functions. For the parent
1812 * elements, see g_markup_parse_context_get_element_stack().
1814 * Returns: the name of the currently open element, or %NULL
1819 g_markup_parse_context_get_element (GMarkupParseContext *context)
1821 g_return_val_if_fail (context != NULL, NULL);
1823 if (context->tag_stack == NULL)
1826 return current_element (context);
1830 * g_markup_parse_context_get_element_stack:
1831 * @context: a #GMarkupParseContext
1833 * Retrieves the element stack from the internal state of the parser.
1835 * The returned #GSList is a list of strings where the first item is
1836 * the currently open tag (as would be returned by
1837 * g_markup_parse_context_get_element()) and the next item is its
1840 * This function is intended to be used in the start_element and
1841 * end_element handlers where g_markup_parse_context_get_element()
1842 * would merely return the name of the element that is being
1845 * Returns: the element stack, which must not be modified
1850 g_markup_parse_context_get_element_stack (GMarkupParseContext *context)
1852 g_return_val_if_fail (context != NULL, NULL);
1853 return context->tag_stack;
1857 * g_markup_parse_context_get_position:
1858 * @context: a #GMarkupParseContext
1859 * @line_number: (allow-none): return location for a line number, or %NULL
1860 * @char_number: (allow-none): return location for a char-on-line number, or %NULL
1862 * Retrieves the current line number and the number of the character on
1863 * that line. Intended for use in error messages; there are no strict
1864 * semantics for what constitutes the "current" line number other than
1865 * "the best number we could come up with for error messages."
1868 g_markup_parse_context_get_position (GMarkupParseContext *context,
1872 g_return_if_fail (context != NULL);
1875 *line_number = context->line_number;
1878 *char_number = context->char_number;
1882 * g_markup_parse_context_get_user_data:
1883 * @context: a #GMarkupParseContext
1885 * Returns the user_data associated with @context.
1887 * This will either be the user_data that was provided to
1888 * g_markup_parse_context_new() or to the most recent call
1889 * of g_markup_parse_context_push().
1891 * Returns: the provided user_data. The returned data belongs to
1892 * the markup context and will be freed when
1893 * g_markup_parse_context_free() is called.
1898 g_markup_parse_context_get_user_data (GMarkupParseContext *context)
1900 return context->user_data;
1904 * g_markup_parse_context_push:
1905 * @context: a #GMarkupParseContext
1906 * @parser: a #GMarkupParser
1907 * @user_data: user data to pass to #GMarkupParser functions
1909 * Temporarily redirects markup data to a sub-parser.
1911 * This function may only be called from the start_element handler of
1912 * a #GMarkupParser. It must be matched with a corresponding call to
1913 * g_markup_parse_context_pop() in the matching end_element handler
1914 * (except in the case that the parser aborts due to an error).
1916 * All tags, text and other data between the matching tags is
1917 * redirected to the subparser given by @parser. @user_data is used
1918 * as the user_data for that parser. @user_data is also passed to the
1919 * error callback in the event that an error occurs. This includes
1920 * errors that occur in subparsers of the subparser.
1922 * The end tag matching the start tag for which this call was made is
1923 * handled by the previous parser (which is given its own user_data)
1924 * which is why g_markup_parse_context_pop() is provided to allow "one
1925 * last access" to the @user_data provided to this function. In the
1926 * case of error, the @user_data provided here is passed directly to
1927 * the error callback of the subparser and g_markup_parse_context_pop()
1928 * should not be called. In either case, if @user_data was allocated
1929 * then it ought to be freed from both of these locations.
1931 * This function is not intended to be directly called by users
1932 * interested in invoking subparsers. Instead, it is intended to be
1933 * used by the subparsers themselves to implement a higher-level
1936 * As an example, see the following implementation of a simple
1937 * parser that counts the number of tags encountered.
1946 * counter_start_element (GMarkupParseContext *context,
1947 * const gchar *element_name,
1948 * const gchar **attribute_names,
1949 * const gchar **attribute_values,
1950 * gpointer user_data,
1953 * CounterData *data = user_data;
1955 * data->tag_count++;
1959 * counter_error (GMarkupParseContext *context,
1961 * gpointer user_data)
1963 * CounterData *data = user_data;
1965 * g_slice_free (CounterData, data);
1968 * static GMarkupParser counter_subparser =
1970 * counter_start_element,
1978 * In order to allow this parser to be easily used as a subparser, the
1979 * following interface is provided:
1983 * start_counting (GMarkupParseContext *context)
1985 * CounterData *data = g_slice_new (CounterData);
1987 * data->tag_count = 0;
1988 * g_markup_parse_context_push (context, &counter_subparser, data);
1992 * end_counting (GMarkupParseContext *context)
1994 * CounterData *data = g_markup_parse_context_pop (context);
1997 * result = data->tag_count;
1998 * g_slice_free (CounterData, data);
2004 * The subparser would then be used as follows:
2007 * static void start_element (context, element_name, ...)
2009 * if (strcmp (element_name, "count-these") == 0)
2010 * start_counting (context);
2012 * /* else, handle other tags... */
2015 * static void end_element (context, element_name, ...)
2017 * if (strcmp (element_name, "count-these") == 0)
2018 * g_print ("Counted %d tags\n", end_counting (context));
2020 * /* else, handle other tags... */
2027 g_markup_parse_context_push (GMarkupParseContext *context,
2028 const GMarkupParser *parser,
2031 GMarkupRecursionTracker *tracker;
2033 tracker = g_slice_new (GMarkupRecursionTracker);
2034 tracker->prev_element = context->subparser_element;
2035 tracker->prev_parser = context->parser;
2036 tracker->prev_user_data = context->user_data;
2038 context->subparser_element = current_element (context);
2039 context->parser = parser;
2040 context->user_data = user_data;
2042 context->subparser_stack = g_slist_prepend (context->subparser_stack,
2047 * g_markup_parse_context_pop:
2048 * @context: a #GMarkupParseContext
2050 * Completes the process of a temporary sub-parser redirection.
2052 * This function exists to collect the user_data allocated by a
2053 * matching call to g_markup_parse_context_push(). It must be called
2054 * in the end_element handler corresponding to the start_element
2055 * handler during which g_markup_parse_context_push() was called.
2056 * You must not call this function from the error callback -- the
2057 * @user_data is provided directly to the callback in that case.
2059 * This function is not intended to be directly called by users
2060 * interested in invoking subparsers. Instead, it is intended to
2061 * be used by the subparsers themselves to implement a higher-level
2064 * Returns: the user data passed to g_markup_parse_context_push()
2069 g_markup_parse_context_pop (GMarkupParseContext *context)
2073 if (!context->awaiting_pop)
2074 possibly_finish_subparser (context);
2076 g_assert (context->awaiting_pop);
2078 context->awaiting_pop = FALSE;
2080 /* valgrind friendliness */
2081 user_data = context->held_user_data;
2082 context->held_user_data = NULL;
2088 append_escaped_text (GString *str,
2097 end = text + length;
2102 next = g_utf8_next_char (p);
2107 g_string_append (str, "&");
2111 g_string_append (str, "<");
2115 g_string_append (str, ">");
2119 g_string_append (str, "'");
2123 g_string_append (str, """);
2127 c = g_utf8_get_char (p);
2128 if ((0x1 <= c && c <= 0x8) ||
2129 (0xb <= c && c <= 0xc) ||
2130 (0xe <= c && c <= 0x1f) ||
2131 (0x7f <= c && c <= 0x84) ||
2132 (0x86 <= c && c <= 0x9f))
2133 g_string_append_printf (str, "&#x%x;", c);
2135 g_string_append_len (str, p, next - p);
2144 * g_markup_escape_text:
2145 * @text: some valid UTF-8 text
2146 * @length: length of @text in bytes, or -1 if the text is nul-terminated
2148 * Escapes text so that the markup parser will parse it verbatim.
2149 * Less than, greater than, ampersand, etc. are replaced with the
2150 * corresponding entities. This function would typically be used
2151 * when writing out a file to be parsed with the markup parser.
2153 * Note that this function doesn't protect whitespace and line endings
2154 * from being processed according to the XML rules for normalization
2155 * of line endings and attribute values.
2157 * Note also that this function will produce character references in
2158 * the range of &#x1; ... &#x1f; for all control sequences
2159 * except for tabstop, newline and carriage return. The character
2160 * references in this range are not valid XML 1.0, but they are
2161 * valid XML 1.1 and will be accepted by the GMarkup parser.
2163 * Return value: a newly allocated string with the escaped text
2166 g_markup_escape_text (const gchar *text,
2171 g_return_val_if_fail (text != NULL, NULL);
2174 length = strlen (text);
2176 /* prealloc at least as long as original text */
2177 str = g_string_sized_new (length);
2178 append_escaped_text (str, text, length);
2180 return g_string_free (str, FALSE);
2185 * @format: a printf-style format string
2186 * @after: location to store a pointer to the character after
2187 * the returned conversion. On a %NULL return, returns the
2188 * pointer to the trailing NUL in the string
2190 * Find the next conversion in a printf-style format string.
2191 * Partially based on code from printf-parser.c,
2192 * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
2194 * Return value: pointer to the next conversion in @format,
2195 * or %NULL, if none.
2198 find_conversion (const char *format,
2201 const char *start = format;
2204 while (*start != '\0' && *start != '%')
2221 /* Test for positional argument. */
2222 if (*cp >= '0' && *cp <= '9')
2226 for (np = cp; *np >= '0' && *np <= '9'; np++)
2232 /* Skip the flags. */
2246 /* Skip the field width. */
2251 /* Test for positional argument. */
2252 if (*cp >= '0' && *cp <= '9')
2256 for (np = cp; *np >= '0' && *np <= '9'; np++)
2264 for (; *cp >= '0' && *cp <= '9'; cp++)
2268 /* Skip the precision. */
2274 /* Test for positional argument. */
2275 if (*cp >= '0' && *cp <= '9')
2279 for (np = cp; *np >= '0' && *np <= '9'; np++)
2287 for (; *cp >= '0' && *cp <= '9'; cp++)
2292 /* Skip argument type/size specifiers. */
2293 while (*cp == 'h' ||
2302 /* Skip the conversion character. */
2310 * g_markup_vprintf_escaped:
2311 * @format: printf() style format string
2312 * @args: variable argument list, similar to vprintf()
2314 * Formats the data in @args according to @format, escaping
2315 * all string and character arguments in the fashion
2316 * of g_markup_escape_text(). See g_markup_printf_escaped().
2318 * Return value: newly allocated result from formatting
2319 * operation. Free with g_free().
2324 g_markup_vprintf_escaped (const gchar *format,
2329 GString *result = NULL;
2330 gchar *output1 = NULL;
2331 gchar *output2 = NULL;
2332 const char *p, *op1, *op2;
2335 /* The technique here, is that we make two format strings that
2336 * have the identical conversions in the identical order to the
2337 * original strings, but differ in the text in-between. We
2338 * then use the normal g_strdup_vprintf() to format the arguments
2339 * with the two new format strings. By comparing the results,
2340 * we can figure out what segments of the output come from
2341 * the original format string, and what from the arguments,
2342 * and thus know what portions of the string to escape.
2344 * For instance, for:
2346 * g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2348 * We form the two format strings "%sX%dX" and %sY%sY". The results
2349 * of formatting with those two strings are
2351 * "%sX%dX" => "Susan & FredX5X"
2352 * "%sY%dY" => "Susan & FredY5Y"
2354 * To find the span of the first argument, we find the first position
2355 * where the two arguments differ, which tells us that the first
2356 * argument formatted to "Susan & Fred". We then escape that
2357 * to "Susan & Fred" and join up with the intermediate portions
2358 * of the format string and the second argument to get
2359 * "Susan & Fred ate 5 apples".
2362 /* Create the two modified format strings
2364 format1 = g_string_new (NULL);
2365 format2 = g_string_new (NULL);
2370 const char *conv = find_conversion (p, &after);
2374 g_string_append_len (format1, conv, after - conv);
2375 g_string_append_c (format1, 'X');
2376 g_string_append_len (format2, conv, after - conv);
2377 g_string_append_c (format2, 'Y');
2382 /* Use them to format the arguments
2384 G_VA_COPY (args2, args);
2386 output1 = g_strdup_vprintf (format1->str, args);
2393 output2 = g_strdup_vprintf (format2->str, args2);
2398 result = g_string_new (NULL);
2400 /* Iterate through the original format string again,
2401 * copying the non-conversion portions and the escaped
2402 * converted arguments to the output string.
2410 const char *output_start;
2411 const char *conv = find_conversion (p, &after);
2414 if (!conv) /* The end, after points to the trailing \0 */
2416 g_string_append_len (result, p, after - p);
2420 g_string_append_len (result, p, conv - p);
2422 while (*op1 == *op2)
2428 escaped = g_markup_escape_text (output_start, op1 - output_start);
2429 g_string_append (result, escaped);
2438 g_string_free (format1, TRUE);
2439 g_string_free (format2, TRUE);
2444 return g_string_free (result, FALSE);
2450 * g_markup_printf_escaped:
2451 * @format: printf() style format string
2452 * @...: the arguments to insert in the format string
2454 * Formats arguments according to @format, escaping
2455 * all string and character arguments in the fashion
2456 * of g_markup_escape_text(). This is useful when you
2457 * want to insert literal strings into XML-style markup
2458 * output, without having to worry that the strings
2459 * might themselves contain markup.
2462 * const char *store = "Fortnum & Mason";
2463 * const char *item = "Tea";
2466 * output = g_markup_printf_escaped ("<purchase>"
2467 * "<store>%s</store>"
2468 * "<item>%s</item>"
2469 * "</purchase>",
2473 * Return value: newly allocated result from formatting
2474 * operation. Free with g_free().
2479 g_markup_printf_escaped (const gchar *format, ...)
2484 va_start (args, format);
2485 result = g_markup_vprintf_escaped (format, args);
2492 g_markup_parse_boolean (const char *string,
2495 char const * const falses[] = { "false", "f", "no", "n", "0" };
2496 char const * const trues[] = { "true", "t", "yes", "y", "1" };
2499 for (i = 0; i < G_N_ELEMENTS (falses); i++)
2501 if (g_ascii_strcasecmp (string, falses[i]) == 0)
2510 for (i = 0; i < G_N_ELEMENTS (trues); i++)
2512 if (g_ascii_strcasecmp (string, trues[i]) == 0)
2525 * GMarkupCollectType:
2526 * @G_MARKUP_COLLECT_INVALID: used to terminate the list of attributes
2528 * @G_MARKUP_COLLECT_STRING: collect the string pointer directly from
2529 * the attribute_values[] array. Expects a parameter of type (const
2530 * char **). If %G_MARKUP_COLLECT_OPTIONAL is specified and the
2531 * attribute isn't present then the pointer will be set to %NULL
2532 * @G_MARKUP_COLLECT_STRDUP: as with %G_MARKUP_COLLECT_STRING, but
2533 * expects a parameter of type (char **) and g_strdup()s the
2534 * returned pointer. The pointer must be freed with g_free()
2535 * @G_MARKUP_COLLECT_BOOLEAN: expects a parameter of type (gboolean *)
2536 * and parses the attribute value as a boolean. Sets %FALSE if the
2537 * attribute isn't present. Valid boolean values consist of
2538 * (case-insensitive) "false", "f", "no", "n", "0" and "true", "t",
2540 * @G_MARKUP_COLLECT_TRISTATE: as with %G_MARKUP_COLLECT_BOOLEAN, but
2541 * in the case of a missing attribute a value is set that compares
2542 * equal to neither %FALSE nor %TRUE G_MARKUP_COLLECT_OPTIONAL is
2544 * @G_MARKUP_COLLECT_OPTIONAL: can be bitwise ORed with the other fields.
2545 * If present, allows the attribute not to appear. A default value
2546 * is set depending on what value type is used
2548 * A mixed enumerated type and flags field. You must specify one type
2549 * (string, strdup, boolean, tristate). Additionally, you may optionally
2550 * bitwise OR the type with the flag %G_MARKUP_COLLECT_OPTIONAL.
2552 * It is likely that this enum will be extended in the future to
2553 * support other types.
2557 * g_markup_collect_attributes:
2558 * @element_name: the current tag name
2559 * @attribute_names: the attribute names
2560 * @attribute_values: the attribute values
2561 * @error: a pointer to a #GError or %NULL
2562 * @first_type: the #GMarkupCollectType of the first attribute
2563 * @first_attr: the name of the first attribute
2564 * @...: a pointer to the storage location of the first attribute
2565 * (or %NULL), followed by more types names and pointers, ending
2566 * with %G_MARKUP_COLLECT_INVALID
2568 * Collects the attributes of the element from the data passed to the
2569 * #GMarkupParser start_element function, dealing with common error
2570 * conditions and supporting boolean values.
2572 * This utility function is not required to write a parser but can save
2575 * The @element_name, @attribute_names, @attribute_values and @error
2576 * parameters passed to the start_element callback should be passed
2577 * unmodified to this function.
2579 * Following these arguments is a list of "supported" attributes to collect.
2580 * It is an error to specify multiple attributes with the same name. If any
2581 * attribute not in the list appears in the @attribute_names array then an
2582 * unknown attribute error will result.
2584 * The #GMarkupCollectType field allows specifying the type of collection
2585 * to perform and if a given attribute must appear or is optional.
2587 * The attribute name is simply the name of the attribute to collect.
2589 * The pointer should be of the appropriate type (see the descriptions
2590 * under #GMarkupCollectType) and may be %NULL in case a particular
2591 * attribute is to be allowed but ignored.
2593 * This function deals with issuing errors for missing attributes
2594 * (of type %G_MARKUP_ERROR_MISSING_ATTRIBUTE), unknown attributes
2595 * (of type %G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE) and duplicate
2596 * attributes (of type %G_MARKUP_ERROR_INVALID_CONTENT) as well
2597 * as parse errors for boolean-valued attributes (again of type
2598 * %G_MARKUP_ERROR_INVALID_CONTENT). In all of these cases %FALSE
2599 * will be returned and @error will be set as appropriate.
2601 * Return value: %TRUE if successful
2606 g_markup_collect_attributes (const gchar *element_name,
2607 const gchar **attribute_names,
2608 const gchar **attribute_values,
2610 GMarkupCollectType first_type,
2611 const gchar *first_attr,
2614 GMarkupCollectType type;
2626 va_start (ap, first_attr);
2627 while (type != G_MARKUP_COLLECT_INVALID)
2632 mandatory = !(type & G_MARKUP_COLLECT_OPTIONAL);
2633 type &= (G_MARKUP_COLLECT_OPTIONAL - 1);
2635 /* tristate records a value != TRUE and != FALSE
2636 * for the case where the attribute is missing
2638 if (type == G_MARKUP_COLLECT_TRISTATE)
2641 for (i = 0; attribute_names[i]; i++)
2642 if (i >= 40 || !(collected & (G_GUINT64_CONSTANT(1) << i)))
2643 if (!strcmp (attribute_names[i], attr))
2646 /* ISO C99 only promises that the user can pass up to 127 arguments.
2647 * Subtracting the first 4 arguments plus the final NULL and dividing
2648 * by 3 arguments per collected attribute, we are left with a maximum
2649 * number of supported attributes of (127 - 5) / 3 = 40.
2651 * In reality, nobody is ever going to call us with anywhere close to
2652 * 40 attributes to collect, so it is safe to assume that if i > 40
2653 * then the user has given some invalid or repeated arguments. These
2654 * problems will be caught and reported at the end of the function.
2656 * We know at this point that we have an error, but we don't know
2657 * what error it is, so just continue...
2660 collected |= (G_GUINT64_CONSTANT(1) << i);
2662 value = attribute_values[i];
2664 if (value == NULL && mandatory)
2666 g_set_error (error, G_MARKUP_ERROR,
2667 G_MARKUP_ERROR_MISSING_ATTRIBUTE,
2668 "element '%s' requires attribute '%s'",
2669 element_name, attr);
2677 case G_MARKUP_COLLECT_STRING:
2679 const char **str_ptr;
2681 str_ptr = va_arg (ap, const char **);
2683 if (str_ptr != NULL)
2688 case G_MARKUP_COLLECT_STRDUP:
2692 str_ptr = va_arg (ap, char **);
2694 if (str_ptr != NULL)
2695 *str_ptr = g_strdup (value);
2699 case G_MARKUP_COLLECT_BOOLEAN:
2700 case G_MARKUP_COLLECT_TRISTATE:
2705 bool_ptr = va_arg (ap, gboolean *);
2707 if (bool_ptr != NULL)
2709 if (type == G_MARKUP_COLLECT_TRISTATE)
2710 /* constructivists rejoice!
2711 * neither false nor true...
2715 else /* G_MARKUP_COLLECT_BOOLEAN */
2721 if (!g_markup_parse_boolean (value, va_arg (ap, gboolean *)))
2723 g_set_error (error, G_MARKUP_ERROR,
2724 G_MARKUP_ERROR_INVALID_CONTENT,
2725 "element '%s', attribute '%s', value '%s' "
2726 "cannot be parsed as a boolean value",
2727 element_name, attr, value);
2737 g_assert_not_reached ();
2740 type = va_arg (ap, GMarkupCollectType);
2741 attr = va_arg (ap, const char *);
2746 /* ensure we collected all the arguments */
2747 for (i = 0; attribute_names[i]; i++)
2748 if ((collected & (G_GUINT64_CONSTANT(1) << i)) == 0)
2750 /* attribute not collected: could be caused by two things.
2752 * 1) it doesn't exist in our list of attributes
2753 * 2) it existed but was matched by a duplicate attribute earlier
2759 for (j = 0; j < i; j++)
2760 if (strcmp (attribute_names[i], attribute_names[j]) == 0)
2764 /* j is now the first occurrence of attribute_names[i] */
2766 g_set_error (error, G_MARKUP_ERROR,
2767 G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
2768 "attribute '%s' invalid for element '%s'",
2769 attribute_names[i], element_name);
2771 g_set_error (error, G_MARKUP_ERROR,
2772 G_MARKUP_ERROR_INVALID_CONTENT,
2773 "attribute '%s' given multiple times for element '%s'",
2774 attribute_names[i], element_name);
2782 /* replay the above to free allocations */
2786 va_start (ap, first_attr);
2787 while (type != G_MARKUP_COLLECT_INVALID)
2791 ptr = va_arg (ap, gpointer);
2795 switch (type & (G_MARKUP_COLLECT_OPTIONAL - 1))
2797 case G_MARKUP_COLLECT_STRDUP:
2799 g_free (*(char **) ptr);
2801 case G_MARKUP_COLLECT_STRING:
2802 *(char **) ptr = NULL;
2805 case G_MARKUP_COLLECT_BOOLEAN:
2806 *(gboolean *) ptr = FALSE;
2809 case G_MARKUP_COLLECT_TRISTATE:
2810 *(gboolean *) ptr = -1;
2815 type = va_arg (ap, GMarkupCollectType);
2816 attr = va_arg (ap, const char *);