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"
41 * @Title: Simple XML Subset Parser
42 * @Short_description: parses a subset of XML
43 * @See_also: <ulink url="http://www.w3.org/TR/REC-xml/">XML
44 * Specification</ulink>
46 * The "GMarkup" parser is intended to parse a simple markup format
47 * that's a subset of XML. This is a small, efficient, easy-to-use
48 * parser. It should not be used if you expect to interoperate with
49 * other applications generating full-scale XML. However, it's very
50 * useful for application data files, config files, etc. where you
51 * know your application will be the only one writing the file.
52 * Full-scale XML parsers should be able to parse the subset used by
53 * GMarkup, so you can easily migrate to full-scale XML at a later
54 * time if the need arises.
56 * GMarkup is not guaranteed to signal an error on all invalid XML;
57 * the parser may accept documents that an XML parser would not.
58 * However, XML documents which are not well-formed<footnote
59 * id="wellformed">Being wellformed is a weaker condition than being
60 * valid. See the <ulink url="http://www.w3.org/TR/REC-xml/">XML
61 * specification</ulink> for definitions of these terms.</footnote>
62 * are not considered valid GMarkup documents.
64 * Simplifications to XML include:
66 * <listitem>Only UTF-8 encoding is allowed</listitem>
67 * <listitem>No user-defined entities</listitem>
68 * <listitem>Processing instructions, comments and the doctype declaration
69 * are "passed through" but are not interpreted in any way</listitem>
70 * <listitem>No DTD or validation.</listitem>
73 * The markup format does support:
75 * <listitem>Elements</listitem>
76 * <listitem>Attributes</listitem>
77 * <listitem>5 standard entities:
78 * <literal>&amp; &lt; &gt; &quot; &apos;</literal>
80 * <listitem>Character references</listitem>
81 * <listitem>Sections marked as CDATA</listitem>
86 g_markup_error_quark (void)
88 return g_quark_from_static_string ("g-markup-error-quark");
94 STATE_AFTER_OPEN_ANGLE
,
95 STATE_AFTER_CLOSE_ANGLE
,
96 STATE_AFTER_ELISION_SLASH
, /* the slash that obviates need for end element */
97 STATE_INSIDE_OPEN_TAG_NAME
,
98 STATE_INSIDE_ATTRIBUTE_NAME
,
99 STATE_AFTER_ATTRIBUTE_NAME
,
100 STATE_BETWEEN_ATTRIBUTES
,
101 STATE_AFTER_ATTRIBUTE_EQUALS_SIGN
,
102 STATE_INSIDE_ATTRIBUTE_VALUE_SQ
,
103 STATE_INSIDE_ATTRIBUTE_VALUE_DQ
,
105 STATE_AFTER_CLOSE_TAG_SLASH
,
106 STATE_INSIDE_CLOSE_TAG_NAME
,
107 STATE_AFTER_CLOSE_TAG_NAME
,
108 STATE_INSIDE_PASSTHROUGH
,
114 const char *prev_element
;
115 const GMarkupParser
*prev_parser
;
116 gpointer prev_user_data
;
117 } GMarkupRecursionTracker
;
119 struct _GMarkupParseContext
121 const GMarkupParser
*parser
;
123 GMarkupParseFlags flags
;
128 GMarkupParseState state
;
131 GDestroyNotify dnotify
;
133 /* A piece of character data or an element that
134 * hasn't "ended" yet so we haven't yet called
135 * the callback for it.
137 GString
*partial_chunk
;
138 GSList
*spare_chunks
;
141 GSList
*tag_stack_gstr
;
142 GSList
*spare_list_nodes
;
144 GString
**attr_names
;
145 GString
**attr_values
;
149 const gchar
*current_text
;
150 gssize current_text_len
;
151 const gchar
*current_text_end
;
153 /* used to save the start of the last interesting thingy */
158 guint document_empty
: 1;
160 guint awaiting_pop
: 1;
163 /* subparser support */
164 GSList
*subparser_stack
; /* (GMarkupRecursionTracker *) */
165 const char *subparser_element
;
166 gpointer held_user_data
;
170 * Helpers to reduce our allocation overhead, we have
171 * a well defined allocation lifecycle.
174 get_list_node (GMarkupParseContext
*context
, gpointer data
)
177 if (context
->spare_list_nodes
!= NULL
)
179 node
= context
->spare_list_nodes
;
180 context
->spare_list_nodes
= g_slist_remove_link (context
->spare_list_nodes
, node
);
183 node
= g_slist_alloc();
189 free_list_node (GMarkupParseContext
*context
, GSList
*node
)
192 context
->spare_list_nodes
= g_slist_concat (node
, context
->spare_list_nodes
);
196 string_blank (GString
*string
)
198 string
->str
[0] = '\0';
203 * g_markup_parse_context_new:
204 * @parser: a #GMarkupParser
205 * @flags: one or more #GMarkupParseFlags
206 * @user_data: user data to pass to #GMarkupParser functions
207 * @user_data_dnotify: user data destroy notifier called when
208 * the parse context is freed
210 * Creates a new parse context. A parse context is used to parse
211 * marked-up documents. You can feed any number of documents into
212 * a context, as long as no errors occur; once an error occurs,
213 * the parse context can't continue to parse text (you have to
214 * free it and create a new parse context).
216 * Return value: a new #GMarkupParseContext
218 GMarkupParseContext
*
219 g_markup_parse_context_new (const GMarkupParser
*parser
,
220 GMarkupParseFlags flags
,
222 GDestroyNotify user_data_dnotify
)
224 GMarkupParseContext
*context
;
226 g_return_val_if_fail (parser
!= NULL
, NULL
);
228 context
= g_new (GMarkupParseContext
, 1);
230 context
->parser
= parser
;
231 context
->flags
= flags
;
232 context
->user_data
= user_data
;
233 context
->dnotify
= user_data_dnotify
;
235 context
->line_number
= 1;
236 context
->char_number
= 1;
238 context
->partial_chunk
= NULL
;
239 context
->spare_chunks
= NULL
;
240 context
->spare_list_nodes
= NULL
;
242 context
->state
= STATE_START
;
243 context
->tag_stack
= NULL
;
244 context
->tag_stack_gstr
= NULL
;
245 context
->attr_names
= NULL
;
246 context
->attr_values
= NULL
;
247 context
->cur_attr
= -1;
248 context
->alloc_attrs
= 0;
250 context
->current_text
= NULL
;
251 context
->current_text_len
= -1;
252 context
->current_text_end
= NULL
;
254 context
->start
= NULL
;
255 context
->iter
= NULL
;
257 context
->document_empty
= TRUE
;
258 context
->parsing
= FALSE
;
260 context
->awaiting_pop
= FALSE
;
261 context
->subparser_stack
= NULL
;
262 context
->subparser_element
= NULL
;
264 /* this is only looked at if awaiting_pop = TRUE. initialise anyway. */
265 context
->held_user_data
= NULL
;
267 context
->balance
= 0;
273 string_full_free (gpointer ptr
)
275 g_string_free (ptr
, TRUE
);
278 static void clear_attributes (GMarkupParseContext
*context
);
281 * g_markup_parse_context_free:
282 * @context: a #GMarkupParseContext
284 * Frees a #GMarkupParseContext.
286 * This function can't be called from inside one of the
287 * #GMarkupParser functions or while a subparser is pushed.
290 g_markup_parse_context_free (GMarkupParseContext
*context
)
292 g_return_if_fail (context
!= NULL
);
293 g_return_if_fail (!context
->parsing
);
294 g_return_if_fail (!context
->subparser_stack
);
295 g_return_if_fail (!context
->awaiting_pop
);
297 if (context
->dnotify
)
298 (* context
->dnotify
) (context
->user_data
);
300 clear_attributes (context
);
301 g_free (context
->attr_names
);
302 g_free (context
->attr_values
);
304 g_slist_free_full (context
->tag_stack_gstr
, string_full_free
);
305 g_slist_free (context
->tag_stack
);
307 g_slist_free_full (context
->spare_chunks
, string_full_free
);
308 g_slist_free (context
->spare_list_nodes
);
310 if (context
->partial_chunk
)
311 g_string_free (context
->partial_chunk
, TRUE
);
316 static void pop_subparser_stack (GMarkupParseContext
*context
);
319 mark_error (GMarkupParseContext
*context
,
322 context
->state
= STATE_ERROR
;
324 if (context
->parser
->error
)
325 (*context
->parser
->error
) (context
, error
, context
->user_data
);
327 /* report the error all the way up to free all the user-data */
328 while (context
->subparser_stack
)
330 pop_subparser_stack (context
);
331 context
->awaiting_pop
= FALSE
; /* already been freed */
333 if (context
->parser
->error
)
334 (*context
->parser
->error
) (context
, error
, context
->user_data
);
339 set_error (GMarkupParseContext
*context
,
343 ...) G_GNUC_PRINTF (4, 5);
346 set_error_literal (GMarkupParseContext
*context
,
349 const gchar
*message
)
353 tmp_error
= g_error_new_literal (G_MARKUP_ERROR
, code
, message
);
355 g_prefix_error (&tmp_error
,
356 _("Error on line %d char %d: "),
357 context
->line_number
,
358 context
->char_number
);
360 mark_error (context
, tmp_error
);
362 g_propagate_error (error
, tmp_error
);
366 set_error (GMarkupParseContext
*context
,
376 va_start (args
, format
);
377 s
= g_strdup_vprintf (format
, args
);
380 /* Make sure that the GError message is valid UTF-8
381 * even if it is complaining about invalid UTF-8 in the markup
383 s_valid
= _g_utf8_make_valid (s
);
384 set_error_literal (context
, error
, code
, s
);
391 propagate_error (GMarkupParseContext
*context
,
395 if (context
->flags
& G_MARKUP_PREFIX_ERROR_POSITION
)
396 g_prefix_error (&src
,
397 _("Error on line %d char %d: "),
398 context
->line_number
,
399 context
->char_number
);
401 mark_error (context
, src
);
403 g_propagate_error (dest
, src
);
406 #define IS_COMMON_NAME_END_CHAR(c) \
407 ((c) == '=' || (c) == '/' || (c) == '>' || (c) == ' ')
410 slow_name_validate (GMarkupParseContext
*context
,
414 const gchar
*p
= name
;
416 if (!g_utf8_validate (name
, strlen (name
), NULL
))
418 set_error (context
, error
, G_MARKUP_ERROR_BAD_UTF8
,
419 _("Invalid UTF-8 encoded text in name - not valid '%s'"), name
);
423 if (!(g_ascii_isalpha (*p
) ||
424 (!IS_COMMON_NAME_END_CHAR (*p
) &&
427 g_unichar_isalpha (g_utf8_get_char (p
))))))
429 set_error (context
, error
, G_MARKUP_ERROR_PARSE
,
430 _("'%s' is not a valid name "), name
);
434 for (p
= g_utf8_next_char (name
); *p
!= '\0'; p
= g_utf8_next_char (p
))
437 if (!(g_ascii_isalnum (*p
) ||
438 (!IS_COMMON_NAME_END_CHAR (*p
) &&
443 g_unichar_isalpha (g_utf8_get_char (p
))))))
445 set_error (context
, error
, G_MARKUP_ERROR_PARSE
,
446 _("'%s' is not a valid name: '%c' "), name
, *p
);
454 * Use me for elements, attributes etc.
457 name_validate (GMarkupParseContext
*context
,
464 /* name start char */
466 if (G_UNLIKELY (IS_COMMON_NAME_END_CHAR (*p
) ||
467 !(g_ascii_isalpha (*p
) || *p
== '_' || *p
== ':')))
470 for (mask
= *p
++; *p
!= '\0'; p
++)
475 if (G_UNLIKELY (!(g_ascii_isalnum (*p
) ||
476 (!IS_COMMON_NAME_END_CHAR (*p
) &&
484 if (mask
& 0x80) /* un-common / non-ascii */
490 return slow_name_validate (context
, name
, error
);
494 text_validate (GMarkupParseContext
*context
,
499 if (!g_utf8_validate (p
, len
, NULL
))
501 set_error (context
, error
, G_MARKUP_ERROR_BAD_UTF8
,
502 _("Invalid UTF-8 encoded text in name - not valid '%s'"), p
);
510 char_str (gunichar c
,
514 g_unichar_to_utf8 (c
, buf
);
519 utf8_str (const gchar
*utf8
,
522 char_str (g_utf8_get_char (utf8
), buf
);
527 set_unescape_error (GMarkupParseContext
*context
,
529 const gchar
*remaining_text
,
537 gint remaining_newlines
;
540 remaining_newlines
= 0;
545 ++remaining_newlines
;
549 va_start (args
, format
);
550 s
= g_strdup_vprintf (format
, args
);
553 tmp_error
= g_error_new (G_MARKUP_ERROR
,
555 _("Error on line %d: %s"),
556 context
->line_number
- remaining_newlines
,
561 mark_error (context
, tmp_error
);
563 g_propagate_error (error
, tmp_error
);
567 * re-write the GString in-place, unescaping anything that escaped.
568 * most XML does not contain entities, or escaping.
571 unescape_gstring_inplace (GMarkupParseContext
*context
,
579 gboolean normalize_attribute
;
583 /* are we unescaping an attribute or not ? */
584 if (context
->state
== STATE_INSIDE_ATTRIBUTE_VALUE_SQ
||
585 context
->state
== STATE_INSIDE_ATTRIBUTE_VALUE_DQ
)
586 normalize_attribute
= TRUE
;
588 normalize_attribute
= FALSE
;
591 * Meeks' theorum: unescaping can only shrink text.
592 * for < etc. this is obvious, for  more
593 * thought is required, but this is patently so.
596 for (from
= to
= string
->str
; *from
!= '\0'; from
++, to
++)
603 if (normalize_attribute
&& (*to
== '\t' || *to
== '\n'))
607 *to
= normalize_attribute
? ' ' : '\n';
616 gboolean is_hex
= FALSE
;
628 /* digit is between start and p */
631 l
= strtoul (from
, &end
, 16);
633 l
= strtoul (from
, &end
, 10);
635 if (end
== from
|| errno
!= 0)
637 set_unescape_error (context
, error
,
638 from
, G_MARKUP_ERROR_PARSE
,
639 _("Failed to parse '%-.*s', which "
640 "should have been a digit "
641 "inside a character reference "
642 "(ê for example) - perhaps "
643 "the digit is too large"),
647 else if (*end
!= ';')
649 set_unescape_error (context
, error
,
650 from
, G_MARKUP_ERROR_PARSE
,
651 _("Character reference did not end with a "
653 "most likely you used an ampersand "
654 "character without intending to start "
655 "an entity - escape ampersand as &"));
660 /* characters XML 1.1 permits */
661 if ((0 < l
&& l
<= 0xD7FF) ||
662 (0xE000 <= l
&& l
<= 0xFFFD) ||
663 (0x10000 <= l
&& l
<= 0x10FFFF))
668 to
+= strlen (buf
) - 1;
670 if (l
>= 0x80) /* not ascii */
675 set_unescape_error (context
, error
,
676 from
, G_MARKUP_ERROR_PARSE
,
677 _("Character reference '%-.*s' does not "
678 "encode a permitted character"),
685 else if (strncmp (from
, "lt;", 3) == 0)
690 else if (strncmp (from
, "gt;", 3) == 0)
695 else if (strncmp (from
, "amp;", 4) == 0)
700 else if (strncmp (from
, "quot;", 5) == 0)
705 else if (strncmp (from
, "apos;", 5) == 0)
713 set_unescape_error (context
, error
,
714 from
, G_MARKUP_ERROR_PARSE
,
715 _("Empty entity '&;' seen; valid "
716 "entities are: & " < > '"));
719 const char *end
= strchr (from
, ';');
721 set_unescape_error (context
, error
,
722 from
, G_MARKUP_ERROR_PARSE
,
723 _("Entity name '%-.*s' is not known"),
726 set_unescape_error (context
, error
,
727 from
, G_MARKUP_ERROR_PARSE
,
728 _("Entity did not end with a semicolon; "
729 "most likely you used an ampersand "
730 "character without intending to start "
731 "an entity - escape ampersand as &"));
738 g_assert (to
- string
->str
<= string
->len
);
739 if (to
- string
->str
!= string
->len
)
740 g_string_truncate (string
, to
- string
->str
);
742 *is_ascii
= !(mask
& 0x80);
747 static inline gboolean
748 advance_char (GMarkupParseContext
*context
)
751 context
->char_number
++;
753 if (G_UNLIKELY (context
->iter
== context
->current_text_end
))
756 else if (G_UNLIKELY (*context
->iter
== '\n'))
758 context
->line_number
++;
759 context
->char_number
= 1;
765 static inline gboolean
768 return c
== ' ' || c
== '\t' || c
== '\n' || c
== '\r';
772 skip_spaces (GMarkupParseContext
*context
)
776 if (!xml_isspace (*context
->iter
))
779 while (advance_char (context
));
783 advance_to_name_end (GMarkupParseContext
*context
)
787 if (IS_COMMON_NAME_END_CHAR (*(context
->iter
)))
789 if (xml_isspace (*(context
->iter
)))
792 while (advance_char (context
));
796 release_chunk (GMarkupParseContext
*context
, GString
*str
)
801 if (str
->allocated_len
> 256)
802 { /* large strings are unusual and worth freeing */
803 g_string_free (str
, TRUE
);
807 node
= get_list_node (context
, str
);
808 context
->spare_chunks
= g_slist_concat (node
, context
->spare_chunks
);
812 add_to_partial (GMarkupParseContext
*context
,
813 const gchar
*text_start
,
814 const gchar
*text_end
)
816 if (context
->partial_chunk
== NULL
)
817 { /* allocate a new chunk to parse into */
819 if (context
->spare_chunks
!= NULL
)
821 GSList
*node
= context
->spare_chunks
;
822 context
->spare_chunks
= g_slist_remove_link (context
->spare_chunks
, node
);
823 context
->partial_chunk
= node
->data
;
824 free_list_node (context
, node
);
827 context
->partial_chunk
= g_string_sized_new (MAX (28, text_end
- text_start
));
830 if (text_start
!= text_end
)
831 g_string_insert_len (context
->partial_chunk
, -1,
832 text_start
, text_end
- text_start
);
836 truncate_partial (GMarkupParseContext
*context
)
838 if (context
->partial_chunk
!= NULL
)
839 string_blank (context
->partial_chunk
);
842 static inline const gchar
*
843 current_element (GMarkupParseContext
*context
)
845 return context
->tag_stack
->data
;
849 pop_subparser_stack (GMarkupParseContext
*context
)
851 GMarkupRecursionTracker
*tracker
;
853 g_assert (context
->subparser_stack
);
855 tracker
= context
->subparser_stack
->data
;
857 context
->awaiting_pop
= TRUE
;
858 context
->held_user_data
= context
->user_data
;
860 context
->user_data
= tracker
->prev_user_data
;
861 context
->parser
= tracker
->prev_parser
;
862 context
->subparser_element
= tracker
->prev_element
;
863 g_slice_free (GMarkupRecursionTracker
, tracker
);
865 context
->subparser_stack
= g_slist_delete_link (context
->subparser_stack
,
866 context
->subparser_stack
);
870 push_partial_as_tag (GMarkupParseContext
*context
)
872 GString
*str
= context
->partial_chunk
;
873 /* sadly, this is exported by gmarkup_get_element_stack as-is */
874 context
->tag_stack
= g_slist_concat (get_list_node (context
, str
->str
), context
->tag_stack
);
875 context
->tag_stack_gstr
= g_slist_concat (get_list_node (context
, str
), context
->tag_stack_gstr
);
876 context
->partial_chunk
= NULL
;
880 pop_tag (GMarkupParseContext
*context
)
882 GSList
*nodea
, *nodeb
;
884 nodea
= context
->tag_stack
;
885 nodeb
= context
->tag_stack_gstr
;
886 release_chunk (context
, nodeb
->data
);
887 context
->tag_stack
= g_slist_remove_link (context
->tag_stack
, nodea
);
888 context
->tag_stack_gstr
= g_slist_remove_link (context
->tag_stack_gstr
, nodeb
);
889 free_list_node (context
, nodea
);
890 free_list_node (context
, nodeb
);
894 possibly_finish_subparser (GMarkupParseContext
*context
)
896 if (current_element (context
) == context
->subparser_element
)
897 pop_subparser_stack (context
);
901 ensure_no_outstanding_subparser (GMarkupParseContext
*context
)
903 if (context
->awaiting_pop
)
904 g_critical ("During the first end_element call after invoking a "
905 "subparser you must pop the subparser stack and handle "
906 "the freeing of the subparser user_data. This can be "
907 "done by calling the end function of the subparser. "
908 "Very probably, your program just leaked memory.");
910 /* let valgrind watch the pointer disappear... */
911 context
->held_user_data
= NULL
;
912 context
->awaiting_pop
= FALSE
;
916 current_attribute (GMarkupParseContext
*context
)
918 g_assert (context
->cur_attr
>= 0);
919 return context
->attr_names
[context
->cur_attr
]->str
;
923 add_attribute (GMarkupParseContext
*context
, GString
*str
)
925 if (context
->cur_attr
+ 2 >= context
->alloc_attrs
)
927 context
->alloc_attrs
+= 5; /* silly magic number */
928 context
->attr_names
= g_realloc (context
->attr_names
, sizeof(GString
*)*context
->alloc_attrs
);
929 context
->attr_values
= g_realloc (context
->attr_values
, sizeof(GString
*)*context
->alloc_attrs
);
932 context
->attr_names
[context
->cur_attr
] = str
;
933 context
->attr_values
[context
->cur_attr
] = NULL
;
934 context
->attr_names
[context
->cur_attr
+1] = NULL
;
935 context
->attr_values
[context
->cur_attr
+1] = NULL
;
939 clear_attributes (GMarkupParseContext
*context
)
941 /* Go ahead and free the attributes. */
942 for (; context
->cur_attr
>= 0; context
->cur_attr
--)
944 int pos
= context
->cur_attr
;
945 release_chunk (context
, context
->attr_names
[pos
]);
946 release_chunk (context
, context
->attr_values
[pos
]);
947 context
->attr_names
[pos
] = context
->attr_values
[pos
] = NULL
;
949 g_assert (context
->cur_attr
== -1);
950 g_assert (context
->attr_names
== NULL
||
951 context
->attr_names
[0] == NULL
);
952 g_assert (context
->attr_values
== NULL
||
953 context
->attr_values
[0] == NULL
);
956 /* This has to be a separate function to ensure the alloca's
957 * are unwound on exit - otherwise we grow & blow the stack
958 * with large documents
961 emit_start_element (GMarkupParseContext
*context
,
965 const gchar
*start_name
;
966 const gchar
**attr_names
;
967 const gchar
**attr_values
;
970 attr_names
= g_newa (const gchar
*, context
->cur_attr
+ 2);
971 attr_values
= g_newa (const gchar
*, context
->cur_attr
+ 2);
972 for (i
= 0; i
< context
->cur_attr
+ 1; i
++)
974 attr_names
[i
] = context
->attr_names
[i
]->str
;
975 attr_values
[i
] = context
->attr_values
[i
]->str
;
977 attr_names
[i
] = NULL
;
978 attr_values
[i
] = NULL
;
980 /* Call user callback for element start */
982 start_name
= current_element (context
);
984 if (context
->parser
->start_element
&&
985 name_validate (context
, start_name
, error
))
986 (* context
->parser
->start_element
) (context
,
988 (const gchar
**)attr_names
,
989 (const gchar
**)attr_values
,
992 clear_attributes (context
);
994 if (tmp_error
!= NULL
)
995 propagate_error (context
, error
, tmp_error
);
999 * g_markup_parse_context_parse:
1000 * @context: a #GMarkupParseContext
1001 * @text: chunk of text to parse
1002 * @text_len: length of @text in bytes
1003 * @error: return location for a #GError
1005 * Feed some data to the #GMarkupParseContext.
1007 * The data need not be valid UTF-8; an error will be signaled if
1008 * it's invalid. The data need not be an entire document; you can
1009 * feed a document into the parser incrementally, via multiple calls
1010 * to this function. Typically, as you receive data from a network
1011 * connection or file, you feed each received chunk of data into this
1012 * function, aborting the process if an error occurs. Once an error
1013 * is reported, no further data may be fed to the #GMarkupParseContext;
1014 * all errors are fatal.
1016 * Return value: %FALSE if an error occurred, %TRUE on success
1019 g_markup_parse_context_parse (GMarkupParseContext
*context
,
1024 g_return_val_if_fail (context
!= NULL
, FALSE
);
1025 g_return_val_if_fail (text
!= NULL
, FALSE
);
1026 g_return_val_if_fail (context
->state
!= STATE_ERROR
, FALSE
);
1027 g_return_val_if_fail (!context
->parsing
, FALSE
);
1030 text_len
= strlen (text
);
1035 context
->parsing
= TRUE
;
1038 context
->current_text
= text
;
1039 context
->current_text_len
= text_len
;
1040 context
->current_text_end
= context
->current_text
+ text_len
;
1041 context
->iter
= context
->current_text
;
1042 context
->start
= context
->iter
;
1044 while (context
->iter
!= context
->current_text_end
)
1046 switch (context
->state
)
1049 /* Possible next state: AFTER_OPEN_ANGLE */
1051 g_assert (context
->tag_stack
== NULL
);
1053 /* whitespace is ignored outside of any elements */
1054 skip_spaces (context
);
1056 if (context
->iter
!= context
->current_text_end
)
1058 if (*context
->iter
== '<')
1060 /* Move after the open angle */
1061 advance_char (context
);
1063 context
->state
= STATE_AFTER_OPEN_ANGLE
;
1065 /* this could start a passthrough */
1066 context
->start
= context
->iter
;
1068 /* document is now non-empty */
1069 context
->document_empty
= FALSE
;
1073 set_error_literal (context
,
1075 G_MARKUP_ERROR_PARSE
,
1076 _("Document must begin with an element (e.g. <book>)"));
1081 case STATE_AFTER_OPEN_ANGLE
:
1082 /* Possible next states: INSIDE_OPEN_TAG_NAME,
1083 * AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1085 if (*context
->iter
== '?' ||
1086 *context
->iter
== '!')
1088 /* include < in the passthrough */
1089 const gchar
*openangle
= "<";
1090 add_to_partial (context
, openangle
, openangle
+ 1);
1091 context
->start
= context
->iter
;
1092 context
->balance
= 1;
1093 context
->state
= STATE_INSIDE_PASSTHROUGH
;
1095 else if (*context
->iter
== '/')
1098 advance_char (context
);
1100 context
->state
= STATE_AFTER_CLOSE_TAG_SLASH
;
1102 else if (!IS_COMMON_NAME_END_CHAR (*(context
->iter
)))
1104 context
->state
= STATE_INSIDE_OPEN_TAG_NAME
;
1106 /* start of tag name */
1107 context
->start
= context
->iter
;
1115 G_MARKUP_ERROR_PARSE
,
1116 _("'%s' is not a valid character following "
1117 "a '<' character; it may not begin an "
1119 utf8_str (context
->iter
, buf
));
1123 /* The AFTER_CLOSE_ANGLE state is actually sort of
1124 * broken, because it doesn't correspond to a range
1125 * of characters in the input stream as the others do,
1126 * and thus makes things harder to conceptualize
1128 case STATE_AFTER_CLOSE_ANGLE
:
1129 /* Possible next states: INSIDE_TEXT, STATE_START */
1130 if (context
->tag_stack
== NULL
)
1132 context
->start
= NULL
;
1133 context
->state
= STATE_START
;
1137 context
->start
= context
->iter
;
1138 context
->state
= STATE_INSIDE_TEXT
;
1142 case STATE_AFTER_ELISION_SLASH
:
1143 /* Possible next state: AFTER_CLOSE_ANGLE */
1146 /* We need to pop the tag stack and call the end_element
1147 * function, since this is the close tag
1149 GError
*tmp_error
= NULL
;
1151 g_assert (context
->tag_stack
!= NULL
);
1153 possibly_finish_subparser (context
);
1156 if (context
->parser
->end_element
)
1157 (* context
->parser
->end_element
) (context
,
1158 current_element (context
),
1162 ensure_no_outstanding_subparser (context
);
1166 mark_error (context
, tmp_error
);
1167 g_propagate_error (error
, tmp_error
);
1171 if (*context
->iter
== '>')
1173 /* move after the close angle */
1174 advance_char (context
);
1175 context
->state
= STATE_AFTER_CLOSE_ANGLE
;
1183 G_MARKUP_ERROR_PARSE
,
1184 _("Odd character '%s', expected a '>' character "
1185 "to end the empty-element tag '%s'"),
1186 utf8_str (context
->iter
, buf
),
1187 current_element (context
));
1194 case STATE_INSIDE_OPEN_TAG_NAME
:
1195 /* Possible next states: BETWEEN_ATTRIBUTES */
1197 /* if there's a partial chunk then it's the first part of the
1198 * tag name. If there's a context->start then it's the start
1199 * of the tag name in current_text, the partial chunk goes
1200 * before that start though.
1202 advance_to_name_end (context
);
1204 if (context
->iter
== context
->current_text_end
)
1206 /* The name hasn't necessarily ended. Merge with
1207 * partial chunk, leave state unchanged.
1209 add_to_partial (context
, context
->start
, context
->iter
);
1213 /* The name has ended. Combine it with the partial chunk
1214 * if any; push it on the stack; enter next state.
1216 add_to_partial (context
, context
->start
, context
->iter
);
1217 push_partial_as_tag (context
);
1219 context
->state
= STATE_BETWEEN_ATTRIBUTES
;
1220 context
->start
= NULL
;
1224 case STATE_INSIDE_ATTRIBUTE_NAME
:
1225 /* Possible next states: AFTER_ATTRIBUTE_NAME */
1227 advance_to_name_end (context
);
1228 add_to_partial (context
, context
->start
, context
->iter
);
1230 /* read the full name, if we enter the equals sign state
1231 * then add the attribute to the list (without the value),
1232 * otherwise store a partial chunk to be prepended later.
1234 if (context
->iter
!= context
->current_text_end
)
1235 context
->state
= STATE_AFTER_ATTRIBUTE_NAME
;
1238 case STATE_AFTER_ATTRIBUTE_NAME
:
1239 /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1241 skip_spaces (context
);
1243 if (context
->iter
!= context
->current_text_end
)
1245 /* The name has ended. Combine it with the partial chunk
1246 * if any; push it on the stack; enter next state.
1248 if (!name_validate (context
, context
->partial_chunk
->str
, error
))
1251 add_attribute (context
, context
->partial_chunk
);
1253 context
->partial_chunk
= NULL
;
1254 context
->start
= NULL
;
1256 if (*context
->iter
== '=')
1258 advance_char (context
);
1259 context
->state
= STATE_AFTER_ATTRIBUTE_EQUALS_SIGN
;
1267 G_MARKUP_ERROR_PARSE
,
1268 _("Odd character '%s', expected a '=' after "
1269 "attribute name '%s' of element '%s'"),
1270 utf8_str (context
->iter
, buf
),
1271 current_attribute (context
),
1272 current_element (context
));
1278 case STATE_BETWEEN_ATTRIBUTES
:
1279 /* Possible next states: AFTER_CLOSE_ANGLE,
1280 * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1282 skip_spaces (context
);
1284 if (context
->iter
!= context
->current_text_end
)
1286 if (*context
->iter
== '/')
1288 advance_char (context
);
1289 context
->state
= STATE_AFTER_ELISION_SLASH
;
1291 else if (*context
->iter
== '>')
1293 advance_char (context
);
1294 context
->state
= STATE_AFTER_CLOSE_ANGLE
;
1296 else if (!IS_COMMON_NAME_END_CHAR (*(context
->iter
)))
1298 context
->state
= STATE_INSIDE_ATTRIBUTE_NAME
;
1299 /* start of attribute name */
1300 context
->start
= context
->iter
;
1308 G_MARKUP_ERROR_PARSE
,
1309 _("Odd character '%s', expected a '>' or '/' "
1310 "character to end the start tag of "
1311 "element '%s', or optionally an attribute; "
1312 "perhaps you used an invalid character in "
1313 "an attribute name"),
1314 utf8_str (context
->iter
, buf
),
1315 current_element (context
));
1318 /* If we're done with attributes, invoke
1319 * the start_element callback
1321 if (context
->state
== STATE_AFTER_ELISION_SLASH
||
1322 context
->state
== STATE_AFTER_CLOSE_ANGLE
)
1323 emit_start_element (context
, error
);
1327 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN
:
1328 /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1330 skip_spaces (context
);
1332 if (context
->iter
!= context
->current_text_end
)
1334 if (*context
->iter
== '"')
1336 advance_char (context
);
1337 context
->state
= STATE_INSIDE_ATTRIBUTE_VALUE_DQ
;
1338 context
->start
= context
->iter
;
1340 else if (*context
->iter
== '\'')
1342 advance_char (context
);
1343 context
->state
= STATE_INSIDE_ATTRIBUTE_VALUE_SQ
;
1344 context
->start
= context
->iter
;
1352 G_MARKUP_ERROR_PARSE
,
1353 _("Odd character '%s', expected an open quote mark "
1354 "after the equals sign when giving value for "
1355 "attribute '%s' of element '%s'"),
1356 utf8_str (context
->iter
, buf
),
1357 current_attribute (context
),
1358 current_element (context
));
1363 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ
:
1364 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ
:
1365 /* Possible next states: BETWEEN_ATTRIBUTES */
1369 if (context
->state
== STATE_INSIDE_ATTRIBUTE_VALUE_SQ
)
1380 if (*context
->iter
== delim
)
1383 while (advance_char (context
));
1385 if (context
->iter
== context
->current_text_end
)
1387 /* The value hasn't necessarily ended. Merge with
1388 * partial chunk, leave state unchanged.
1390 add_to_partial (context
, context
->start
, context
->iter
);
1395 /* The value has ended at the quote mark. Combine it
1396 * with the partial chunk if any; set it for the current
1399 add_to_partial (context
, context
->start
, context
->iter
);
1401 g_assert (context
->cur_attr
>= 0);
1403 if (unescape_gstring_inplace (context
, context
->partial_chunk
, &is_ascii
, error
) &&
1404 (is_ascii
|| text_validate (context
, context
->partial_chunk
->str
,
1405 context
->partial_chunk
->len
, error
)))
1407 /* success, advance past quote and set state. */
1408 context
->attr_values
[context
->cur_attr
] = context
->partial_chunk
;
1409 context
->partial_chunk
= NULL
;
1410 advance_char (context
);
1411 context
->state
= STATE_BETWEEN_ATTRIBUTES
;
1412 context
->start
= NULL
;
1415 truncate_partial (context
);
1419 case STATE_INSIDE_TEXT
:
1420 /* Possible next states: AFTER_OPEN_ANGLE */
1423 if (*context
->iter
== '<')
1426 while (advance_char (context
));
1428 /* The text hasn't necessarily ended. Merge with
1429 * partial chunk, leave state unchanged.
1432 add_to_partial (context
, context
->start
, context
->iter
);
1434 if (context
->iter
!= context
->current_text_end
)
1438 /* The text has ended at the open angle. Call the text
1441 if (unescape_gstring_inplace (context
, context
->partial_chunk
, &is_ascii
, error
) &&
1442 (is_ascii
|| text_validate (context
, context
->partial_chunk
->str
,
1443 context
->partial_chunk
->len
, error
)))
1445 GError
*tmp_error
= NULL
;
1447 if (context
->parser
->text
)
1448 (*context
->parser
->text
) (context
,
1449 context
->partial_chunk
->str
,
1450 context
->partial_chunk
->len
,
1454 if (tmp_error
== NULL
)
1456 /* advance past open angle and set state. */
1457 advance_char (context
);
1458 context
->state
= STATE_AFTER_OPEN_ANGLE
;
1459 /* could begin a passthrough */
1460 context
->start
= context
->iter
;
1463 propagate_error (context
, error
, tmp_error
);
1466 truncate_partial (context
);
1470 case STATE_AFTER_CLOSE_TAG_SLASH
:
1471 /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1472 if (!IS_COMMON_NAME_END_CHAR (*(context
->iter
)))
1474 context
->state
= STATE_INSIDE_CLOSE_TAG_NAME
;
1476 /* start of tag name */
1477 context
->start
= context
->iter
;
1485 G_MARKUP_ERROR_PARSE
,
1486 _("'%s' is not a valid character following "
1487 "the characters '</'; '%s' may not begin an "
1489 utf8_str (context
->iter
, buf
),
1490 utf8_str (context
->iter
, buf
));
1494 case STATE_INSIDE_CLOSE_TAG_NAME
:
1495 /* Possible next state: AFTER_CLOSE_TAG_NAME */
1496 advance_to_name_end (context
);
1497 add_to_partial (context
, context
->start
, context
->iter
);
1499 if (context
->iter
!= context
->current_text_end
)
1500 context
->state
= STATE_AFTER_CLOSE_TAG_NAME
;
1503 case STATE_AFTER_CLOSE_TAG_NAME
:
1504 /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1506 skip_spaces (context
);
1508 if (context
->iter
!= context
->current_text_end
)
1510 GString
*close_name
;
1512 close_name
= context
->partial_chunk
;
1513 context
->partial_chunk
= NULL
;
1515 if (*context
->iter
!= '>')
1521 G_MARKUP_ERROR_PARSE
,
1522 _("'%s' is not a valid character following "
1523 "the close element name '%s'; the allowed "
1524 "character is '>'"),
1525 utf8_str (context
->iter
, buf
),
1528 else if (context
->tag_stack
== NULL
)
1532 G_MARKUP_ERROR_PARSE
,
1533 _("Element '%s' was closed, no element "
1534 "is currently open"),
1537 else if (strcmp (close_name
->str
, current_element (context
)) != 0)
1541 G_MARKUP_ERROR_PARSE
,
1542 _("Element '%s' was closed, but the currently "
1543 "open element is '%s'"),
1545 current_element (context
));
1550 advance_char (context
);
1551 context
->state
= STATE_AFTER_CLOSE_ANGLE
;
1552 context
->start
= NULL
;
1554 possibly_finish_subparser (context
);
1556 /* call the end_element callback */
1558 if (context
->parser
->end_element
)
1559 (* context
->parser
->end_element
) (context
,
1564 ensure_no_outstanding_subparser (context
);
1568 propagate_error (context
, error
, tmp_error
);
1570 context
->partial_chunk
= close_name
;
1571 truncate_partial (context
);
1575 case STATE_INSIDE_PASSTHROUGH
:
1576 /* Possible next state: AFTER_CLOSE_ANGLE */
1579 if (*context
->iter
== '<')
1581 if (*context
->iter
== '>')
1587 add_to_partial (context
, context
->start
, context
->iter
);
1588 context
->start
= context
->iter
;
1590 str
= context
->partial_chunk
->str
;
1591 len
= context
->partial_chunk
->len
;
1593 if (str
[1] == '?' && str
[len
- 1] == '?')
1595 if (strncmp (str
, "<!--", 4) == 0 &&
1596 strcmp (str
+ len
- 2, "--") == 0)
1598 if (strncmp (str
, "<![CDATA[", 9) == 0 &&
1599 strcmp (str
+ len
- 2, "]]") == 0)
1601 if (strncmp (str
, "<!DOCTYPE", 9) == 0 &&
1602 context
->balance
== 0)
1606 while (advance_char (context
));
1608 if (context
->iter
== context
->current_text_end
)
1610 /* The passthrough hasn't necessarily ended. Merge with
1611 * partial chunk, leave state unchanged.
1613 add_to_partial (context
, context
->start
, context
->iter
);
1617 /* The passthrough has ended at the close angle. Combine
1618 * it with the partial chunk if any. Call the passthrough
1619 * callback. Note that the open/close angles are
1620 * included in the text of the passthrough.
1622 GError
*tmp_error
= NULL
;
1624 advance_char (context
); /* advance past close angle */
1625 add_to_partial (context
, context
->start
, context
->iter
);
1627 if (context
->flags
& G_MARKUP_TREAT_CDATA_AS_TEXT
&&
1628 strncmp (context
->partial_chunk
->str
, "<![CDATA[", 9) == 0)
1630 if (context
->parser
->text
&&
1631 text_validate (context
,
1632 context
->partial_chunk
->str
+ 9,
1633 context
->partial_chunk
->len
- 12,
1635 (*context
->parser
->text
) (context
,
1636 context
->partial_chunk
->str
+ 9,
1637 context
->partial_chunk
->len
- 12,
1641 else if (context
->parser
->passthrough
&&
1642 text_validate (context
,
1643 context
->partial_chunk
->str
,
1644 context
->partial_chunk
->len
,
1646 (*context
->parser
->passthrough
) (context
,
1647 context
->partial_chunk
->str
,
1648 context
->partial_chunk
->len
,
1652 truncate_partial (context
);
1654 if (tmp_error
== NULL
)
1656 context
->state
= STATE_AFTER_CLOSE_ANGLE
;
1657 context
->start
= context
->iter
; /* could begin text */
1660 propagate_error (context
, error
, tmp_error
);
1669 g_assert_not_reached ();
1675 context
->parsing
= FALSE
;
1677 return context
->state
!= STATE_ERROR
;
1681 * g_markup_parse_context_end_parse:
1682 * @context: a #GMarkupParseContext
1683 * @error: return location for a #GError
1685 * Signals to the #GMarkupParseContext that all data has been
1686 * fed into the parse context with g_markup_parse_context_parse().
1688 * This function reports an error if the document isn't complete,
1689 * for example if elements are still open.
1691 * Return value: %TRUE on success, %FALSE if an error was set
1694 g_markup_parse_context_end_parse (GMarkupParseContext
*context
,
1697 g_return_val_if_fail (context
!= NULL
, FALSE
);
1698 g_return_val_if_fail (!context
->parsing
, FALSE
);
1699 g_return_val_if_fail (context
->state
!= STATE_ERROR
, FALSE
);
1701 if (context
->partial_chunk
!= NULL
)
1703 g_string_free (context
->partial_chunk
, TRUE
);
1704 context
->partial_chunk
= NULL
;
1707 if (context
->document_empty
)
1709 set_error_literal (context
, error
, G_MARKUP_ERROR_EMPTY
,
1710 _("Document was empty or contained only whitespace"));
1714 context
->parsing
= TRUE
;
1716 switch (context
->state
)
1722 case STATE_AFTER_OPEN_ANGLE
:
1723 set_error_literal (context
, error
, G_MARKUP_ERROR_PARSE
,
1724 _("Document ended unexpectedly just after an open angle bracket '<'"));
1727 case STATE_AFTER_CLOSE_ANGLE
:
1728 if (context
->tag_stack
!= NULL
)
1730 /* Error message the same as for INSIDE_TEXT */
1731 set_error (context
, error
, G_MARKUP_ERROR_PARSE
,
1732 _("Document ended unexpectedly with elements still open - "
1733 "'%s' was the last element opened"),
1734 current_element (context
));
1738 case STATE_AFTER_ELISION_SLASH
:
1739 set_error (context
, error
, G_MARKUP_ERROR_PARSE
,
1740 _("Document ended unexpectedly, expected to see a close angle "
1741 "bracket ending the tag <%s/>"), current_element (context
));
1744 case STATE_INSIDE_OPEN_TAG_NAME
:
1745 set_error_literal (context
, error
, G_MARKUP_ERROR_PARSE
,
1746 _("Document ended unexpectedly inside an element name"));
1749 case STATE_INSIDE_ATTRIBUTE_NAME
:
1750 case STATE_AFTER_ATTRIBUTE_NAME
:
1751 set_error_literal (context
, error
, G_MARKUP_ERROR_PARSE
,
1752 _("Document ended unexpectedly inside an attribute name"));
1755 case STATE_BETWEEN_ATTRIBUTES
:
1756 set_error_literal (context
, error
, G_MARKUP_ERROR_PARSE
,
1757 _("Document ended unexpectedly inside an element-opening "
1761 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN
:
1762 set_error_literal (context
, error
, G_MARKUP_ERROR_PARSE
,
1763 _("Document ended unexpectedly after the equals sign "
1764 "following an attribute name; no attribute value"));
1767 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ
:
1768 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ
:
1769 set_error_literal (context
, error
, G_MARKUP_ERROR_PARSE
,
1770 _("Document ended unexpectedly while inside an attribute "
1774 case STATE_INSIDE_TEXT
:
1775 g_assert (context
->tag_stack
!= NULL
);
1776 set_error (context
, error
, G_MARKUP_ERROR_PARSE
,
1777 _("Document ended unexpectedly with elements still open - "
1778 "'%s' was the last element opened"),
1779 current_element (context
));
1782 case STATE_AFTER_CLOSE_TAG_SLASH
:
1783 case STATE_INSIDE_CLOSE_TAG_NAME
:
1784 case STATE_AFTER_CLOSE_TAG_NAME
:
1785 set_error (context
, error
, G_MARKUP_ERROR_PARSE
,
1786 _("Document ended unexpectedly inside the close tag for "
1787 "element '%s'"), current_element (context
));
1790 case STATE_INSIDE_PASSTHROUGH
:
1791 set_error_literal (context
, error
, G_MARKUP_ERROR_PARSE
,
1792 _("Document ended unexpectedly inside a comment or "
1793 "processing instruction"));
1798 g_assert_not_reached ();
1802 context
->parsing
= FALSE
;
1804 return context
->state
!= STATE_ERROR
;
1808 * g_markup_parse_context_get_element:
1809 * @context: a #GMarkupParseContext
1811 * Retrieves the name of the currently open element.
1813 * If called from the start_element or end_element handlers this will
1814 * give the element_name as passed to those functions. For the parent
1815 * elements, see g_markup_parse_context_get_element_stack().
1817 * Returns: the name of the currently open element, or %NULL
1822 g_markup_parse_context_get_element (GMarkupParseContext
*context
)
1824 g_return_val_if_fail (context
!= NULL
, NULL
);
1826 if (context
->tag_stack
== NULL
)
1829 return current_element (context
);
1833 * g_markup_parse_context_get_element_stack:
1834 * @context: a #GMarkupParseContext
1836 * Retrieves the element stack from the internal state of the parser.
1838 * The returned #GSList is a list of strings where the first item is
1839 * the currently open tag (as would be returned by
1840 * g_markup_parse_context_get_element()) and the next item is its
1843 * This function is intended to be used in the start_element and
1844 * end_element handlers where g_markup_parse_context_get_element()
1845 * would merely return the name of the element that is being
1848 * Returns: the element stack, which must not be modified
1853 g_markup_parse_context_get_element_stack (GMarkupParseContext
*context
)
1855 g_return_val_if_fail (context
!= NULL
, NULL
);
1856 return context
->tag_stack
;
1860 * g_markup_parse_context_get_position:
1861 * @context: a #GMarkupParseContext
1862 * @line_number: (allow-none): return location for a line number, or %NULL
1863 * @char_number: (allow-none): return location for a char-on-line number, or %NULL
1865 * Retrieves the current line number and the number of the character on
1866 * that line. Intended for use in error messages; there are no strict
1867 * semantics for what constitutes the "current" line number other than
1868 * "the best number we could come up with for error messages."
1871 g_markup_parse_context_get_position (GMarkupParseContext
*context
,
1875 g_return_if_fail (context
!= NULL
);
1878 *line_number
= context
->line_number
;
1881 *char_number
= context
->char_number
;
1885 * g_markup_parse_context_get_user_data:
1886 * @context: a #GMarkupParseContext
1888 * Returns the user_data associated with @context.
1890 * This will either be the user_data that was provided to
1891 * g_markup_parse_context_new() or to the most recent call
1892 * of g_markup_parse_context_push().
1894 * Returns: the provided user_data. The returned data belongs to
1895 * the markup context and will be freed when
1896 * g_markup_parse_context_free() is called.
1901 g_markup_parse_context_get_user_data (GMarkupParseContext
*context
)
1903 return context
->user_data
;
1907 * g_markup_parse_context_push:
1908 * @context: a #GMarkupParseContext
1909 * @parser: a #GMarkupParser
1910 * @user_data: user data to pass to #GMarkupParser functions
1912 * Temporarily redirects markup data to a sub-parser.
1914 * This function may only be called from the start_element handler of
1915 * a #GMarkupParser. It must be matched with a corresponding call to
1916 * g_markup_parse_context_pop() in the matching end_element handler
1917 * (except in the case that the parser aborts due to an error).
1919 * All tags, text and other data between the matching tags is
1920 * redirected to the subparser given by @parser. @user_data is used
1921 * as the user_data for that parser. @user_data is also passed to the
1922 * error callback in the event that an error occurs. This includes
1923 * errors that occur in subparsers of the subparser.
1925 * The end tag matching the start tag for which this call was made is
1926 * handled by the previous parser (which is given its own user_data)
1927 * which is why g_markup_parse_context_pop() is provided to allow "one
1928 * last access" to the @user_data provided to this function. In the
1929 * case of error, the @user_data provided here is passed directly to
1930 * the error callback of the subparser and g_markup_parse_context_pop()
1931 * should not be called. In either case, if @user_data was allocated
1932 * then it ought to be freed from both of these locations.
1934 * This function is not intended to be directly called by users
1935 * interested in invoking subparsers. Instead, it is intended to be
1936 * used by the subparsers themselves to implement a higher-level
1939 * As an example, see the following implementation of a simple
1940 * parser that counts the number of tags encountered.
1949 * counter_start_element (GMarkupParseContext *context,
1950 * const gchar *element_name,
1951 * const gchar **attribute_names,
1952 * const gchar **attribute_values,
1953 * gpointer user_data,
1956 * CounterData *data = user_data;
1958 * data->tag_count++;
1962 * counter_error (GMarkupParseContext *context,
1964 * gpointer user_data)
1966 * CounterData *data = user_data;
1968 * g_slice_free (CounterData, data);
1971 * static GMarkupParser counter_subparser =
1973 * counter_start_element,
1981 * In order to allow this parser to be easily used as a subparser, the
1982 * following interface is provided:
1986 * start_counting (GMarkupParseContext *context)
1988 * CounterData *data = g_slice_new (CounterData);
1990 * data->tag_count = 0;
1991 * g_markup_parse_context_push (context, &counter_subparser, data);
1995 * end_counting (GMarkupParseContext *context)
1997 * CounterData *data = g_markup_parse_context_pop (context);
2000 * result = data->tag_count;
2001 * g_slice_free (CounterData, data);
2007 * The subparser would then be used as follows:
2010 * static void start_element (context, element_name, ...)
2012 * if (strcmp (element_name, "count-these") == 0)
2013 * start_counting (context);
2015 * /* else, handle other tags... */
2018 * static void end_element (context, element_name, ...)
2020 * if (strcmp (element_name, "count-these") == 0)
2021 * g_print ("Counted %d tags\n", end_counting (context));
2023 * /* else, handle other tags... */
2030 g_markup_parse_context_push (GMarkupParseContext
*context
,
2031 const GMarkupParser
*parser
,
2034 GMarkupRecursionTracker
*tracker
;
2036 tracker
= g_slice_new (GMarkupRecursionTracker
);
2037 tracker
->prev_element
= context
->subparser_element
;
2038 tracker
->prev_parser
= context
->parser
;
2039 tracker
->prev_user_data
= context
->user_data
;
2041 context
->subparser_element
= current_element (context
);
2042 context
->parser
= parser
;
2043 context
->user_data
= user_data
;
2045 context
->subparser_stack
= g_slist_prepend (context
->subparser_stack
,
2050 * g_markup_parse_context_pop:
2051 * @context: a #GMarkupParseContext
2053 * Completes the process of a temporary sub-parser redirection.
2055 * This function exists to collect the user_data allocated by a
2056 * matching call to g_markup_parse_context_push(). It must be called
2057 * in the end_element handler corresponding to the start_element
2058 * handler during which g_markup_parse_context_push() was called.
2059 * You must not call this function from the error callback -- the
2060 * @user_data is provided directly to the callback in that case.
2062 * This function is not intended to be directly called by users
2063 * interested in invoking subparsers. Instead, it is intended to
2064 * be used by the subparsers themselves to implement a higher-level
2067 * Returns: the user data passed to g_markup_parse_context_push()
2072 g_markup_parse_context_pop (GMarkupParseContext
*context
)
2076 if (!context
->awaiting_pop
)
2077 possibly_finish_subparser (context
);
2079 g_assert (context
->awaiting_pop
);
2081 context
->awaiting_pop
= FALSE
;
2083 /* valgrind friendliness */
2084 user_data
= context
->held_user_data
;
2085 context
->held_user_data
= NULL
;
2091 append_escaped_text (GString
*str
,
2100 end
= text
+ length
;
2105 next
= g_utf8_next_char (p
);
2110 g_string_append (str
, "&");
2114 g_string_append (str
, "<");
2118 g_string_append (str
, ">");
2122 g_string_append (str
, "'");
2126 g_string_append (str
, """);
2130 c
= g_utf8_get_char (p
);
2131 if ((0x1 <= c
&& c
<= 0x8) ||
2132 (0xb <= c
&& c
<= 0xc) ||
2133 (0xe <= c
&& c
<= 0x1f) ||
2134 (0x7f <= c
&& c
<= 0x84) ||
2135 (0x86 <= c
&& c
<= 0x9f))
2136 g_string_append_printf (str
, "&#x%x;", c
);
2138 g_string_append_len (str
, p
, next
- p
);
2147 * g_markup_escape_text:
2148 * @text: some valid UTF-8 text
2149 * @length: length of @text in bytes, or -1 if the text is nul-terminated
2151 * Escapes text so that the markup parser will parse it verbatim.
2152 * Less than, greater than, ampersand, etc. are replaced with the
2153 * corresponding entities. This function would typically be used
2154 * when writing out a file to be parsed with the markup parser.
2156 * Note that this function doesn't protect whitespace and line endings
2157 * from being processed according to the XML rules for normalization
2158 * of line endings and attribute values.
2160 * Note also that this function will produce character references in
2161 * the range of &#x1; ... &#x1f; for all control sequences
2162 * except for tabstop, newline and carriage return. The character
2163 * references in this range are not valid XML 1.0, but they are
2164 * valid XML 1.1 and will be accepted by the GMarkup parser.
2166 * Return value: a newly allocated string with the escaped text
2169 g_markup_escape_text (const gchar
*text
,
2174 g_return_val_if_fail (text
!= NULL
, NULL
);
2177 length
= strlen (text
);
2179 /* prealloc at least as long as original text */
2180 str
= g_string_sized_new (length
);
2181 append_escaped_text (str
, text
, length
);
2183 return g_string_free (str
, FALSE
);
2188 * @format: a printf-style format string
2189 * @after: location to store a pointer to the character after
2190 * the returned conversion. On a %NULL return, returns the
2191 * pointer to the trailing NUL in the string
2193 * Find the next conversion in a printf-style format string.
2194 * Partially based on code from printf-parser.c,
2195 * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
2197 * Return value: pointer to the next conversion in @format,
2198 * or %NULL, if none.
2201 find_conversion (const char *format
,
2204 const char *start
= format
;
2207 while (*start
!= '\0' && *start
!= '%')
2224 /* Test for positional argument. */
2225 if (*cp
>= '0' && *cp
<= '9')
2229 for (np
= cp
; *np
>= '0' && *np
<= '9'; np
++)
2235 /* Skip the flags. */
2249 /* Skip the field width. */
2254 /* Test for positional argument. */
2255 if (*cp
>= '0' && *cp
<= '9')
2259 for (np
= cp
; *np
>= '0' && *np
<= '9'; np
++)
2267 for (; *cp
>= '0' && *cp
<= '9'; cp
++)
2271 /* Skip the precision. */
2277 /* Test for positional argument. */
2278 if (*cp
>= '0' && *cp
<= '9')
2282 for (np
= cp
; *np
>= '0' && *np
<= '9'; np
++)
2290 for (; *cp
>= '0' && *cp
<= '9'; cp
++)
2295 /* Skip argument type/size specifiers. */
2296 while (*cp
== 'h' ||
2305 /* Skip the conversion character. */
2313 * g_markup_vprintf_escaped:
2314 * @format: printf() style format string
2315 * @args: variable argument list, similar to vprintf()
2317 * Formats the data in @args according to @format, escaping
2318 * all string and character arguments in the fashion
2319 * of g_markup_escape_text(). See g_markup_printf_escaped().
2321 * Return value: newly allocated result from formatting
2322 * operation. Free with g_free().
2327 g_markup_vprintf_escaped (const gchar
*format
,
2332 GString
*result
= NULL
;
2333 gchar
*output1
= NULL
;
2334 gchar
*output2
= NULL
;
2335 const char *p
, *op1
, *op2
;
2338 /* The technique here, is that we make two format strings that
2339 * have the identical conversions in the identical order to the
2340 * original strings, but differ in the text in-between. We
2341 * then use the normal g_strdup_vprintf() to format the arguments
2342 * with the two new format strings. By comparing the results,
2343 * we can figure out what segments of the output come from
2344 * the the original format string, and what from the arguments,
2345 * and thus know what portions of the string to escape.
2347 * For instance, for:
2349 * g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2351 * We form the two format strings "%sX%dX" and %sY%sY". The results
2352 * of formatting with those two strings are
2354 * "%sX%dX" => "Susan & FredX5X"
2355 * "%sY%dY" => "Susan & FredY5Y"
2357 * To find the span of the first argument, we find the first position
2358 * where the two arguments differ, which tells us that the first
2359 * argument formatted to "Susan & Fred". We then escape that
2360 * to "Susan & Fred" and join up with the intermediate portions
2361 * of the format string and the second argument to get
2362 * "Susan & Fred ate 5 apples".
2365 /* Create the two modified format strings
2367 format1
= g_string_new (NULL
);
2368 format2
= g_string_new (NULL
);
2373 const char *conv
= find_conversion (p
, &after
);
2377 g_string_append_len (format1
, conv
, after
- conv
);
2378 g_string_append_c (format1
, 'X');
2379 g_string_append_len (format2
, conv
, after
- conv
);
2380 g_string_append_c (format2
, 'Y');
2385 /* Use them to format the arguments
2387 G_VA_COPY (args2
, args
);
2389 output1
= g_strdup_vprintf (format1
->str
, args
);
2396 output2
= g_strdup_vprintf (format2
->str
, args2
);
2401 result
= g_string_new (NULL
);
2403 /* Iterate through the original format string again,
2404 * copying the non-conversion portions and the escaped
2405 * converted arguments to the output string.
2413 const char *output_start
;
2414 const char *conv
= find_conversion (p
, &after
);
2417 if (!conv
) /* The end, after points to the trailing \0 */
2419 g_string_append_len (result
, p
, after
- p
);
2423 g_string_append_len (result
, p
, conv
- p
);
2425 while (*op1
== *op2
)
2431 escaped
= g_markup_escape_text (output_start
, op1
- output_start
);
2432 g_string_append (result
, escaped
);
2441 g_string_free (format1
, TRUE
);
2442 g_string_free (format2
, TRUE
);
2447 return g_string_free (result
, FALSE
);
2453 * g_markup_printf_escaped:
2454 * @format: printf() style format string
2455 * @...: the arguments to insert in the format string
2457 * Formats arguments according to @format, escaping
2458 * all string and character arguments in the fashion
2459 * of g_markup_escape_text(). This is useful when you
2460 * want to insert literal strings into XML-style markup
2461 * output, without having to worry that the strings
2462 * might themselves contain markup.
2465 * const char *store = "Fortnum & Mason";
2466 * const char *item = "Tea";
2469 * output = g_markup_printf_escaped ("<purchase>"
2470 * "<store>%s</store>"
2471 * "<item>%s</item>"
2472 * "</purchase>",
2476 * Return value: newly allocated result from formatting
2477 * operation. Free with g_free().
2482 g_markup_printf_escaped (const gchar
*format
, ...)
2487 va_start (args
, format
);
2488 result
= g_markup_vprintf_escaped (format
, args
);
2495 g_markup_parse_boolean (const char *string
,
2498 char const * const falses
[] = { "false", "f", "no", "n", "0" };
2499 char const * const trues
[] = { "true", "t", "yes", "y", "1" };
2502 for (i
= 0; i
< G_N_ELEMENTS (falses
); i
++)
2504 if (g_ascii_strcasecmp (string
, falses
[i
]) == 0)
2513 for (i
= 0; i
< G_N_ELEMENTS (trues
); i
++)
2515 if (g_ascii_strcasecmp (string
, trues
[i
]) == 0)
2528 * GMarkupCollectType:
2529 * @G_MARKUP_COLLECT_INVALID: used to terminate the list of attributes
2531 * @G_MARKUP_COLLECT_STRING: collect the string pointer directly from
2532 * the attribute_values[] array. Expects a parameter of type (const
2533 * char **). If %G_MARKUP_COLLECT_OPTIONAL is specified and the
2534 * attribute isn't present then the pointer will be set to %NULL
2535 * @G_MARKUP_COLLECT_STRDUP: as with %G_MARKUP_COLLECT_STRING, but
2536 * expects a parameter of type (char **) and g_strdup()s the
2537 * returned pointer. The pointer must be freed with g_free()
2538 * @G_MARKUP_COLLECT_BOOLEAN: expects a parameter of type (gboolean *)
2539 * and parses the attribute value as a boolean. Sets %FALSE if the
2540 * attribute isn't present. Valid boolean values consist of
2541 * (case-insensitive) "false", "f", "no", "n", "0" and "true", "t",
2543 * @G_MARKUP_COLLECT_TRISTATE: as with %G_MARKUP_COLLECT_BOOLEAN, but
2544 * in the case of a missing attribute a value is set that compares
2545 * equal to neither %FALSE nor %TRUE G_MARKUP_COLLECT_OPTIONAL is
2547 * @G_MARKUP_COLLECT_OPTIONAL: can be bitwise ORed with the other fields.
2548 * If present, allows the attribute not to appear. A default value
2549 * is set depending on what value type is used
2551 * A mixed enumerated type and flags field. You must specify one type
2552 * (string, strdup, boolean, tristate). Additionally, you may optionally
2553 * bitwise OR the type with the flag %G_MARKUP_COLLECT_OPTIONAL.
2555 * It is likely that this enum will be extended in the future to
2556 * support other types.
2560 * g_markup_collect_attributes:
2561 * @element_name: the current tag name
2562 * @attribute_names: the attribute names
2563 * @attribute_values: the attribute values
2564 * @error: a pointer to a #GError or %NULL
2565 * @first_type: the #GMarkupCollectType of the first attribute
2566 * @first_attr: the name of the first attribute
2567 * @...: a pointer to the storage location of the first attribute
2568 * (or %NULL), followed by more types names and pointers, ending
2569 * with %G_MARKUP_COLLECT_INVALID
2571 * Collects the attributes of the element from the data passed to the
2572 * #GMarkupParser start_element function, dealing with common error
2573 * conditions and supporting boolean values.
2575 * This utility function is not required to write a parser but can save
2578 * The @element_name, @attribute_names, @attribute_values and @error
2579 * parameters passed to the start_element callback should be passed
2580 * unmodified to this function.
2582 * Following these arguments is a list of "supported" attributes to collect.
2583 * It is an error to specify multiple attributes with the same name. If any
2584 * attribute not in the list appears in the @attribute_names array then an
2585 * unknown attribute error will result.
2587 * The #GMarkupCollectType field allows specifying the type of collection
2588 * to perform and if a given attribute must appear or is optional.
2590 * The attribute name is simply the name of the attribute to collect.
2592 * The pointer should be of the appropriate type (see the descriptions
2593 * under #GMarkupCollectType) and may be %NULL in case a particular
2594 * attribute is to be allowed but ignored.
2596 * This function deals with issuing errors for missing attributes
2597 * (of type %G_MARKUP_ERROR_MISSING_ATTRIBUTE), unknown attributes
2598 * (of type %G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE) and duplicate
2599 * attributes (of type %G_MARKUP_ERROR_INVALID_CONTENT) as well
2600 * as parse errors for boolean-valued attributes (again of type
2601 * %G_MARKUP_ERROR_INVALID_CONTENT). In all of these cases %FALSE
2602 * will be returned and @error will be set as appropriate.
2604 * Return value: %TRUE if successful
2609 g_markup_collect_attributes (const gchar
*element_name
,
2610 const gchar
**attribute_names
,
2611 const gchar
**attribute_values
,
2613 GMarkupCollectType first_type
,
2614 const gchar
*first_attr
,
2617 GMarkupCollectType type
;
2629 va_start (ap
, first_attr
);
2630 while (type
!= G_MARKUP_COLLECT_INVALID
)
2635 mandatory
= !(type
& G_MARKUP_COLLECT_OPTIONAL
);
2636 type
&= (G_MARKUP_COLLECT_OPTIONAL
- 1);
2638 /* tristate records a value != TRUE and != FALSE
2639 * for the case where the attribute is missing
2641 if (type
== G_MARKUP_COLLECT_TRISTATE
)
2644 for (i
= 0; attribute_names
[i
]; i
++)
2645 if (i
>= 40 || !(collected
& (G_GUINT64_CONSTANT(1) << i
)))
2646 if (!strcmp (attribute_names
[i
], attr
))
2649 /* ISO C99 only promises that the user can pass up to 127 arguments.
2650 * Subtracting the first 4 arguments plus the final NULL and dividing
2651 * by 3 arguments per collected attribute, we are left with a maximum
2652 * number of supported attributes of (127 - 5) / 3 = 40.
2654 * In reality, nobody is ever going to call us with anywhere close to
2655 * 40 attributes to collect, so it is safe to assume that if i > 40
2656 * then the user has given some invalid or repeated arguments. These
2657 * problems will be caught and reported at the end of the function.
2659 * We know at this point that we have an error, but we don't know
2660 * what error it is, so just continue...
2663 collected
|= (G_GUINT64_CONSTANT(1) << i
);
2665 value
= attribute_values
[i
];
2667 if (value
== NULL
&& mandatory
)
2669 g_set_error (error
, G_MARKUP_ERROR
,
2670 G_MARKUP_ERROR_MISSING_ATTRIBUTE
,
2671 "element '%s' requires attribute '%s'",
2672 element_name
, attr
);
2680 case G_MARKUP_COLLECT_STRING
:
2682 const char **str_ptr
;
2684 str_ptr
= va_arg (ap
, const char **);
2686 if (str_ptr
!= NULL
)
2691 case G_MARKUP_COLLECT_STRDUP
:
2695 str_ptr
= va_arg (ap
, char **);
2697 if (str_ptr
!= NULL
)
2698 *str_ptr
= g_strdup (value
);
2702 case G_MARKUP_COLLECT_BOOLEAN
:
2703 case G_MARKUP_COLLECT_TRISTATE
:
2708 bool_ptr
= va_arg (ap
, gboolean
*);
2710 if (bool_ptr
!= NULL
)
2712 if (type
== G_MARKUP_COLLECT_TRISTATE
)
2713 /* constructivists rejoice!
2714 * neither false nor true...
2718 else /* G_MARKUP_COLLECT_BOOLEAN */
2724 if (!g_markup_parse_boolean (value
, va_arg (ap
, gboolean
*)))
2726 g_set_error (error
, G_MARKUP_ERROR
,
2727 G_MARKUP_ERROR_INVALID_CONTENT
,
2728 "element '%s', attribute '%s', value '%s' "
2729 "cannot be parsed as a boolean value",
2730 element_name
, attr
, value
);
2740 g_assert_not_reached ();
2743 type
= va_arg (ap
, GMarkupCollectType
);
2744 attr
= va_arg (ap
, const char *);
2749 /* ensure we collected all the arguments */
2750 for (i
= 0; attribute_names
[i
]; i
++)
2751 if ((collected
& (G_GUINT64_CONSTANT(1) << i
)) == 0)
2753 /* attribute not collected: could be caused by two things.
2755 * 1) it doesn't exist in our list of attributes
2756 * 2) it existed but was matched by a duplicate attribute earlier
2762 for (j
= 0; j
< i
; j
++)
2763 if (strcmp (attribute_names
[i
], attribute_names
[j
]) == 0)
2767 /* j is now the first occurrence of attribute_names[i] */
2769 g_set_error (error
, G_MARKUP_ERROR
,
2770 G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE
,
2771 "attribute '%s' invalid for element '%s'",
2772 attribute_names
[i
], element_name
);
2774 g_set_error (error
, G_MARKUP_ERROR
,
2775 G_MARKUP_ERROR_INVALID_CONTENT
,
2776 "attribute '%s' given multiple times for element '%s'",
2777 attribute_names
[i
], element_name
);
2785 /* replay the above to free allocations */
2789 va_start (ap
, first_attr
);
2790 while (type
!= G_MARKUP_COLLECT_INVALID
)
2794 ptr
= va_arg (ap
, gpointer
);
2798 switch (type
& (G_MARKUP_COLLECT_OPTIONAL
- 1))
2800 case G_MARKUP_COLLECT_STRDUP
:
2802 g_free (*(char **) ptr
);
2804 case G_MARKUP_COLLECT_STRING
:
2805 *(char **) ptr
= NULL
;
2808 case G_MARKUP_COLLECT_BOOLEAN
:
2809 *(gboolean
*) ptr
= FALSE
;
2812 case G_MARKUP_COLLECT_TRISTATE
:
2813 *(gboolean
*) ptr
= -1;
2818 type
= va_arg (ap
, GMarkupCollectType
);
2819 attr
= va_arg (ap
, const char *);