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.
35 g_markup_error_quark (void)
37 return g_quark_from_static_string ("g-markup-error-quark");
43 STATE_AFTER_OPEN_ANGLE,
44 STATE_AFTER_CLOSE_ANGLE,
45 STATE_AFTER_ELISION_SLASH, /* the slash that obviates need for end element */
46 STATE_INSIDE_OPEN_TAG_NAME,
47 STATE_INSIDE_ATTRIBUTE_NAME,
48 STATE_AFTER_ATTRIBUTE_NAME,
49 STATE_BETWEEN_ATTRIBUTES,
50 STATE_AFTER_ATTRIBUTE_EQUALS_SIGN,
51 STATE_INSIDE_ATTRIBUTE_VALUE_SQ,
52 STATE_INSIDE_ATTRIBUTE_VALUE_DQ,
54 STATE_AFTER_CLOSE_TAG_SLASH,
55 STATE_INSIDE_CLOSE_TAG_NAME,
56 STATE_AFTER_CLOSE_TAG_NAME,
57 STATE_INSIDE_PASSTHROUGH,
63 const char *prev_element;
64 const GMarkupParser *prev_parser;
65 gpointer prev_user_data;
66 } GMarkupRecursionTracker;
68 struct _GMarkupParseContext
70 const GMarkupParser *parser;
72 GMarkupParseFlags flags;
78 GDestroyNotify dnotify;
80 /* A piece of character data or an element that
81 * hasn't "ended" yet so we haven't yet called
82 * the callback for it.
84 GString *partial_chunk;
87 GMarkupParseState state;
89 GSList *tag_stack_gstr;
90 GSList *spare_list_nodes;
93 GString **attr_values;
97 const gchar *current_text;
98 gssize current_text_len;
99 const gchar *current_text_end;
101 /* used to save the start of the last interesting thingy */
106 guint document_empty : 1;
108 guint awaiting_pop : 1;
111 /* subparser support */
112 GSList *subparser_stack; /* (GMarkupRecursionTracker *) */
113 const char *subparser_element;
114 gpointer held_user_data;
118 * Helpers to reduce our allocation overhead, we have
119 * a well defined allocation lifecycle.
122 get_list_node (GMarkupParseContext *context, gpointer data)
125 if (context->spare_list_nodes != NULL)
127 node = context->spare_list_nodes;
128 context->spare_list_nodes = g_slist_remove_link (context->spare_list_nodes, node);
131 node = g_slist_alloc();
137 free_list_node (GMarkupParseContext *context, GSList *node)
140 context->spare_list_nodes = g_slist_concat (node, context->spare_list_nodes);
144 string_blank (GString *string)
146 string->str[0] = '\0';
151 * g_markup_parse_context_new:
152 * @parser: a #GMarkupParser
153 * @flags: one or more #GMarkupParseFlags
154 * @user_data: user data to pass to #GMarkupParser functions
155 * @user_data_dnotify: user data destroy notifier called when the parse context is freed
157 * Creates a new parse context. A parse context is used to parse
158 * marked-up documents. You can feed any number of documents into
159 * a context, as long as no errors occur; once an error occurs,
160 * the parse context can't continue to parse text (you have to free it
161 * and create a new parse context).
163 * Return value: a new #GMarkupParseContext
165 GMarkupParseContext *
166 g_markup_parse_context_new (const GMarkupParser *parser,
167 GMarkupParseFlags flags,
169 GDestroyNotify user_data_dnotify)
171 GMarkupParseContext *context;
173 g_return_val_if_fail (parser != NULL, NULL);
175 context = g_new (GMarkupParseContext, 1);
177 context->parser = parser;
178 context->flags = flags;
179 context->user_data = user_data;
180 context->dnotify = user_data_dnotify;
182 context->line_number = 1;
183 context->char_number = 1;
185 context->partial_chunk = NULL;
186 context->spare_chunks = NULL;
187 context->spare_list_nodes = NULL;
189 context->state = STATE_START;
190 context->tag_stack = NULL;
191 context->tag_stack_gstr = NULL;
192 context->attr_names = NULL;
193 context->attr_values = NULL;
194 context->cur_attr = -1;
195 context->alloc_attrs = 0;
197 context->current_text = NULL;
198 context->current_text_len = -1;
199 context->current_text_end = NULL;
201 context->start = NULL;
202 context->iter = NULL;
204 context->document_empty = TRUE;
205 context->parsing = FALSE;
207 context->awaiting_pop = FALSE;
208 context->subparser_stack = NULL;
209 context->subparser_element = NULL;
211 /* this is only looked at if awaiting_pop = TRUE. initialise anyway. */
212 context->held_user_data = NULL;
214 context->balance = 0;
220 string_full_free (gpointer ptr, gpointer user_data)
222 g_string_free (ptr, TRUE);
225 static void clear_attributes (GMarkupParseContext *context);
228 * g_markup_parse_context_free:
229 * @context: a #GMarkupParseContext
231 * Frees a #GMarkupParseContext. Can't be called from inside
232 * one of the #GMarkupParser functions. Can't be called while
233 * a subparser is pushed.
236 g_markup_parse_context_free (GMarkupParseContext *context)
238 g_return_if_fail (context != NULL);
239 g_return_if_fail (!context->parsing);
240 g_return_if_fail (!context->subparser_stack);
241 g_return_if_fail (!context->awaiting_pop);
243 if (context->dnotify)
244 (* context->dnotify) (context->user_data);
246 clear_attributes (context);
247 g_free (context->attr_names);
248 g_free (context->attr_values);
250 g_slist_foreach (context->tag_stack_gstr, string_full_free, NULL);
251 g_slist_free (context->tag_stack_gstr);
252 g_slist_free (context->tag_stack);
254 g_slist_foreach (context->spare_chunks, string_full_free, NULL);
255 g_slist_free (context->spare_chunks);
256 g_slist_free (context->spare_list_nodes);
258 if (context->partial_chunk)
259 g_string_free (context->partial_chunk, TRUE);
264 static void pop_subparser_stack (GMarkupParseContext *context);
267 mark_error (GMarkupParseContext *context,
270 context->state = STATE_ERROR;
272 if (context->parser->error)
273 (*context->parser->error) (context, error, context->user_data);
275 /* report the error all the way up to free all the user-data */
276 while (context->subparser_stack)
278 pop_subparser_stack (context);
279 context->awaiting_pop = FALSE; /* already been freed */
281 if (context->parser->error)
282 (*context->parser->error) (context, error, context->user_data);
286 static void set_error (GMarkupParseContext *context,
290 ...) G_GNUC_PRINTF (4, 5);
293 set_error_literal (GMarkupParseContext *context,
296 const gchar *message)
300 tmp_error = g_error_new_literal (G_MARKUP_ERROR, code, message);
302 g_prefix_error (&tmp_error,
303 _("Error on line %d char %d: "),
304 context->line_number,
305 context->char_number);
307 mark_error (context, tmp_error);
309 g_propagate_error (error, tmp_error);
313 set_error (GMarkupParseContext *context,
323 va_start (args, format);
324 s = g_strdup_vprintf (format, args);
327 /* Make sure that the GError message is valid UTF-8 even if it is
328 * complaining about invalid UTF-8 in the markup: */
329 s_valid = _g_utf8_make_valid (s);
330 set_error_literal (context, error, code, s);
337 propagate_error (GMarkupParseContext *context,
341 if (context->flags & G_MARKUP_PREFIX_ERROR_POSITION)
342 g_prefix_error (&src,
343 _("Error on line %d char %d: "),
344 context->line_number,
345 context->char_number);
347 mark_error (context, src);
349 g_propagate_error (dest, src);
352 #define IS_COMMON_NAME_END_CHAR(c) \
353 ((c) == '=' || (c) == '/' || (c) == '>' || (c) == ' ')
356 slow_name_validate (GMarkupParseContext *context, const char *name, GError **error)
358 const char *p = name;
360 if (!g_utf8_validate (name, strlen (name), NULL))
362 set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
363 _("Invalid UTF-8 encoded text in name - not valid '%s'"), name);
367 if (!(g_ascii_isalpha (*p) ||
368 (!IS_COMMON_NAME_END_CHAR (*p) &&
371 g_unichar_isalpha (g_utf8_get_char (p))))))
373 set_error (context, error, G_MARKUP_ERROR_PARSE,
374 _("'%s' is not a valid name "), name);
378 for (p = g_utf8_next_char (name); *p != '\0'; p = g_utf8_next_char (p))
381 if (!(g_ascii_isalnum (*p) ||
382 (!IS_COMMON_NAME_END_CHAR (*p) &&
387 g_unichar_isalpha (g_utf8_get_char (p))))))
389 set_error (context, error, G_MARKUP_ERROR_PARSE,
390 _("'%s' is not a valid name: '%c' "), name, *p);
398 * Use me for elements, attributes etc.
401 name_validate (GMarkupParseContext *context, const char *name, GError **error)
406 /* name start char */
408 if (G_UNLIKELY (IS_COMMON_NAME_END_CHAR (*p) ||
409 !(g_ascii_isalpha (*p) || *p == '_' || *p == ':')))
412 for (mask = *p++; *p != '\0'; p++)
417 if (G_UNLIKELY (!(g_ascii_isalnum (*p) ||
418 (!IS_COMMON_NAME_END_CHAR (*p) &&
426 if (mask & 0x80) /* un-common / non-ascii */
432 return slow_name_validate (context, name, error);
436 text_validate (GMarkupParseContext *context, const char *p, int len, GError **error)
438 if (!g_utf8_validate (p, len, NULL))
440 set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
441 _("Invalid UTF-8 encoded text in name - not valid '%s'"), p);
449 char_str (gunichar c,
453 g_unichar_to_utf8 (c, buf);
458 utf8_str (const gchar *utf8,
461 char_str (g_utf8_get_char (utf8), buf);
466 set_unescape_error (GMarkupParseContext *context,
468 const gchar *remaining_text,
476 gint remaining_newlines;
479 remaining_newlines = 0;
484 ++remaining_newlines;
488 va_start (args, format);
489 s = g_strdup_vprintf (format, args);
492 tmp_error = g_error_new (G_MARKUP_ERROR,
494 _("Error on line %d: %s"),
495 context->line_number - remaining_newlines,
500 mark_error (context, tmp_error);
502 g_propagate_error (error, tmp_error);
506 * re-write the GString in-place, unescaping anything that escaped.
507 * most XML does not contain entities, or escaping.
510 unescape_gstring_inplace (GMarkupParseContext *context,
518 gboolean normalize_attribute;
522 /* are we unescaping an attribute or not ? */
523 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
524 context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
525 normalize_attribute = TRUE;
527 normalize_attribute = FALSE;
530 * Meeks' theorum: unescaping can only shrink text.
531 * for < etc. this is obvious, for  more
532 * thought is required, but this is patently so.
535 for (from = to = string->str; *from != '\0'; from++, to++)
542 if (normalize_attribute && (*to == '\t' || *to == '\n'))
546 *to = normalize_attribute ? ' ' : '\n';
555 gboolean is_hex = FALSE;
567 /* digit is between start and p */
570 l = strtoul (from, &end, 16);
572 l = strtoul (from, &end, 10);
574 if (end == from || errno != 0)
576 set_unescape_error (context, error,
577 from, G_MARKUP_ERROR_PARSE,
578 _("Failed to parse '%-.*s', which "
579 "should have been a digit "
580 "inside a character reference "
581 "(ê for example) - perhaps "
582 "the digit is too large"),
586 else if (*end != ';')
588 set_unescape_error (context, error,
589 from, G_MARKUP_ERROR_PARSE,
590 _("Character reference did not end with a "
592 "most likely you used an ampersand "
593 "character without intending to start "
594 "an entity - escape ampersand as &"));
599 /* characters XML 1.1 permits */
600 if ((0 < l && l <= 0xD7FF) ||
601 (0xE000 <= l && l <= 0xFFFD) ||
602 (0x10000 <= l && l <= 0x10FFFF))
607 to += strlen (buf) - 1;
609 if (l >= 0x80) /* not ascii */
614 set_unescape_error (context, error,
615 from, G_MARKUP_ERROR_PARSE,
616 _("Character reference '%-.*s' does not "
617 "encode a permitted character"),
624 else if (strncmp (from, "lt;", 3) == 0)
629 else if (strncmp (from, "gt;", 3) == 0)
634 else if (strncmp (from, "amp;", 4) == 0)
639 else if (strncmp (from, "quot;", 5) == 0)
644 else if (strncmp (from, "apos;", 5) == 0)
652 set_unescape_error (context, error,
653 from, G_MARKUP_ERROR_PARSE,
654 _("Empty entity '&;' seen; valid "
655 "entities are: & " < > '"));
658 const char *end = strchr (from, ';');
660 set_unescape_error (context, error,
661 from, G_MARKUP_ERROR_PARSE,
662 _("Entity name '%-.*s' is not known"),
665 set_unescape_error (context, error,
666 from, G_MARKUP_ERROR_PARSE,
667 _("Entity did not end with a semicolon; "
668 "most likely you used an ampersand "
669 "character without intending to start "
670 "an entity - escape ampersand as &"));
677 g_assert (to - string->str <= string->len);
678 if (to - string->str != string->len)
679 g_string_truncate (string, to - string->str);
681 *is_ascii = !(mask & 0x80);
686 static inline gboolean
687 advance_char (GMarkupParseContext *context)
690 context->char_number++;
692 if (G_UNLIKELY (context->iter == context->current_text_end))
695 else if (G_UNLIKELY (*context->iter == '\n'))
697 context->line_number++;
698 context->char_number = 1;
704 static inline gboolean
707 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
711 skip_spaces (GMarkupParseContext *context)
715 if (!xml_isspace (*context->iter))
718 while (advance_char (context));
722 advance_to_name_end (GMarkupParseContext *context)
726 if (IS_COMMON_NAME_END_CHAR (*(context->iter)))
728 if (xml_isspace (*(context->iter)))
731 while (advance_char (context));
735 release_chunk (GMarkupParseContext *context, GString *str)
740 if (str->allocated_len > 256)
741 { /* large strings are unusual and worth freeing */
742 g_string_free (str, TRUE);
746 node = get_list_node (context, str);
747 context->spare_chunks = g_slist_concat (node, context->spare_chunks);
751 add_to_partial (GMarkupParseContext *context,
752 const gchar *text_start,
753 const gchar *text_end)
755 if (context->partial_chunk == NULL)
756 { /* allocate a new chunk to parse into */
758 if (context->spare_chunks != NULL)
760 GSList *node = context->spare_chunks;
761 context->spare_chunks = g_slist_remove_link (context->spare_chunks, node);
762 context->partial_chunk = node->data;
763 free_list_node (context, node);
766 context->partial_chunk = g_string_sized_new (MAX (28, text_end - text_start));
769 if (text_start != text_end)
770 g_string_insert_len (context->partial_chunk, -1,
771 text_start, text_end - text_start);
775 truncate_partial (GMarkupParseContext *context)
777 if (context->partial_chunk != NULL)
778 string_blank (context->partial_chunk);
781 static inline const gchar*
782 current_element (GMarkupParseContext *context)
784 return context->tag_stack->data;
788 pop_subparser_stack (GMarkupParseContext *context)
790 GMarkupRecursionTracker *tracker;
792 g_assert (context->subparser_stack);
794 tracker = context->subparser_stack->data;
796 context->awaiting_pop = TRUE;
797 context->held_user_data = context->user_data;
799 context->user_data = tracker->prev_user_data;
800 context->parser = tracker->prev_parser;
801 context->subparser_element = tracker->prev_element;
802 g_slice_free (GMarkupRecursionTracker, tracker);
804 context->subparser_stack = g_slist_delete_link (context->subparser_stack,
805 context->subparser_stack);
809 push_partial_as_tag (GMarkupParseContext *context)
811 GString *str = context->partial_chunk;
812 /* sadly, this is exported by gmarkup_get_element_stack as-is */
813 context->tag_stack = g_slist_concat (get_list_node (context, str->str), context->tag_stack);
814 context->tag_stack_gstr = g_slist_concat (get_list_node (context, str), context->tag_stack_gstr);
815 context->partial_chunk = NULL;
819 pop_tag (GMarkupParseContext *context)
821 GSList *nodea, *nodeb;
823 nodea = context->tag_stack;
824 nodeb = context->tag_stack_gstr;
825 release_chunk (context, nodeb->data);
826 context->tag_stack = g_slist_remove_link (context->tag_stack, nodea);
827 context->tag_stack_gstr = g_slist_remove_link (context->tag_stack_gstr, nodeb);
828 free_list_node (context, nodea);
829 free_list_node (context, nodeb);
833 possibly_finish_subparser (GMarkupParseContext *context)
835 if (current_element (context) == context->subparser_element)
836 pop_subparser_stack (context);
840 ensure_no_outstanding_subparser (GMarkupParseContext *context)
842 if (context->awaiting_pop)
843 g_critical ("During the first end_element call after invoking a "
844 "subparser you must pop the subparser stack and handle "
845 "the freeing of the subparser user_data. This can be "
846 "done by calling the end function of the subparser. "
847 "Very probably, your program just leaked memory.");
849 /* let valgrind watch the pointer disappear... */
850 context->held_user_data = NULL;
851 context->awaiting_pop = FALSE;
855 current_attribute (GMarkupParseContext *context)
857 g_assert (context->cur_attr >= 0);
858 return context->attr_names[context->cur_attr]->str;
862 add_attribute (GMarkupParseContext *context, GString *str)
864 if (context->cur_attr + 2 >= context->alloc_attrs)
866 context->alloc_attrs += 5; /* silly magic number */
867 context->attr_names = g_realloc (context->attr_names, sizeof(GString*)*context->alloc_attrs);
868 context->attr_values = g_realloc (context->attr_values, sizeof(GString*)*context->alloc_attrs);
871 context->attr_names[context->cur_attr] = str;
872 context->attr_values[context->cur_attr] = NULL;
873 context->attr_names[context->cur_attr+1] = NULL;
874 context->attr_values[context->cur_attr+1] = NULL;
878 clear_attributes (GMarkupParseContext *context)
880 /* Go ahead and free the attributes. */
881 for (; context->cur_attr >= 0; context->cur_attr--)
883 int pos = context->cur_attr;
884 release_chunk (context, context->attr_names[pos]);
885 release_chunk (context, context->attr_values[pos]);
886 context->attr_names[pos] = context->attr_values[pos] = NULL;
888 g_assert (context->cur_attr == -1);
889 g_assert (context->attr_names == NULL ||
890 context->attr_names[0] == NULL);
891 g_assert (context->attr_values == NULL ||
892 context->attr_values[0] == NULL);
895 /* This has to be a separate function to ensure the alloca's
896 are unwound on exit - otherwise we grow & blow the stack
897 with large documents */
899 emit_start_element (GMarkupParseContext *context, GError **error)
902 const gchar *start_name;
903 const gchar **attr_names;
904 const gchar **attr_values;
907 attr_names = g_newa (const gchar *, context->cur_attr + 2);
908 attr_values = g_newa (const gchar *, context->cur_attr + 2);
909 for (i = 0; i < context->cur_attr + 1; i++)
911 attr_names[i] = context->attr_names[i]->str;
912 attr_values[i] = context->attr_values[i]->str;
914 attr_names[i] = NULL;
915 attr_values[i] = NULL;
917 /* Call user callback for element start */
919 start_name = current_element (context);
921 if (context->parser->start_element &&
922 name_validate (context, start_name, error))
923 (* context->parser->start_element) (context,
925 (const gchar **)attr_names,
926 (const gchar **)attr_values,
929 clear_attributes (context);
931 if (tmp_error != NULL)
932 propagate_error (context, error, tmp_error);
936 * g_markup_parse_context_parse:
937 * @context: a #GMarkupParseContext
938 * @text: chunk of text to parse
939 * @text_len: length of @text in bytes
940 * @error: return location for a #GError
942 * Feed some data to the #GMarkupParseContext. The data need not
943 * be valid UTF-8; an error will be signaled if it's invalid.
944 * The data need not be an entire document; you can feed a document
945 * into the parser incrementally, via multiple calls to this function.
946 * Typically, as you receive data from a network connection or file,
947 * you feed each received chunk of data into this function, aborting
948 * the process if an error occurs. Once an error is reported, no further
949 * data may be fed to the #GMarkupParseContext; all errors are fatal.
951 * Return value: %FALSE if an error occurred, %TRUE on success
954 g_markup_parse_context_parse (GMarkupParseContext *context,
959 g_return_val_if_fail (context != NULL, FALSE);
960 g_return_val_if_fail (text != NULL, FALSE);
961 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
962 g_return_val_if_fail (!context->parsing, FALSE);
965 text_len = strlen (text);
970 context->parsing = TRUE;
973 context->current_text = text;
974 context->current_text_len = text_len;
975 context->current_text_end = context->current_text + text_len;
976 context->iter = context->current_text;
977 context->start = context->iter;
979 if (context->current_text_len == 0)
982 while (context->iter != context->current_text_end)
984 switch (context->state)
987 /* Possible next state: AFTER_OPEN_ANGLE */
989 g_assert (context->tag_stack == NULL);
991 /* whitespace is ignored outside of any elements */
992 skip_spaces (context);
994 if (context->iter != context->current_text_end)
996 if (*context->iter == '<')
998 /* Move after the open angle */
999 advance_char (context);
1001 context->state = STATE_AFTER_OPEN_ANGLE;
1003 /* this could start a passthrough */
1004 context->start = context->iter;
1006 /* document is now non-empty */
1007 context->document_empty = FALSE;
1011 set_error_literal (context,
1013 G_MARKUP_ERROR_PARSE,
1014 _("Document must begin with an element (e.g. <book>)"));
1019 case STATE_AFTER_OPEN_ANGLE:
1020 /* Possible next states: INSIDE_OPEN_TAG_NAME,
1021 * AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1023 if (*context->iter == '?' ||
1024 *context->iter == '!')
1026 /* include < in the passthrough */
1027 const gchar *openangle = "<";
1028 add_to_partial (context, openangle, openangle + 1);
1029 context->start = context->iter;
1030 context->balance = 1;
1031 context->state = STATE_INSIDE_PASSTHROUGH;
1033 else if (*context->iter == '/')
1036 advance_char (context);
1038 context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1040 else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1042 context->state = STATE_INSIDE_OPEN_TAG_NAME;
1044 /* start of tag name */
1045 context->start = context->iter;
1053 G_MARKUP_ERROR_PARSE,
1054 _("'%s' is not a valid character following "
1055 "a '<' character; it may not begin an "
1057 utf8_str (context->iter, buf));
1061 /* The AFTER_CLOSE_ANGLE state is actually sort of
1062 * broken, because it doesn't correspond to a range
1063 * of characters in the input stream as the others do,
1064 * and thus makes things harder to conceptualize
1066 case STATE_AFTER_CLOSE_ANGLE:
1067 /* Possible next states: INSIDE_TEXT, STATE_START */
1068 if (context->tag_stack == NULL)
1070 context->start = NULL;
1071 context->state = STATE_START;
1075 context->start = context->iter;
1076 context->state = STATE_INSIDE_TEXT;
1080 case STATE_AFTER_ELISION_SLASH:
1081 /* Possible next state: AFTER_CLOSE_ANGLE */
1084 /* We need to pop the tag stack and call the end_element
1085 * function, since this is the close tag
1087 GError *tmp_error = NULL;
1089 g_assert (context->tag_stack != NULL);
1091 possibly_finish_subparser (context);
1094 if (context->parser->end_element)
1095 (* context->parser->end_element) (context,
1096 current_element (context),
1100 ensure_no_outstanding_subparser (context);
1104 mark_error (context, tmp_error);
1105 g_propagate_error (error, tmp_error);
1109 if (*context->iter == '>')
1111 /* move after the close angle */
1112 advance_char (context);
1113 context->state = STATE_AFTER_CLOSE_ANGLE;
1121 G_MARKUP_ERROR_PARSE,
1122 _("Odd character '%s', expected a '>' character "
1123 "to end the empty-element tag '%s'"),
1124 utf8_str (context->iter, buf),
1125 current_element (context));
1132 case STATE_INSIDE_OPEN_TAG_NAME:
1133 /* Possible next states: BETWEEN_ATTRIBUTES */
1135 /* if there's a partial chunk then it's the first part of the
1136 * tag name. If there's a context->start then it's the start
1137 * of the tag name in current_text, the partial chunk goes
1138 * before that start though.
1140 advance_to_name_end (context);
1142 if (context->iter == context->current_text_end)
1144 /* The name hasn't necessarily ended. Merge with
1145 * partial chunk, leave state unchanged.
1147 add_to_partial (context, context->start, context->iter);
1151 /* The name has ended. Combine it with the partial chunk
1152 * if any; push it on the stack; enter next state.
1154 add_to_partial (context, context->start, context->iter);
1155 push_partial_as_tag (context);
1157 context->state = STATE_BETWEEN_ATTRIBUTES;
1158 context->start = NULL;
1162 case STATE_INSIDE_ATTRIBUTE_NAME:
1163 /* Possible next states: AFTER_ATTRIBUTE_NAME */
1165 advance_to_name_end (context);
1166 add_to_partial (context, context->start, context->iter);
1168 /* read the full name, if we enter the equals sign state
1169 * then add the attribute to the list (without the value),
1170 * otherwise store a partial chunk to be prepended later.
1172 if (context->iter != context->current_text_end)
1173 context->state = STATE_AFTER_ATTRIBUTE_NAME;
1176 case STATE_AFTER_ATTRIBUTE_NAME:
1177 /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1179 skip_spaces (context);
1181 if (context->iter != context->current_text_end)
1183 /* The name has ended. Combine it with the partial chunk
1184 * if any; push it on the stack; enter next state.
1186 if (!name_validate (context, context->partial_chunk->str, error))
1189 add_attribute (context, context->partial_chunk);
1191 context->partial_chunk = NULL;
1192 context->start = NULL;
1194 if (*context->iter == '=')
1196 advance_char (context);
1197 context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1205 G_MARKUP_ERROR_PARSE,
1206 _("Odd character '%s', expected a '=' after "
1207 "attribute name '%s' of element '%s'"),
1208 utf8_str (context->iter, buf),
1209 current_attribute (context),
1210 current_element (context));
1216 case STATE_BETWEEN_ATTRIBUTES:
1217 /* Possible next states: AFTER_CLOSE_ANGLE,
1218 * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1220 skip_spaces (context);
1222 if (context->iter != context->current_text_end)
1224 if (*context->iter == '/')
1226 advance_char (context);
1227 context->state = STATE_AFTER_ELISION_SLASH;
1229 else if (*context->iter == '>')
1231 advance_char (context);
1232 context->state = STATE_AFTER_CLOSE_ANGLE;
1234 else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1236 context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1237 /* start of attribute name */
1238 context->start = context->iter;
1246 G_MARKUP_ERROR_PARSE,
1247 _("Odd character '%s', expected a '>' or '/' "
1248 "character to end the start tag of "
1249 "element '%s', or optionally an attribute; "
1250 "perhaps you used an invalid character in "
1251 "an attribute name"),
1252 utf8_str (context->iter, buf),
1253 current_element (context));
1256 /* If we're done with attributes, invoke
1257 * the start_element callback
1259 if (context->state == STATE_AFTER_ELISION_SLASH ||
1260 context->state == STATE_AFTER_CLOSE_ANGLE)
1261 emit_start_element (context, error);
1265 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1266 /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1268 skip_spaces (context);
1270 if (context->iter != context->current_text_end)
1272 if (*context->iter == '"')
1274 advance_char (context);
1275 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1276 context->start = context->iter;
1278 else if (*context->iter == '\'')
1280 advance_char (context);
1281 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1282 context->start = context->iter;
1290 G_MARKUP_ERROR_PARSE,
1291 _("Odd character '%s', expected an open quote mark "
1292 "after the equals sign when giving value for "
1293 "attribute '%s' of element '%s'"),
1294 utf8_str (context->iter, buf),
1295 current_attribute (context),
1296 current_element (context));
1301 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1302 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1303 /* Possible next states: BETWEEN_ATTRIBUTES */
1307 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ)
1318 if (*context->iter == delim)
1321 while (advance_char (context));
1323 if (context->iter == context->current_text_end)
1325 /* The value hasn't necessarily ended. Merge with
1326 * partial chunk, leave state unchanged.
1328 add_to_partial (context, context->start, context->iter);
1333 /* The value has ended at the quote mark. Combine it
1334 * with the partial chunk if any; set it for the current
1337 add_to_partial (context, context->start, context->iter);
1339 g_assert (context->cur_attr >= 0);
1341 if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1342 (is_ascii || text_validate (context, context->partial_chunk->str,
1343 context->partial_chunk->len, error)))
1345 /* success, advance past quote and set state. */
1346 context->attr_values[context->cur_attr] = context->partial_chunk;
1347 context->partial_chunk = NULL;
1348 advance_char (context);
1349 context->state = STATE_BETWEEN_ATTRIBUTES;
1350 context->start = NULL;
1353 truncate_partial (context);
1357 case STATE_INSIDE_TEXT:
1358 /* Possible next states: AFTER_OPEN_ANGLE */
1361 if (*context->iter == '<')
1364 while (advance_char (context));
1366 /* The text hasn't necessarily ended. Merge with
1367 * partial chunk, leave state unchanged.
1370 add_to_partial (context, context->start, context->iter);
1372 if (context->iter != context->current_text_end)
1376 /* The text has ended at the open angle. Call the text
1380 if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1381 (is_ascii || text_validate (context, context->partial_chunk->str,
1382 context->partial_chunk->len, error)))
1384 GError *tmp_error = NULL;
1386 if (context->parser->text)
1387 (*context->parser->text) (context,
1388 context->partial_chunk->str,
1389 context->partial_chunk->len,
1393 if (tmp_error == NULL)
1395 /* advance past open angle and set state. */
1396 advance_char (context);
1397 context->state = STATE_AFTER_OPEN_ANGLE;
1398 /* could begin a passthrough */
1399 context->start = context->iter;
1402 propagate_error (context, error, tmp_error);
1405 truncate_partial (context);
1409 case STATE_AFTER_CLOSE_TAG_SLASH:
1410 /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1411 if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1413 context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1415 /* start of tag name */
1416 context->start = context->iter;
1424 G_MARKUP_ERROR_PARSE,
1425 _("'%s' is not a valid character following "
1426 "the characters '</'; '%s' may not begin an "
1428 utf8_str (context->iter, buf),
1429 utf8_str (context->iter, buf));
1433 case STATE_INSIDE_CLOSE_TAG_NAME:
1434 /* Possible next state: AFTER_CLOSE_TAG_NAME */
1435 advance_to_name_end (context);
1436 add_to_partial (context, context->start, context->iter);
1438 if (context->iter != context->current_text_end)
1439 context->state = STATE_AFTER_CLOSE_TAG_NAME;
1442 case STATE_AFTER_CLOSE_TAG_NAME:
1443 /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1445 skip_spaces (context);
1447 if (context->iter != context->current_text_end)
1449 GString *close_name;
1451 close_name = context->partial_chunk;
1452 context->partial_chunk = NULL;
1454 if (*context->iter != '>')
1460 G_MARKUP_ERROR_PARSE,
1461 _("'%s' is not a valid character following "
1462 "the close element name '%s'; the allowed "
1463 "character is '>'"),
1464 utf8_str (context->iter, buf),
1467 else if (context->tag_stack == NULL)
1471 G_MARKUP_ERROR_PARSE,
1472 _("Element '%s' was closed, no element "
1473 "is currently open"),
1476 else if (strcmp (close_name->str, current_element (context)) != 0)
1480 G_MARKUP_ERROR_PARSE,
1481 _("Element '%s' was closed, but the currently "
1482 "open element is '%s'"),
1484 current_element (context));
1489 advance_char (context);
1490 context->state = STATE_AFTER_CLOSE_ANGLE;
1491 context->start = NULL;
1493 possibly_finish_subparser (context);
1495 /* call the end_element callback */
1497 if (context->parser->end_element)
1498 (* context->parser->end_element) (context,
1503 ensure_no_outstanding_subparser (context);
1507 propagate_error (context, error, tmp_error);
1509 context->partial_chunk = close_name;
1510 truncate_partial (context);
1514 case STATE_INSIDE_PASSTHROUGH:
1515 /* Possible next state: AFTER_CLOSE_ANGLE */
1518 if (*context->iter == '<')
1520 if (*context->iter == '>')
1526 add_to_partial (context, context->start, context->iter);
1527 context->start = context->iter;
1529 str = context->partial_chunk->str;
1530 len = context->partial_chunk->len;
1532 if (str[1] == '?' && str[len - 1] == '?')
1534 if (strncmp (str, "<!--", 4) == 0 &&
1535 strcmp (str + len - 2, "--") == 0)
1537 if (strncmp (str, "<![CDATA[", 9) == 0 &&
1538 strcmp (str + len - 2, "]]") == 0)
1540 if (strncmp (str, "<!DOCTYPE", 9) == 0 &&
1541 context->balance == 0)
1545 while (advance_char (context));
1547 if (context->iter == context->current_text_end)
1549 /* The passthrough hasn't necessarily ended. Merge with
1550 * partial chunk, leave state unchanged.
1552 add_to_partial (context, context->start, context->iter);
1556 /* The passthrough has ended at the close angle. Combine
1557 * it with the partial chunk if any. Call the passthrough
1558 * callback. Note that the open/close angles are
1559 * included in the text of the passthrough.
1561 GError *tmp_error = NULL;
1563 advance_char (context); /* advance past close angle */
1564 add_to_partial (context, context->start, context->iter);
1566 if (context->flags & G_MARKUP_TREAT_CDATA_AS_TEXT &&
1567 strncmp (context->partial_chunk->str, "<![CDATA[", 9) == 0)
1569 if (context->parser->text &&
1570 text_validate (context,
1571 context->partial_chunk->str + 9,
1572 context->partial_chunk->len - 12,
1574 (*context->parser->text) (context,
1575 context->partial_chunk->str + 9,
1576 context->partial_chunk->len - 12,
1580 else if (context->parser->passthrough &&
1581 text_validate (context,
1582 context->partial_chunk->str,
1583 context->partial_chunk->len,
1585 (*context->parser->passthrough) (context,
1586 context->partial_chunk->str,
1587 context->partial_chunk->len,
1591 truncate_partial (context);
1593 if (tmp_error == NULL)
1595 context->state = STATE_AFTER_CLOSE_ANGLE;
1596 context->start = context->iter; /* could begin text */
1599 propagate_error (context, error, tmp_error);
1608 g_assert_not_reached ();
1614 context->parsing = FALSE;
1616 return context->state != STATE_ERROR;
1620 * g_markup_parse_context_end_parse:
1621 * @context: a #GMarkupParseContext
1622 * @error: return location for a #GError
1624 * Signals to the #GMarkupParseContext that all data has been
1625 * fed into the parse context with g_markup_parse_context_parse().
1626 * This function reports an error if the document isn't complete,
1627 * for example if elements are still open.
1629 * Return value: %TRUE on success, %FALSE if an error was set
1632 g_markup_parse_context_end_parse (GMarkupParseContext *context,
1635 g_return_val_if_fail (context != NULL, FALSE);
1636 g_return_val_if_fail (!context->parsing, FALSE);
1637 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1639 if (context->partial_chunk != NULL)
1641 g_string_free (context->partial_chunk, TRUE);
1642 context->partial_chunk = NULL;
1645 if (context->document_empty)
1647 set_error_literal (context, error, G_MARKUP_ERROR_EMPTY,
1648 _("Document was empty or contained only whitespace"));
1652 context->parsing = TRUE;
1654 switch (context->state)
1660 case STATE_AFTER_OPEN_ANGLE:
1661 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1662 _("Document ended unexpectedly just after an open angle bracket '<'"));
1665 case STATE_AFTER_CLOSE_ANGLE:
1666 if (context->tag_stack != NULL)
1668 /* Error message the same as for INSIDE_TEXT */
1669 set_error (context, error, G_MARKUP_ERROR_PARSE,
1670 _("Document ended unexpectedly with elements still open - "
1671 "'%s' was the last element opened"),
1672 current_element (context));
1676 case STATE_AFTER_ELISION_SLASH:
1677 set_error (context, error, G_MARKUP_ERROR_PARSE,
1678 _("Document ended unexpectedly, expected to see a close angle "
1679 "bracket ending the tag <%s/>"), current_element (context));
1682 case STATE_INSIDE_OPEN_TAG_NAME:
1683 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1684 _("Document ended unexpectedly inside an element name"));
1687 case STATE_INSIDE_ATTRIBUTE_NAME:
1688 case STATE_AFTER_ATTRIBUTE_NAME:
1689 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1690 _("Document ended unexpectedly inside an attribute name"));
1693 case STATE_BETWEEN_ATTRIBUTES:
1694 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1695 _("Document ended unexpectedly inside an element-opening "
1699 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1700 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1701 _("Document ended unexpectedly after the equals sign "
1702 "following an attribute name; no attribute value"));
1705 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1706 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1707 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1708 _("Document ended unexpectedly while inside an attribute "
1712 case STATE_INSIDE_TEXT:
1713 g_assert (context->tag_stack != NULL);
1714 set_error (context, error, G_MARKUP_ERROR_PARSE,
1715 _("Document ended unexpectedly with elements still open - "
1716 "'%s' was the last element opened"),
1717 current_element (context));
1720 case STATE_AFTER_CLOSE_TAG_SLASH:
1721 case STATE_INSIDE_CLOSE_TAG_NAME:
1722 case STATE_AFTER_CLOSE_TAG_NAME:
1723 set_error (context, error, G_MARKUP_ERROR_PARSE,
1724 _("Document ended unexpectedly inside the close tag for "
1725 "element '%s'"), current_element (context));
1728 case STATE_INSIDE_PASSTHROUGH:
1729 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1730 _("Document ended unexpectedly inside a comment or "
1731 "processing instruction"));
1736 g_assert_not_reached ();
1740 context->parsing = FALSE;
1742 return context->state != STATE_ERROR;
1746 * g_markup_parse_context_get_element:
1747 * @context: a #GMarkupParseContext
1748 * @returns: the name of the currently open element, or %NULL
1750 * Retrieves the name of the currently open element.
1752 * If called from the start_element or end_element handlers this will
1753 * give the element_name as passed to those functions. For the parent
1754 * elements, see g_markup_parse_context_get_element_stack().
1758 G_CONST_RETURN gchar *
1759 g_markup_parse_context_get_element (GMarkupParseContext *context)
1761 g_return_val_if_fail (context != NULL, NULL);
1763 if (context->tag_stack == NULL)
1766 return current_element (context);
1770 * g_markup_parse_context_get_element_stack:
1771 * @context: a #GMarkupParseContext
1773 * Retrieves the element stack from the internal state of the parser.
1774 * The returned #GSList is a list of strings where the first item is
1775 * the currently open tag (as would be returned by
1776 * g_markup_parse_context_get_element()) and the next item is its
1779 * This function is intended to be used in the start_element and
1780 * end_element handlers where g_markup_parse_context_get_element()
1781 * would merely return the name of the element that is being
1784 * Returns: the element stack, which must not be modified
1788 G_CONST_RETURN GSList *
1789 g_markup_parse_context_get_element_stack (GMarkupParseContext *context)
1791 g_return_val_if_fail (context != NULL, NULL);
1792 return context->tag_stack;
1796 * g_markup_parse_context_get_position:
1797 * @context: a #GMarkupParseContext
1798 * @line_number: return location for a line number, or %NULL
1799 * @char_number: return location for a char-on-line number, or %NULL
1801 * Retrieves the current line number and the number of the character on
1802 * that line. Intended for use in error messages; there are no strict
1803 * semantics for what constitutes the "current" line number other than
1804 * "the best number we could come up with for error messages."
1808 g_markup_parse_context_get_position (GMarkupParseContext *context,
1812 g_return_if_fail (context != NULL);
1815 *line_number = context->line_number;
1818 *char_number = context->char_number;
1822 * g_markup_parse_context_get_user_data:
1823 * @context: a #GMarkupParseContext
1825 * Returns the user_data associated with @context. This will either
1826 * be the user_data that was provided to g_markup_parse_context_new()
1827 * or to the most recent call of g_markup_parse_context_push().
1829 * Returns: the provided user_data. The returned data belongs to
1830 * the markup context and will be freed when g_markup_context_free()
1836 g_markup_parse_context_get_user_data (GMarkupParseContext *context)
1838 return context->user_data;
1842 * g_markup_parse_context_push:
1843 * @context: a #GMarkupParseContext
1844 * @parser: a #GMarkupParser
1845 * @user_data: user data to pass to #GMarkupParser functions
1847 * Temporarily redirects markup data to a sub-parser.
1849 * This function may only be called from the start_element handler of
1850 * a #GMarkupParser. It must be matched with a corresponding call to
1851 * g_markup_parse_context_pop() in the matching end_element handler
1852 * (except in the case that the parser aborts due to an error).
1854 * All tags, text and other data between the matching tags is
1855 * redirected to the subparser given by @parser. @user_data is used
1856 * as the user_data for that parser. @user_data is also passed to the
1857 * error callback in the event that an error occurs. This includes
1858 * errors that occur in subparsers of the subparser.
1860 * The end tag matching the start tag for which this call was made is
1861 * handled by the previous parser (which is given its own user_data)
1862 * which is why g_markup_parse_context_pop() is provided to allow "one
1863 * last access" to the @user_data provided to this function. In the
1864 * case of error, the @user_data provided here is passed directly to
1865 * the error callback of the subparser and g_markup_parse_context()
1866 * should not be called. In either case, if @user_data was allocated
1867 * then it ought to be freed from both of these locations.
1869 * This function is not intended to be directly called by users
1870 * interested in invoking subparsers. Instead, it is intended to be
1871 * used by the subparsers themselves to implement a higher-level
1874 * As an example, see the following implementation of a simple
1875 * parser that counts the number of tags encountered.
1884 * counter_start_element (GMarkupParseContext *context,
1885 * const gchar *element_name,
1886 * const gchar **attribute_names,
1887 * const gchar **attribute_values,
1888 * gpointer user_data,
1891 * CounterData *data = user_data;
1893 * data->tag_count++;
1897 * counter_error (GMarkupParseContext *context,
1899 * gpointer user_data)
1901 * CounterData *data = user_data;
1903 * g_slice_free (CounterData, data);
1906 * static GMarkupParser counter_subparser =
1908 * counter_start_element,
1916 * In order to allow this parser to be easily used as a subparser, the
1917 * following interface is provided:
1921 * start_counting (GMarkupParseContext *context)
1923 * CounterData *data = g_slice_new (CounterData);
1925 * data->tag_count = 0;
1926 * g_markup_parse_context_push (context, &counter_subparser, data);
1930 * end_counting (GMarkupParseContext *context)
1932 * CounterData *data = g_markup_parse_context_pop (context);
1935 * result = data->tag_count;
1936 * g_slice_free (CounterData, data);
1942 * The subparser would then be used as follows:
1945 * static void start_element (context, element_name, ...)
1947 * if (strcmp (element_name, "count-these") == 0)
1948 * start_counting (context);
1950 * /* else, handle other tags... */
1953 * static void end_element (context, element_name, ...)
1955 * if (strcmp (element_name, "count-these") == 0)
1956 * g_print ("Counted %d tags\n", end_counting (context));
1958 * /* else, handle other tags... */
1965 g_markup_parse_context_push (GMarkupParseContext *context,
1966 GMarkupParser *parser,
1969 GMarkupRecursionTracker *tracker;
1971 tracker = g_slice_new (GMarkupRecursionTracker);
1972 tracker->prev_element = context->subparser_element;
1973 tracker->prev_parser = context->parser;
1974 tracker->prev_user_data = context->user_data;
1976 context->subparser_element = current_element (context);
1977 context->parser = parser;
1978 context->user_data = user_data;
1980 context->subparser_stack = g_slist_prepend (context->subparser_stack,
1985 * g_markup_parse_context_pop:
1986 * @context: a #GMarkupParseContext
1988 * Completes the process of a temporary sub-parser redirection.
1990 * This function exists to collect the user_data allocated by a
1991 * matching call to g_markup_parse_context_push(). It must be called
1992 * in the end_element handler corresponding to the start_element
1993 * handler during which g_markup_parse_context_push() was called. You
1994 * must not call this function from the error callback -- the
1995 * @user_data is provided directly to the callback in that case.
1997 * This function is not intended to be directly called by users
1998 * interested in invoking subparsers. Instead, it is intended to be
1999 * used by the subparsers themselves to implement a higher-level
2002 * Returns: the user_data passed to g_markup_parse_context_push().
2007 g_markup_parse_context_pop (GMarkupParseContext *context)
2011 if (!context->awaiting_pop)
2012 possibly_finish_subparser (context);
2014 g_assert (context->awaiting_pop);
2016 context->awaiting_pop = FALSE;
2018 /* valgrind friendliness */
2019 user_data = context->held_user_data;
2020 context->held_user_data = NULL;
2026 append_escaped_text (GString *str,
2035 end = text + length;
2040 next = g_utf8_next_char (p);
2045 g_string_append (str, "&");
2049 g_string_append (str, "<");
2053 g_string_append (str, ">");
2057 g_string_append (str, "'");
2061 g_string_append (str, """);
2065 c = g_utf8_get_char (p);
2066 if ((0x1 <= c && c <= 0x8) ||
2067 (0xb <= c && c <= 0xc) ||
2068 (0xe <= c && c <= 0x1f) ||
2069 (0x7f <= c && c <= 0x84) ||
2070 (0x86 <= c && c <= 0x9f))
2071 g_string_append_printf (str, "&#x%x;", c);
2073 g_string_append_len (str, p, next - p);
2082 * g_markup_escape_text:
2083 * @text: some valid UTF-8 text
2084 * @length: length of @text in bytes, or -1 if the text is nul-terminated
2086 * Escapes text so that the markup parser will parse it verbatim.
2087 * Less than, greater than, ampersand, etc. are replaced with the
2088 * corresponding entities. This function would typically be used
2089 * when writing out a file to be parsed with the markup parser.
2091 * Note that this function doesn't protect whitespace and line endings
2092 * from being processed according to the XML rules for normalization
2093 * of line endings and attribute values.
2095 * Note also that this function will produce character references in
2096 * the range of &#x1; ... &#x1f; for all control sequences
2097 * except for tabstop, newline and carriage return. The character
2098 * references in this range are not valid XML 1.0, but they are
2099 * valid XML 1.1 and will be accepted by the GMarkup parser.
2101 * Return value: a newly allocated string with the escaped text
2104 g_markup_escape_text (const gchar *text,
2109 g_return_val_if_fail (text != NULL, NULL);
2112 length = strlen (text);
2114 /* prealloc at least as long as original text */
2115 str = g_string_sized_new (length);
2116 append_escaped_text (str, text, length);
2118 return g_string_free (str, FALSE);
2123 * @format: a printf-style format string
2124 * @after: location to store a pointer to the character after
2125 * the returned conversion. On a %NULL return, returns the
2126 * pointer to the trailing NUL in the string
2128 * Find the next conversion in a printf-style format string.
2129 * Partially based on code from printf-parser.c,
2130 * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
2132 * Return value: pointer to the next conversion in @format,
2133 * or %NULL, if none.
2136 find_conversion (const char *format,
2139 const char *start = format;
2142 while (*start != '\0' && *start != '%')
2159 /* Test for positional argument. */
2160 if (*cp >= '0' && *cp <= '9')
2164 for (np = cp; *np >= '0' && *np <= '9'; np++)
2170 /* Skip the flags. */
2184 /* Skip the field width. */
2189 /* Test for positional argument. */
2190 if (*cp >= '0' && *cp <= '9')
2194 for (np = cp; *np >= '0' && *np <= '9'; np++)
2202 for (; *cp >= '0' && *cp <= '9'; cp++)
2206 /* Skip the precision. */
2212 /* Test for positional argument. */
2213 if (*cp >= '0' && *cp <= '9')
2217 for (np = cp; *np >= '0' && *np <= '9'; np++)
2225 for (; *cp >= '0' && *cp <= '9'; cp++)
2230 /* Skip argument type/size specifiers. */
2231 while (*cp == 'h' ||
2240 /* Skip the conversion character. */
2248 * g_markup_vprintf_escaped:
2249 * @format: printf() style format string
2250 * @args: variable argument list, similar to vprintf()
2252 * Formats the data in @args according to @format, escaping
2253 * all string and character arguments in the fashion
2254 * of g_markup_escape_text(). See g_markup_printf_escaped().
2256 * Return value: newly allocated result from formatting
2257 * operation. Free with g_free().
2262 g_markup_vprintf_escaped (const char *format,
2267 GString *result = NULL;
2268 gchar *output1 = NULL;
2269 gchar *output2 = NULL;
2270 const char *p, *op1, *op2;
2273 /* The technique here, is that we make two format strings that
2274 * have the identical conversions in the identical order to the
2275 * original strings, but differ in the text in-between. We
2276 * then use the normal g_strdup_vprintf() to format the arguments
2277 * with the two new format strings. By comparing the results,
2278 * we can figure out what segments of the output come from
2279 * the the original format string, and what from the arguments,
2280 * and thus know what portions of the string to escape.
2282 * For instance, for:
2284 * g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2286 * We form the two format strings "%sX%dX" and %sY%sY". The results
2287 * of formatting with those two strings are
2289 * "%sX%dX" => "Susan & FredX5X"
2290 * "%sY%dY" => "Susan & FredY5Y"
2292 * To find the span of the first argument, we find the first position
2293 * where the two arguments differ, which tells us that the first
2294 * argument formatted to "Susan & Fred". We then escape that
2295 * to "Susan & Fred" and join up with the intermediate portions
2296 * of the format string and the second argument to get
2297 * "Susan & Fred ate 5 apples".
2300 /* Create the two modified format strings
2302 format1 = g_string_new (NULL);
2303 format2 = g_string_new (NULL);
2308 const char *conv = find_conversion (p, &after);
2312 g_string_append_len (format1, conv, after - conv);
2313 g_string_append_c (format1, 'X');
2314 g_string_append_len (format2, conv, after - conv);
2315 g_string_append_c (format2, 'Y');
2320 /* Use them to format the arguments
2322 G_VA_COPY (args2, args);
2324 output1 = g_strdup_vprintf (format1->str, args);
2331 output2 = g_strdup_vprintf (format2->str, args2);
2336 result = g_string_new (NULL);
2338 /* Iterate through the original format string again,
2339 * copying the non-conversion portions and the escaped
2340 * converted arguments to the output string.
2348 const char *output_start;
2349 const char *conv = find_conversion (p, &after);
2352 if (!conv) /* The end, after points to the trailing \0 */
2354 g_string_append_len (result, p, after - p);
2358 g_string_append_len (result, p, conv - p);
2360 while (*op1 == *op2)
2366 escaped = g_markup_escape_text (output_start, op1 - output_start);
2367 g_string_append (result, escaped);
2376 g_string_free (format1, TRUE);
2377 g_string_free (format2, TRUE);
2382 return g_string_free (result, FALSE);
2388 * g_markup_printf_escaped:
2389 * @format: printf() style format string
2390 * @Varargs: the arguments to insert in the format string
2392 * Formats arguments according to @format, escaping
2393 * all string and character arguments in the fashion
2394 * of g_markup_escape_text(). This is useful when you
2395 * want to insert literal strings into XML-style markup
2396 * output, without having to worry that the strings
2397 * might themselves contain markup.
2400 * const char *store = "Fortnum & Mason";
2401 * const char *item = "Tea";
2404 * output = g_markup_printf_escaped ("<purchase>"
2405 * "<store>%s</store>"
2406 * "<item>%s</item>"
2407 * "</purchase>",
2411 * Return value: newly allocated result from formatting
2412 * operation. Free with g_free().
2417 g_markup_printf_escaped (const char *format, ...)
2422 va_start (args, format);
2423 result = g_markup_vprintf_escaped (format, args);
2430 g_markup_parse_boolean (const char *string,
2433 char const * const falses[] = { "false", "f", "no", "n", "0" };
2434 char const * const trues[] = { "true", "t", "yes", "y", "1" };
2437 for (i = 0; i < G_N_ELEMENTS (falses); i++)
2439 if (g_ascii_strcasecmp (string, falses[i]) == 0)
2448 for (i = 0; i < G_N_ELEMENTS (trues); i++)
2450 if (g_ascii_strcasecmp (string, trues[i]) == 0)
2463 * GMarkupCollectType:
2464 * @G_MARKUP_COLLECT_INVALID: used to terminate the list of attributes
2466 * @G_MARKUP_COLLECT_STRING: collect the string pointer directly from
2467 * the attribute_values[] array. Expects a
2468 * parameter of type (const char **). If
2469 * %G_MARKUP_COLLECT_OPTIONAL is specified
2470 * and the attribute isn't present then the
2471 * pointer will be set to %NULL.
2472 * @G_MARKUP_COLLECT_STRDUP: as with %G_MARKUP_COLLECT_STRING, but
2473 * expects a parameter of type (char **) and
2474 * g_strdup()s the returned pointer. The
2475 * pointer must be freed with g_free().
2476 * @G_MARKUP_COLLECT_BOOLEAN: expects a parameter of type (gboolean *)
2477 * and parses the attribute value as a
2478 * boolean. Sets %FALSE if the attribute
2479 * isn't present. Valid boolean values
2480 * consist of (case insensitive) "false",
2481 * "f", "no", "n", "0" and "true", "t",
2483 * @G_MARKUP_COLLECT_TRISTATE: as with %G_MARKUP_COLLECT_BOOLEAN, but
2484 * in the case of a missing attribute a
2485 * value is set that compares equal to
2486 * neither %FALSE nor %TRUE.
2487 * G_MARKUP_COLLECT_OPTIONAL is implied.
2488 * @G_MARKUP_COLLECT_OPTIONAL: can be bitwise ORed with the other
2489 * fields. If present, allows the
2490 * attribute not to appear. A default
2491 * value is set depending on what value
2494 * A mixed enumerated type and flags field. You must specify one type
2495 * (string, strdup, boolean, tristate). Additionally, you may
2496 * optionally bitwise OR the type with the flag
2497 * %G_MARKUP_COLLECT_OPTIONAL.
2499 * It is likely that this enum will be extended in the future to
2500 * support other types.
2504 * g_markup_collect_attributes:
2505 * @element_name: the current tag name
2506 * @attribute_names: the attribute names
2507 * @attribute_values: the attribute values
2508 * @error: a pointer to a #GError or %NULL
2509 * @first_type: the #GMarkupCollectType of the
2511 * @first_attr: the name of the first attribute
2512 * @...: a pointer to the storage location of the
2513 * first attribute (or %NULL), followed by
2514 * more types names and pointers, ending
2515 * with %G_MARKUP_COLLECT_INVALID.
2517 * Collects the attributes of the element from the
2518 * data passed to the #GMarkupParser start_element
2519 * function, dealing with common error conditions
2520 * and supporting boolean values.
2522 * This utility function is not required to write
2523 * a parser but can save a lot of typing.
2525 * The @element_name, @attribute_names,
2526 * @attribute_values and @error parameters passed
2527 * to the start_element callback should be passed
2528 * unmodified to this function.
2530 * Following these arguments is a list of
2531 * "supported" attributes to collect. It is an
2532 * error to specify multiple attributes with the
2533 * same name. If any attribute not in the list
2534 * appears in the @attribute_names array then an
2535 * unknown attribute error will result.
2537 * The #GMarkupCollectType field allows specifying
2538 * the type of collection to perform and if a
2539 * given attribute must appear or is optional.
2541 * The attribute name is simply the name of the
2542 * attribute to collect.
2544 * The pointer should be of the appropriate type
2545 * (see the descriptions under
2546 * #GMarkupCollectType) and may be %NULL in case a
2547 * particular attribute is to be allowed but
2550 * This function deals with issuing errors for missing attributes
2551 * (of type %G_MARKUP_ERROR_MISSING_ATTRIBUTE), unknown attributes
2552 * (of type %G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE) and duplicate
2553 * attributes (of type %G_MARKUP_ERROR_INVALID_CONTENT) as well
2554 * as parse errors for boolean-valued attributes (again of type
2555 * %G_MARKUP_ERROR_INVALID_CONTENT). In all of these cases %FALSE
2556 * will be returned and @error will be set as appropriate.
2558 * Return value: %TRUE if successful
2563 g_markup_collect_attributes (const gchar *element_name,
2564 const gchar **attribute_names,
2565 const gchar **attribute_values,
2567 GMarkupCollectType first_type,
2568 const gchar *first_attr,
2571 GMarkupCollectType type;
2583 va_start (ap, first_attr);
2584 while (type != G_MARKUP_COLLECT_INVALID)
2589 mandatory = !(type & G_MARKUP_COLLECT_OPTIONAL);
2590 type &= (G_MARKUP_COLLECT_OPTIONAL - 1);
2592 /* tristate records a value != TRUE and != FALSE
2593 * for the case where the attribute is missing
2595 if (type == G_MARKUP_COLLECT_TRISTATE)
2598 for (i = 0; attribute_names[i]; i++)
2599 if (i >= 40 || !(collected & (G_GUINT64_CONSTANT(1) << i)))
2600 if (!strcmp (attribute_names[i], attr))
2603 /* ISO C99 only promises that the user can pass up to 127 arguments.
2604 * Subtracting the first 4 arguments plus the final NULL and dividing
2605 * by 3 arguments per collected attribute, we are left with a maximum
2606 * number of supported attributes of (127 - 5) / 3 = 40.
2608 * In reality, nobody is ever going to call us with anywhere close to
2609 * 40 attributes to collect, so it is safe to assume that if i > 40
2610 * then the user has given some invalid or repeated arguments. These
2611 * problems will be caught and reported at the end of the function.
2613 * We know at this point that we have an error, but we don't know
2614 * what error it is, so just continue...
2617 collected |= (G_GUINT64_CONSTANT(1) << i);
2619 value = attribute_values[i];
2621 if (value == NULL && mandatory)
2623 g_set_error (error, G_MARKUP_ERROR,
2624 G_MARKUP_ERROR_MISSING_ATTRIBUTE,
2625 "element '%s' requires attribute '%s'",
2626 element_name, attr);
2634 case G_MARKUP_COLLECT_STRING:
2636 const char **str_ptr;
2638 str_ptr = va_arg (ap, const char **);
2640 if (str_ptr != NULL)
2645 case G_MARKUP_COLLECT_STRDUP:
2649 str_ptr = va_arg (ap, char **);
2651 if (str_ptr != NULL)
2652 *str_ptr = g_strdup (value);
2656 case G_MARKUP_COLLECT_BOOLEAN:
2657 case G_MARKUP_COLLECT_TRISTATE:
2662 bool_ptr = va_arg (ap, gboolean *);
2664 if (bool_ptr != NULL)
2666 if (type == G_MARKUP_COLLECT_TRISTATE)
2667 /* constructivists rejoice!
2668 * neither false nor true...
2672 else /* G_MARKUP_COLLECT_BOOLEAN */
2678 if (!g_markup_parse_boolean (value, va_arg (ap, gboolean *)))
2680 g_set_error (error, G_MARKUP_ERROR,
2681 G_MARKUP_ERROR_INVALID_CONTENT,
2682 "element '%s', attribute '%s', value '%s' "
2683 "cannot be parsed as a boolean value",
2684 element_name, attr, value);
2694 g_assert_not_reached ();
2697 type = va_arg (ap, GMarkupCollectType);
2698 attr = va_arg (ap, const char *);
2703 /* ensure we collected all the arguments */
2704 for (i = 0; attribute_names[i]; i++)
2705 if ((collected & (G_GUINT64_CONSTANT(1) << i)) == 0)
2707 /* attribute not collected: could be caused by two things.
2709 * 1) it doesn't exist in our list of attributes
2710 * 2) it existed but was matched by a duplicate attribute earlier
2716 for (j = 0; j < i; j++)
2717 if (strcmp (attribute_names[i], attribute_names[j]) == 0)
2721 /* j is now the first occurrence of attribute_names[i] */
2723 g_set_error (error, G_MARKUP_ERROR,
2724 G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
2725 "attribute '%s' invalid for element '%s'",
2726 attribute_names[i], element_name);
2728 g_set_error (error, G_MARKUP_ERROR,
2729 G_MARKUP_ERROR_INVALID_CONTENT,
2730 "attribute '%s' given multiple times for element '%s'",
2731 attribute_names[i], element_name);
2739 /* replay the above to free allocations */
2743 va_start (ap, first_attr);
2744 while (type != G_MARKUP_COLLECT_INVALID)
2748 ptr = va_arg (ap, gpointer);
2753 switch (type & (G_MARKUP_COLLECT_OPTIONAL - 1))
2755 case G_MARKUP_COLLECT_STRDUP:
2757 g_free (*(char **) ptr);
2759 case G_MARKUP_COLLECT_STRING:
2760 *(char **) ptr = NULL;
2763 case G_MARKUP_COLLECT_BOOLEAN:
2764 *(gboolean *) ptr = FALSE;
2767 case G_MARKUP_COLLECT_TRISTATE:
2768 *(gboolean *) ptr = -1;
2772 type = va_arg (ap, GMarkupCollectType);
2773 attr = va_arg (ap, const char *);
2783 #define __G_MARKUP_C__
2784 #include "galiasdef.c"