1 /* gmarkup.c - Simple XML-like parser
3 * Copyright 2000, 2003 Red Hat, Inc.
4 * Copyright 2007, 2008 Ryan Lortie <desrt@desrt.ca>
6 * GLib is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation; either version 2 of the
9 * License, or (at your option) any later version.
11 * GLib is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with GLib; see the file COPYING.LIB. If not,
18 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 * Boston, MA 02111-1307, USA.
33 #include "gstrfuncs.h"
35 #include "gtestutils.h"
39 g_markup_error_quark (void)
41 return g_quark_from_static_string ("g-markup-error-quark");
47 STATE_AFTER_OPEN_ANGLE,
48 STATE_AFTER_CLOSE_ANGLE,
49 STATE_AFTER_ELISION_SLASH, /* the slash that obviates need for end element */
50 STATE_INSIDE_OPEN_TAG_NAME,
51 STATE_INSIDE_ATTRIBUTE_NAME,
52 STATE_AFTER_ATTRIBUTE_NAME,
53 STATE_BETWEEN_ATTRIBUTES,
54 STATE_AFTER_ATTRIBUTE_EQUALS_SIGN,
55 STATE_INSIDE_ATTRIBUTE_VALUE_SQ,
56 STATE_INSIDE_ATTRIBUTE_VALUE_DQ,
58 STATE_AFTER_CLOSE_TAG_SLASH,
59 STATE_INSIDE_CLOSE_TAG_NAME,
60 STATE_AFTER_CLOSE_TAG_NAME,
61 STATE_INSIDE_PASSTHROUGH,
67 const char *prev_element;
68 const GMarkupParser *prev_parser;
69 gpointer prev_user_data;
70 } GMarkupRecursionTracker;
72 struct _GMarkupParseContext
74 const GMarkupParser *parser;
76 GMarkupParseFlags flags;
82 GDestroyNotify dnotify;
84 /* A piece of character data or an element that
85 * hasn't "ended" yet so we haven't yet called
86 * the callback for it.
88 GString *partial_chunk;
91 GMarkupParseState state;
93 GSList *tag_stack_gstr;
94 GSList *spare_list_nodes;
97 GString **attr_values;
101 const gchar *current_text;
102 gssize current_text_len;
103 const gchar *current_text_end;
105 /* used to save the start of the last interesting thingy */
110 guint document_empty : 1;
112 guint awaiting_pop : 1;
115 /* subparser support */
116 GSList *subparser_stack; /* (GMarkupRecursionTracker *) */
117 const char *subparser_element;
118 gpointer held_user_data;
122 * Helpers to reduce our allocation overhead, we have
123 * a well defined allocation lifecycle.
126 get_list_node (GMarkupParseContext *context, gpointer data)
129 if (context->spare_list_nodes != NULL)
131 node = context->spare_list_nodes;
132 context->spare_list_nodes = g_slist_remove_link (context->spare_list_nodes, node);
135 node = g_slist_alloc();
141 free_list_node (GMarkupParseContext *context, GSList *node)
144 context->spare_list_nodes = g_slist_concat (node, context->spare_list_nodes);
148 string_blank (GString *string)
150 string->str[0] = '\0';
155 * g_markup_parse_context_new:
156 * @parser: a #GMarkupParser
157 * @flags: one or more #GMarkupParseFlags
158 * @user_data: user data to pass to #GMarkupParser functions
159 * @user_data_dnotify: user data destroy notifier called when the parse context is freed
161 * Creates a new parse context. A parse context is used to parse
162 * marked-up documents. You can feed any number of documents into
163 * a context, as long as no errors occur; once an error occurs,
164 * the parse context can't continue to parse text (you have to free it
165 * and create a new parse context).
167 * Return value: a new #GMarkupParseContext
169 GMarkupParseContext *
170 g_markup_parse_context_new (const GMarkupParser *parser,
171 GMarkupParseFlags flags,
173 GDestroyNotify user_data_dnotify)
175 GMarkupParseContext *context;
177 g_return_val_if_fail (parser != NULL, NULL);
179 context = g_new (GMarkupParseContext, 1);
181 context->parser = parser;
182 context->flags = flags;
183 context->user_data = user_data;
184 context->dnotify = user_data_dnotify;
186 context->line_number = 1;
187 context->char_number = 1;
189 context->partial_chunk = NULL;
190 context->spare_chunks = NULL;
191 context->spare_list_nodes = NULL;
193 context->state = STATE_START;
194 context->tag_stack = NULL;
195 context->tag_stack_gstr = NULL;
196 context->attr_names = NULL;
197 context->attr_values = NULL;
198 context->cur_attr = -1;
199 context->alloc_attrs = 0;
201 context->current_text = NULL;
202 context->current_text_len = -1;
203 context->current_text_end = NULL;
205 context->start = NULL;
206 context->iter = NULL;
208 context->document_empty = TRUE;
209 context->parsing = FALSE;
211 context->awaiting_pop = FALSE;
212 context->subparser_stack = NULL;
213 context->subparser_element = NULL;
215 /* this is only looked at if awaiting_pop = TRUE. initialise anyway. */
216 context->held_user_data = NULL;
218 context->balance = 0;
224 string_full_free (gpointer ptr, gpointer user_data)
226 g_string_free (ptr, TRUE);
229 static void clear_attributes (GMarkupParseContext *context);
232 * g_markup_parse_context_free:
233 * @context: a #GMarkupParseContext
235 * Frees a #GMarkupParseContext. Can't be called from inside
236 * one of the #GMarkupParser functions. Can't be called while
237 * a subparser is pushed.
240 g_markup_parse_context_free (GMarkupParseContext *context)
242 g_return_if_fail (context != NULL);
243 g_return_if_fail (!context->parsing);
244 g_return_if_fail (!context->subparser_stack);
245 g_return_if_fail (!context->awaiting_pop);
247 if (context->dnotify)
248 (* context->dnotify) (context->user_data);
250 clear_attributes (context);
251 g_free (context->attr_names);
252 g_free (context->attr_values);
254 g_slist_foreach (context->tag_stack_gstr, string_full_free, NULL);
255 g_slist_free (context->tag_stack_gstr);
256 g_slist_free (context->tag_stack);
258 g_slist_foreach (context->spare_chunks, string_full_free, NULL);
259 g_slist_free (context->spare_chunks);
260 g_slist_free (context->spare_list_nodes);
262 if (context->partial_chunk)
263 g_string_free (context->partial_chunk, TRUE);
268 static void pop_subparser_stack (GMarkupParseContext *context);
271 mark_error (GMarkupParseContext *context,
274 context->state = STATE_ERROR;
276 if (context->parser->error)
277 (*context->parser->error) (context, error, context->user_data);
279 /* report the error all the way up to free all the user-data */
280 while (context->subparser_stack)
282 pop_subparser_stack (context);
283 context->awaiting_pop = FALSE; /* already been freed */
285 if (context->parser->error)
286 (*context->parser->error) (context, error, context->user_data);
290 static void set_error (GMarkupParseContext *context,
294 ...) G_GNUC_PRINTF (4, 5);
297 set_error_literal (GMarkupParseContext *context,
300 const gchar *message)
304 tmp_error = g_error_new_literal (G_MARKUP_ERROR, code, message);
306 g_prefix_error (&tmp_error,
307 _("Error on line %d char %d: "),
308 context->line_number,
309 context->char_number);
311 mark_error (context, tmp_error);
313 g_propagate_error (error, tmp_error);
317 set_error (GMarkupParseContext *context,
327 va_start (args, format);
328 s = g_strdup_vprintf (format, args);
331 /* Make sure that the GError message is valid UTF-8 even if it is
332 * complaining about invalid UTF-8 in the markup: */
333 s_valid = _g_utf8_make_valid (s);
334 set_error_literal (context, error, code, s);
341 propagate_error (GMarkupParseContext *context,
345 if (context->flags & G_MARKUP_PREFIX_ERROR_POSITION)
346 g_prefix_error (&src,
347 _("Error on line %d char %d: "),
348 context->line_number,
349 context->char_number);
351 mark_error (context, src);
353 g_propagate_error (dest, src);
356 #define IS_COMMON_NAME_END_CHAR(c) \
357 ((c) == '=' || (c) == '/' || (c) == '>' || (c) == ' ')
360 slow_name_validate (GMarkupParseContext *context, const char *name, GError **error)
362 const char *p = name;
364 if (!g_utf8_validate (name, strlen (name), NULL))
366 set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
367 _("Invalid UTF-8 encoded text in name - not valid '%s'"), name);
371 if (!(g_ascii_isalpha (*p) ||
372 (!IS_COMMON_NAME_END_CHAR (*p) &&
375 g_unichar_isalpha (g_utf8_get_char (p))))))
377 set_error (context, error, G_MARKUP_ERROR_PARSE,
378 _("'%s' is not a valid name "), name);
382 for (p = g_utf8_next_char (name); *p != '\0'; p = g_utf8_next_char (p))
385 if (!(g_ascii_isalnum (*p) ||
386 (!IS_COMMON_NAME_END_CHAR (*p) &&
391 g_unichar_isalpha (g_utf8_get_char (p))))))
393 set_error (context, error, G_MARKUP_ERROR_PARSE,
394 _("'%s' is not a valid name: '%c' "), name, *p);
402 * Use me for elements, attributes etc.
405 name_validate (GMarkupParseContext *context, const char *name, GError **error)
410 /* name start char */
412 if (G_UNLIKELY (IS_COMMON_NAME_END_CHAR (*p) ||
413 !(g_ascii_isalpha (*p) || *p == '_' || *p == ':')))
416 for (mask = *p++; *p != '\0'; p++)
421 if (G_UNLIKELY (!(g_ascii_isalnum (*p) ||
422 (!IS_COMMON_NAME_END_CHAR (*p) &&
430 if (mask & 0x80) /* un-common / non-ascii */
436 return slow_name_validate (context, name, error);
440 text_validate (GMarkupParseContext *context, const char *p, int len, GError **error)
442 if (!g_utf8_validate (p, len, NULL))
444 set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
445 _("Invalid UTF-8 encoded text in name - not valid '%s'"), p);
453 char_str (gunichar c,
457 g_unichar_to_utf8 (c, buf);
462 utf8_str (const gchar *utf8,
465 char_str (g_utf8_get_char (utf8), buf);
470 set_unescape_error (GMarkupParseContext *context,
472 const gchar *remaining_text,
480 gint remaining_newlines;
483 remaining_newlines = 0;
488 ++remaining_newlines;
492 va_start (args, format);
493 s = g_strdup_vprintf (format, args);
496 tmp_error = g_error_new (G_MARKUP_ERROR,
498 _("Error on line %d: %s"),
499 context->line_number - remaining_newlines,
504 mark_error (context, tmp_error);
506 g_propagate_error (error, tmp_error);
510 * re-write the GString in-place, unescaping anything that escaped.
511 * most XML does not contain entities, or escaping.
514 unescape_gstring_inplace (GMarkupParseContext *context,
522 gboolean normalize_attribute;
526 /* are we unescaping an attribute or not ? */
527 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
528 context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
529 normalize_attribute = TRUE;
531 normalize_attribute = FALSE;
534 * Meeks' theorum: unescaping can only shrink text.
535 * for < etc. this is obvious, for  more
536 * thought is required, but this is patently so.
539 for (from = to = string->str; *from != '\0'; from++, to++)
546 if (normalize_attribute && (*to == '\t' || *to == '\n'))
550 *to = normalize_attribute ? ' ' : '\n';
559 gboolean is_hex = FALSE;
571 /* digit is between start and p */
574 l = strtoul (from, &end, 16);
576 l = strtoul (from, &end, 10);
578 if (end == from || errno != 0)
580 set_unescape_error (context, error,
581 from, G_MARKUP_ERROR_PARSE,
582 _("Failed to parse '%-.*s', which "
583 "should have been a digit "
584 "inside a character reference "
585 "(ê for example) - perhaps "
586 "the digit is too large"),
590 else if (*end != ';')
592 set_unescape_error (context, error,
593 from, G_MARKUP_ERROR_PARSE,
594 _("Character reference did not end with a "
596 "most likely you used an ampersand "
597 "character without intending to start "
598 "an entity - escape ampersand as &"));
603 /* characters XML 1.1 permits */
604 if ((0 < l && l <= 0xD7FF) ||
605 (0xE000 <= l && l <= 0xFFFD) ||
606 (0x10000 <= l && l <= 0x10FFFF))
611 to += strlen (buf) - 1;
613 if (l >= 0x80) /* not ascii */
618 set_unescape_error (context, error,
619 from, G_MARKUP_ERROR_PARSE,
620 _("Character reference '%-.*s' does not "
621 "encode a permitted character"),
628 else if (strncmp (from, "lt;", 3) == 0)
633 else if (strncmp (from, "gt;", 3) == 0)
638 else if (strncmp (from, "amp;", 4) == 0)
643 else if (strncmp (from, "quot;", 5) == 0)
648 else if (strncmp (from, "apos;", 5) == 0)
656 set_unescape_error (context, error,
657 from, G_MARKUP_ERROR_PARSE,
658 _("Empty entity '&;' seen; valid "
659 "entities are: & " < > '"));
662 const char *end = strchr (from, ';');
664 set_unescape_error (context, error,
665 from, G_MARKUP_ERROR_PARSE,
666 _("Entity name '%-.*s' is not known"),
669 set_unescape_error (context, error,
670 from, G_MARKUP_ERROR_PARSE,
671 _("Entity did not end with a semicolon; "
672 "most likely you used an ampersand "
673 "character without intending to start "
674 "an entity - escape ampersand as &"));
681 g_assert (to - string->str <= string->len);
682 if (to - string->str != string->len)
683 g_string_truncate (string, to - string->str);
685 *is_ascii = !(mask & 0x80);
690 static inline gboolean
691 advance_char (GMarkupParseContext *context)
694 context->char_number++;
696 if (G_UNLIKELY (context->iter == context->current_text_end))
699 else if (G_UNLIKELY (*context->iter == '\n'))
701 context->line_number++;
702 context->char_number = 1;
708 static inline gboolean
711 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
715 skip_spaces (GMarkupParseContext *context)
719 if (!xml_isspace (*context->iter))
722 while (advance_char (context));
726 advance_to_name_end (GMarkupParseContext *context)
730 if (IS_COMMON_NAME_END_CHAR (*(context->iter)))
732 if (xml_isspace (*(context->iter)))
735 while (advance_char (context));
739 release_chunk (GMarkupParseContext *context, GString *str)
744 if (str->allocated_len > 256)
745 { /* large strings are unusual and worth freeing */
746 g_string_free (str, TRUE);
750 node = get_list_node (context, str);
751 context->spare_chunks = g_slist_concat (node, context->spare_chunks);
755 add_to_partial (GMarkupParseContext *context,
756 const gchar *text_start,
757 const gchar *text_end)
759 if (context->partial_chunk == NULL)
760 { /* allocate a new chunk to parse into */
762 if (context->spare_chunks != NULL)
764 GSList *node = context->spare_chunks;
765 context->spare_chunks = g_slist_remove_link (context->spare_chunks, node);
766 context->partial_chunk = node->data;
767 free_list_node (context, node);
770 context->partial_chunk = g_string_sized_new (MAX (28, text_end - text_start));
773 if (text_start != text_end)
774 g_string_insert_len (context->partial_chunk, -1,
775 text_start, text_end - text_start);
779 truncate_partial (GMarkupParseContext *context)
781 if (context->partial_chunk != NULL)
782 string_blank (context->partial_chunk);
785 static inline const gchar*
786 current_element (GMarkupParseContext *context)
788 return context->tag_stack->data;
792 pop_subparser_stack (GMarkupParseContext *context)
794 GMarkupRecursionTracker *tracker;
796 g_assert (context->subparser_stack);
798 tracker = context->subparser_stack->data;
800 context->awaiting_pop = TRUE;
801 context->held_user_data = context->user_data;
803 context->user_data = tracker->prev_user_data;
804 context->parser = tracker->prev_parser;
805 context->subparser_element = tracker->prev_element;
806 g_slice_free (GMarkupRecursionTracker, tracker);
808 context->subparser_stack = g_slist_delete_link (context->subparser_stack,
809 context->subparser_stack);
813 push_partial_as_tag (GMarkupParseContext *context)
815 GString *str = context->partial_chunk;
816 /* sadly, this is exported by gmarkup_get_element_stack as-is */
817 context->tag_stack = g_slist_concat (get_list_node (context, str->str), context->tag_stack);
818 context->tag_stack_gstr = g_slist_concat (get_list_node (context, str), context->tag_stack_gstr);
819 context->partial_chunk = NULL;
823 pop_tag (GMarkupParseContext *context)
825 GSList *nodea, *nodeb;
827 nodea = context->tag_stack;
828 nodeb = context->tag_stack_gstr;
829 release_chunk (context, nodeb->data);
830 context->tag_stack = g_slist_remove_link (context->tag_stack, nodea);
831 context->tag_stack_gstr = g_slist_remove_link (context->tag_stack_gstr, nodeb);
832 free_list_node (context, nodea);
833 free_list_node (context, nodeb);
837 possibly_finish_subparser (GMarkupParseContext *context)
839 if (current_element (context) == context->subparser_element)
840 pop_subparser_stack (context);
844 ensure_no_outstanding_subparser (GMarkupParseContext *context)
846 if (context->awaiting_pop)
847 g_critical ("During the first end_element call after invoking a "
848 "subparser you must pop the subparser stack and handle "
849 "the freeing of the subparser user_data. This can be "
850 "done by calling the end function of the subparser. "
851 "Very probably, your program just leaked memory.");
853 /* let valgrind watch the pointer disappear... */
854 context->held_user_data = NULL;
855 context->awaiting_pop = FALSE;
859 current_attribute (GMarkupParseContext *context)
861 g_assert (context->cur_attr >= 0);
862 return context->attr_names[context->cur_attr]->str;
866 add_attribute (GMarkupParseContext *context, GString *str)
868 if (context->cur_attr + 2 >= context->alloc_attrs)
870 context->alloc_attrs += 5; /* silly magic number */
871 context->attr_names = g_realloc (context->attr_names, sizeof(GString*)*context->alloc_attrs);
872 context->attr_values = g_realloc (context->attr_values, sizeof(GString*)*context->alloc_attrs);
875 context->attr_names[context->cur_attr] = str;
876 context->attr_values[context->cur_attr] = NULL;
877 context->attr_names[context->cur_attr+1] = NULL;
878 context->attr_values[context->cur_attr+1] = NULL;
882 clear_attributes (GMarkupParseContext *context)
884 /* Go ahead and free the attributes. */
885 for (; context->cur_attr >= 0; context->cur_attr--)
887 int pos = context->cur_attr;
888 release_chunk (context, context->attr_names[pos]);
889 release_chunk (context, context->attr_values[pos]);
890 context->attr_names[pos] = context->attr_values[pos] = NULL;
892 g_assert (context->cur_attr == -1);
893 g_assert (context->attr_names == NULL ||
894 context->attr_names[0] == NULL);
895 g_assert (context->attr_values == NULL ||
896 context->attr_values[0] == NULL);
899 /* This has to be a separate function to ensure the alloca's
900 are unwound on exit - otherwise we grow & blow the stack
901 with large documents */
903 emit_start_element (GMarkupParseContext *context, GError **error)
906 const gchar *start_name;
907 const gchar **attr_names;
908 const gchar **attr_values;
911 attr_names = g_newa (const gchar *, context->cur_attr + 2);
912 attr_values = g_newa (const gchar *, context->cur_attr + 2);
913 for (i = 0; i < context->cur_attr + 1; i++)
915 attr_names[i] = context->attr_names[i]->str;
916 attr_values[i] = context->attr_values[i]->str;
918 attr_names[i] = NULL;
919 attr_values[i] = NULL;
921 /* Call user callback for element start */
923 start_name = current_element (context);
925 if (context->parser->start_element &&
926 name_validate (context, start_name, error))
927 (* context->parser->start_element) (context,
929 (const gchar **)attr_names,
930 (const gchar **)attr_values,
933 clear_attributes (context);
935 if (tmp_error != NULL)
936 propagate_error (context, error, tmp_error);
940 * g_markup_parse_context_parse:
941 * @context: a #GMarkupParseContext
942 * @text: chunk of text to parse
943 * @text_len: length of @text in bytes
944 * @error: return location for a #GError
946 * Feed some data to the #GMarkupParseContext. The data need not
947 * be valid UTF-8; an error will be signaled if it's invalid.
948 * The data need not be an entire document; you can feed a document
949 * into the parser incrementally, via multiple calls to this function.
950 * Typically, as you receive data from a network connection or file,
951 * you feed each received chunk of data into this function, aborting
952 * the process if an error occurs. Once an error is reported, no further
953 * data may be fed to the #GMarkupParseContext; all errors are fatal.
955 * Return value: %FALSE if an error occurred, %TRUE on success
958 g_markup_parse_context_parse (GMarkupParseContext *context,
963 g_return_val_if_fail (context != NULL, FALSE);
964 g_return_val_if_fail (text != NULL, FALSE);
965 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
966 g_return_val_if_fail (!context->parsing, FALSE);
969 text_len = strlen (text);
974 context->parsing = TRUE;
977 context->current_text = text;
978 context->current_text_len = text_len;
979 context->current_text_end = context->current_text + text_len;
980 context->iter = context->current_text;
981 context->start = context->iter;
983 if (context->current_text_len == 0)
986 while (context->iter != context->current_text_end)
988 switch (context->state)
991 /* Possible next state: AFTER_OPEN_ANGLE */
993 g_assert (context->tag_stack == NULL);
995 /* whitespace is ignored outside of any elements */
996 skip_spaces (context);
998 if (context->iter != context->current_text_end)
1000 if (*context->iter == '<')
1002 /* Move after the open angle */
1003 advance_char (context);
1005 context->state = STATE_AFTER_OPEN_ANGLE;
1007 /* this could start a passthrough */
1008 context->start = context->iter;
1010 /* document is now non-empty */
1011 context->document_empty = FALSE;
1015 set_error_literal (context,
1017 G_MARKUP_ERROR_PARSE,
1018 _("Document must begin with an element (e.g. <book>)"));
1023 case STATE_AFTER_OPEN_ANGLE:
1024 /* Possible next states: INSIDE_OPEN_TAG_NAME,
1025 * AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1027 if (*context->iter == '?' ||
1028 *context->iter == '!')
1030 /* include < in the passthrough */
1031 const gchar *openangle = "<";
1032 add_to_partial (context, openangle, openangle + 1);
1033 context->start = context->iter;
1034 context->balance = 1;
1035 context->state = STATE_INSIDE_PASSTHROUGH;
1037 else if (*context->iter == '/')
1040 advance_char (context);
1042 context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1044 else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1046 context->state = STATE_INSIDE_OPEN_TAG_NAME;
1048 /* start of tag name */
1049 context->start = context->iter;
1057 G_MARKUP_ERROR_PARSE,
1058 _("'%s' is not a valid character following "
1059 "a '<' character; it may not begin an "
1061 utf8_str (context->iter, buf));
1065 /* The AFTER_CLOSE_ANGLE state is actually sort of
1066 * broken, because it doesn't correspond to a range
1067 * of characters in the input stream as the others do,
1068 * and thus makes things harder to conceptualize
1070 case STATE_AFTER_CLOSE_ANGLE:
1071 /* Possible next states: INSIDE_TEXT, STATE_START */
1072 if (context->tag_stack == NULL)
1074 context->start = NULL;
1075 context->state = STATE_START;
1079 context->start = context->iter;
1080 context->state = STATE_INSIDE_TEXT;
1084 case STATE_AFTER_ELISION_SLASH:
1085 /* Possible next state: AFTER_CLOSE_ANGLE */
1088 /* We need to pop the tag stack and call the end_element
1089 * function, since this is the close tag
1091 GError *tmp_error = NULL;
1093 g_assert (context->tag_stack != NULL);
1095 possibly_finish_subparser (context);
1098 if (context->parser->end_element)
1099 (* context->parser->end_element) (context,
1100 current_element (context),
1104 ensure_no_outstanding_subparser (context);
1108 mark_error (context, tmp_error);
1109 g_propagate_error (error, tmp_error);
1113 if (*context->iter == '>')
1115 /* move after the close angle */
1116 advance_char (context);
1117 context->state = STATE_AFTER_CLOSE_ANGLE;
1125 G_MARKUP_ERROR_PARSE,
1126 _("Odd character '%s', expected a '>' character "
1127 "to end the empty-element tag '%s'"),
1128 utf8_str (context->iter, buf),
1129 current_element (context));
1136 case STATE_INSIDE_OPEN_TAG_NAME:
1137 /* Possible next states: BETWEEN_ATTRIBUTES */
1139 /* if there's a partial chunk then it's the first part of the
1140 * tag name. If there's a context->start then it's the start
1141 * of the tag name in current_text, the partial chunk goes
1142 * before that start though.
1144 advance_to_name_end (context);
1146 if (context->iter == context->current_text_end)
1148 /* The name hasn't necessarily ended. Merge with
1149 * partial chunk, leave state unchanged.
1151 add_to_partial (context, context->start, context->iter);
1155 /* The name has ended. Combine it with the partial chunk
1156 * if any; push it on the stack; enter next state.
1158 add_to_partial (context, context->start, context->iter);
1159 push_partial_as_tag (context);
1161 context->state = STATE_BETWEEN_ATTRIBUTES;
1162 context->start = NULL;
1166 case STATE_INSIDE_ATTRIBUTE_NAME:
1167 /* Possible next states: AFTER_ATTRIBUTE_NAME */
1169 advance_to_name_end (context);
1170 add_to_partial (context, context->start, context->iter);
1172 /* read the full name, if we enter the equals sign state
1173 * then add the attribute to the list (without the value),
1174 * otherwise store a partial chunk to be prepended later.
1176 if (context->iter != context->current_text_end)
1177 context->state = STATE_AFTER_ATTRIBUTE_NAME;
1180 case STATE_AFTER_ATTRIBUTE_NAME:
1181 /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1183 skip_spaces (context);
1185 if (context->iter != context->current_text_end)
1187 /* The name has ended. Combine it with the partial chunk
1188 * if any; push it on the stack; enter next state.
1190 if (!name_validate (context, context->partial_chunk->str, error))
1193 add_attribute (context, context->partial_chunk);
1195 context->partial_chunk = NULL;
1196 context->start = NULL;
1198 if (*context->iter == '=')
1200 advance_char (context);
1201 context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1209 G_MARKUP_ERROR_PARSE,
1210 _("Odd character '%s', expected a '=' after "
1211 "attribute name '%s' of element '%s'"),
1212 utf8_str (context->iter, buf),
1213 current_attribute (context),
1214 current_element (context));
1220 case STATE_BETWEEN_ATTRIBUTES:
1221 /* Possible next states: AFTER_CLOSE_ANGLE,
1222 * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1224 skip_spaces (context);
1226 if (context->iter != context->current_text_end)
1228 if (*context->iter == '/')
1230 advance_char (context);
1231 context->state = STATE_AFTER_ELISION_SLASH;
1233 else if (*context->iter == '>')
1235 advance_char (context);
1236 context->state = STATE_AFTER_CLOSE_ANGLE;
1238 else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1240 context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1241 /* start of attribute name */
1242 context->start = context->iter;
1250 G_MARKUP_ERROR_PARSE,
1251 _("Odd character '%s', expected a '>' or '/' "
1252 "character to end the start tag of "
1253 "element '%s', or optionally an attribute; "
1254 "perhaps you used an invalid character in "
1255 "an attribute name"),
1256 utf8_str (context->iter, buf),
1257 current_element (context));
1260 /* If we're done with attributes, invoke
1261 * the start_element callback
1263 if (context->state == STATE_AFTER_ELISION_SLASH ||
1264 context->state == STATE_AFTER_CLOSE_ANGLE)
1265 emit_start_element (context, error);
1269 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1270 /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1272 skip_spaces (context);
1274 if (context->iter != context->current_text_end)
1276 if (*context->iter == '"')
1278 advance_char (context);
1279 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1280 context->start = context->iter;
1282 else if (*context->iter == '\'')
1284 advance_char (context);
1285 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1286 context->start = context->iter;
1294 G_MARKUP_ERROR_PARSE,
1295 _("Odd character '%s', expected an open quote mark "
1296 "after the equals sign when giving value for "
1297 "attribute '%s' of element '%s'"),
1298 utf8_str (context->iter, buf),
1299 current_attribute (context),
1300 current_element (context));
1305 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1306 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1307 /* Possible next states: BETWEEN_ATTRIBUTES */
1311 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ)
1322 if (*context->iter == delim)
1325 while (advance_char (context));
1327 if (context->iter == context->current_text_end)
1329 /* The value hasn't necessarily ended. Merge with
1330 * partial chunk, leave state unchanged.
1332 add_to_partial (context, context->start, context->iter);
1337 /* The value has ended at the quote mark. Combine it
1338 * with the partial chunk if any; set it for the current
1341 add_to_partial (context, context->start, context->iter);
1343 g_assert (context->cur_attr >= 0);
1345 if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1346 (is_ascii || text_validate (context, context->partial_chunk->str,
1347 context->partial_chunk->len, error)))
1349 /* success, advance past quote and set state. */
1350 context->attr_values[context->cur_attr] = context->partial_chunk;
1351 context->partial_chunk = NULL;
1352 advance_char (context);
1353 context->state = STATE_BETWEEN_ATTRIBUTES;
1354 context->start = NULL;
1357 truncate_partial (context);
1361 case STATE_INSIDE_TEXT:
1362 /* Possible next states: AFTER_OPEN_ANGLE */
1365 if (*context->iter == '<')
1368 while (advance_char (context));
1370 /* The text hasn't necessarily ended. Merge with
1371 * partial chunk, leave state unchanged.
1374 add_to_partial (context, context->start, context->iter);
1376 if (context->iter != context->current_text_end)
1380 /* The text has ended at the open angle. Call the text
1384 if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1385 (is_ascii || text_validate (context, context->partial_chunk->str,
1386 context->partial_chunk->len, error)))
1388 GError *tmp_error = NULL;
1390 if (context->parser->text)
1391 (*context->parser->text) (context,
1392 context->partial_chunk->str,
1393 context->partial_chunk->len,
1397 if (tmp_error == NULL)
1399 /* advance past open angle and set state. */
1400 advance_char (context);
1401 context->state = STATE_AFTER_OPEN_ANGLE;
1402 /* could begin a passthrough */
1403 context->start = context->iter;
1406 propagate_error (context, error, tmp_error);
1409 truncate_partial (context);
1413 case STATE_AFTER_CLOSE_TAG_SLASH:
1414 /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1415 if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1417 context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1419 /* start of tag name */
1420 context->start = context->iter;
1428 G_MARKUP_ERROR_PARSE,
1429 _("'%s' is not a valid character following "
1430 "the characters '</'; '%s' may not begin an "
1432 utf8_str (context->iter, buf),
1433 utf8_str (context->iter, buf));
1437 case STATE_INSIDE_CLOSE_TAG_NAME:
1438 /* Possible next state: AFTER_CLOSE_TAG_NAME */
1439 advance_to_name_end (context);
1440 add_to_partial (context, context->start, context->iter);
1442 if (context->iter != context->current_text_end)
1443 context->state = STATE_AFTER_CLOSE_TAG_NAME;
1446 case STATE_AFTER_CLOSE_TAG_NAME:
1447 /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1449 skip_spaces (context);
1451 if (context->iter != context->current_text_end)
1453 GString *close_name;
1455 close_name = context->partial_chunk;
1456 context->partial_chunk = NULL;
1458 if (*context->iter != '>')
1464 G_MARKUP_ERROR_PARSE,
1465 _("'%s' is not a valid character following "
1466 "the close element name '%s'; the allowed "
1467 "character is '>'"),
1468 utf8_str (context->iter, buf),
1471 else if (context->tag_stack == NULL)
1475 G_MARKUP_ERROR_PARSE,
1476 _("Element '%s' was closed, no element "
1477 "is currently open"),
1480 else if (strcmp (close_name->str, current_element (context)) != 0)
1484 G_MARKUP_ERROR_PARSE,
1485 _("Element '%s' was closed, but the currently "
1486 "open element is '%s'"),
1488 current_element (context));
1493 advance_char (context);
1494 context->state = STATE_AFTER_CLOSE_ANGLE;
1495 context->start = NULL;
1497 possibly_finish_subparser (context);
1499 /* call the end_element callback */
1501 if (context->parser->end_element)
1502 (* context->parser->end_element) (context,
1507 ensure_no_outstanding_subparser (context);
1511 propagate_error (context, error, tmp_error);
1513 context->partial_chunk = close_name;
1514 truncate_partial (context);
1518 case STATE_INSIDE_PASSTHROUGH:
1519 /* Possible next state: AFTER_CLOSE_ANGLE */
1522 if (*context->iter == '<')
1524 if (*context->iter == '>')
1530 add_to_partial (context, context->start, context->iter);
1531 context->start = context->iter;
1533 str = context->partial_chunk->str;
1534 len = context->partial_chunk->len;
1536 if (str[1] == '?' && str[len - 1] == '?')
1538 if (strncmp (str, "<!--", 4) == 0 &&
1539 strcmp (str + len - 2, "--") == 0)
1541 if (strncmp (str, "<![CDATA[", 9) == 0 &&
1542 strcmp (str + len - 2, "]]") == 0)
1544 if (strncmp (str, "<!DOCTYPE", 9) == 0 &&
1545 context->balance == 0)
1549 while (advance_char (context));
1551 if (context->iter == context->current_text_end)
1553 /* The passthrough hasn't necessarily ended. Merge with
1554 * partial chunk, leave state unchanged.
1556 add_to_partial (context, context->start, context->iter);
1560 /* The passthrough has ended at the close angle. Combine
1561 * it with the partial chunk if any. Call the passthrough
1562 * callback. Note that the open/close angles are
1563 * included in the text of the passthrough.
1565 GError *tmp_error = NULL;
1567 advance_char (context); /* advance past close angle */
1568 add_to_partial (context, context->start, context->iter);
1570 if (context->flags & G_MARKUP_TREAT_CDATA_AS_TEXT &&
1571 strncmp (context->partial_chunk->str, "<![CDATA[", 9) == 0)
1573 if (context->parser->text &&
1574 text_validate (context,
1575 context->partial_chunk->str + 9,
1576 context->partial_chunk->len - 12,
1578 (*context->parser->text) (context,
1579 context->partial_chunk->str + 9,
1580 context->partial_chunk->len - 12,
1584 else if (context->parser->passthrough &&
1585 text_validate (context,
1586 context->partial_chunk->str,
1587 context->partial_chunk->len,
1589 (*context->parser->passthrough) (context,
1590 context->partial_chunk->str,
1591 context->partial_chunk->len,
1595 truncate_partial (context);
1597 if (tmp_error == NULL)
1599 context->state = STATE_AFTER_CLOSE_ANGLE;
1600 context->start = context->iter; /* could begin text */
1603 propagate_error (context, error, tmp_error);
1612 g_assert_not_reached ();
1618 context->parsing = FALSE;
1620 return context->state != STATE_ERROR;
1624 * g_markup_parse_context_end_parse:
1625 * @context: a #GMarkupParseContext
1626 * @error: return location for a #GError
1628 * Signals to the #GMarkupParseContext that all data has been
1629 * fed into the parse context with g_markup_parse_context_parse().
1630 * This function reports an error if the document isn't complete,
1631 * for example if elements are still open.
1633 * Return value: %TRUE on success, %FALSE if an error was set
1636 g_markup_parse_context_end_parse (GMarkupParseContext *context,
1639 g_return_val_if_fail (context != NULL, FALSE);
1640 g_return_val_if_fail (!context->parsing, FALSE);
1641 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1643 if (context->partial_chunk != NULL)
1645 g_string_free (context->partial_chunk, TRUE);
1646 context->partial_chunk = NULL;
1649 if (context->document_empty)
1651 set_error_literal (context, error, G_MARKUP_ERROR_EMPTY,
1652 _("Document was empty or contained only whitespace"));
1656 context->parsing = TRUE;
1658 switch (context->state)
1664 case STATE_AFTER_OPEN_ANGLE:
1665 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1666 _("Document ended unexpectedly just after an open angle bracket '<'"));
1669 case STATE_AFTER_CLOSE_ANGLE:
1670 if (context->tag_stack != NULL)
1672 /* Error message the same as for INSIDE_TEXT */
1673 set_error (context, error, G_MARKUP_ERROR_PARSE,
1674 _("Document ended unexpectedly with elements still open - "
1675 "'%s' was the last element opened"),
1676 current_element (context));
1680 case STATE_AFTER_ELISION_SLASH:
1681 set_error (context, error, G_MARKUP_ERROR_PARSE,
1682 _("Document ended unexpectedly, expected to see a close angle "
1683 "bracket ending the tag <%s/>"), current_element (context));
1686 case STATE_INSIDE_OPEN_TAG_NAME:
1687 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1688 _("Document ended unexpectedly inside an element name"));
1691 case STATE_INSIDE_ATTRIBUTE_NAME:
1692 case STATE_AFTER_ATTRIBUTE_NAME:
1693 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1694 _("Document ended unexpectedly inside an attribute name"));
1697 case STATE_BETWEEN_ATTRIBUTES:
1698 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1699 _("Document ended unexpectedly inside an element-opening "
1703 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1704 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1705 _("Document ended unexpectedly after the equals sign "
1706 "following an attribute name; no attribute value"));
1709 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1710 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1711 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1712 _("Document ended unexpectedly while inside an attribute "
1716 case STATE_INSIDE_TEXT:
1717 g_assert (context->tag_stack != NULL);
1718 set_error (context, error, G_MARKUP_ERROR_PARSE,
1719 _("Document ended unexpectedly with elements still open - "
1720 "'%s' was the last element opened"),
1721 current_element (context));
1724 case STATE_AFTER_CLOSE_TAG_SLASH:
1725 case STATE_INSIDE_CLOSE_TAG_NAME:
1726 case STATE_AFTER_CLOSE_TAG_NAME:
1727 set_error (context, error, G_MARKUP_ERROR_PARSE,
1728 _("Document ended unexpectedly inside the close tag for "
1729 "element '%s'"), current_element (context));
1732 case STATE_INSIDE_PASSTHROUGH:
1733 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1734 _("Document ended unexpectedly inside a comment or "
1735 "processing instruction"));
1740 g_assert_not_reached ();
1744 context->parsing = FALSE;
1746 return context->state != STATE_ERROR;
1750 * g_markup_parse_context_get_element:
1751 * @context: a #GMarkupParseContext
1752 * @returns: the name of the currently open element, or %NULL
1754 * Retrieves the name of the currently open element.
1756 * If called from the start_element or end_element handlers this will
1757 * give the element_name as passed to those functions. For the parent
1758 * elements, see g_markup_parse_context_get_element_stack().
1762 G_CONST_RETURN gchar *
1763 g_markup_parse_context_get_element (GMarkupParseContext *context)
1765 g_return_val_if_fail (context != NULL, NULL);
1767 if (context->tag_stack == NULL)
1770 return current_element (context);
1774 * g_markup_parse_context_get_element_stack:
1775 * @context: a #GMarkupParseContext
1777 * Retrieves the element stack from the internal state of the parser.
1778 * The returned #GSList is a list of strings where the first item is
1779 * the currently open tag (as would be returned by
1780 * g_markup_parse_context_get_element()) and the next item is its
1783 * This function is intended to be used in the start_element and
1784 * end_element handlers where g_markup_parse_context_get_element()
1785 * would merely return the name of the element that is being
1788 * Returns: the element stack, which must not be modified
1792 G_CONST_RETURN GSList *
1793 g_markup_parse_context_get_element_stack (GMarkupParseContext *context)
1795 g_return_val_if_fail (context != NULL, NULL);
1796 return context->tag_stack;
1800 * g_markup_parse_context_get_position:
1801 * @context: a #GMarkupParseContext
1802 * @line_number: return location for a line number, or %NULL
1803 * @char_number: return location for a char-on-line number, or %NULL
1805 * Retrieves the current line number and the number of the character on
1806 * that line. Intended for use in error messages; there are no strict
1807 * semantics for what constitutes the "current" line number other than
1808 * "the best number we could come up with for error messages."
1812 g_markup_parse_context_get_position (GMarkupParseContext *context,
1816 g_return_if_fail (context != NULL);
1819 *line_number = context->line_number;
1822 *char_number = context->char_number;
1826 * g_markup_parse_context_get_user_data:
1827 * @context: a #GMarkupParseContext
1829 * Returns the user_data associated with @context. This will either
1830 * be the user_data that was provided to g_markup_parse_context_new()
1831 * or to the most recent call of g_markup_parse_context_push().
1833 * Returns: the provided user_data. The returned data belongs to
1834 * the markup context and will be freed when g_markup_context_free()
1840 g_markup_parse_context_get_user_data (GMarkupParseContext *context)
1842 return context->user_data;
1846 * g_markup_parse_context_push:
1847 * @context: a #GMarkupParseContext
1848 * @parser: a #GMarkupParser
1849 * @user_data: user data to pass to #GMarkupParser functions
1851 * Temporarily redirects markup data to a sub-parser.
1853 * This function may only be called from the start_element handler of
1854 * a #GMarkupParser. It must be matched with a corresponding call to
1855 * g_markup_parse_context_pop() in the matching end_element handler
1856 * (except in the case that the parser aborts due to an error).
1858 * All tags, text and other data between the matching tags is
1859 * redirected to the subparser given by @parser. @user_data is used
1860 * as the user_data for that parser. @user_data is also passed to the
1861 * error callback in the event that an error occurs. This includes
1862 * errors that occur in subparsers of the subparser.
1864 * The end tag matching the start tag for which this call was made is
1865 * handled by the previous parser (which is given its own user_data)
1866 * which is why g_markup_parse_context_pop() is provided to allow "one
1867 * last access" to the @user_data provided to this function. In the
1868 * case of error, the @user_data provided here is passed directly to
1869 * the error callback of the subparser and g_markup_parse_context()
1870 * should not be called. In either case, if @user_data was allocated
1871 * then it ought to be freed from both of these locations.
1873 * This function is not intended to be directly called by users
1874 * interested in invoking subparsers. Instead, it is intended to be
1875 * used by the subparsers themselves to implement a higher-level
1878 * As an example, see the following implementation of a simple
1879 * parser that counts the number of tags encountered.
1888 * counter_start_element (GMarkupParseContext *context,
1889 * const gchar *element_name,
1890 * const gchar **attribute_names,
1891 * const gchar **attribute_values,
1892 * gpointer user_data,
1895 * CounterData *data = user_data;
1897 * data->tag_count++;
1901 * counter_error (GMarkupParseContext *context,
1903 * gpointer user_data)
1905 * CounterData *data = user_data;
1907 * g_slice_free (CounterData, data);
1910 * static GMarkupParser counter_subparser =
1912 * counter_start_element,
1920 * In order to allow this parser to be easily used as a subparser, the
1921 * following interface is provided:
1925 * start_counting (GMarkupParseContext *context)
1927 * CounterData *data = g_slice_new (CounterData);
1929 * data->tag_count = 0;
1930 * g_markup_parse_context_push (context, &counter_subparser, data);
1934 * end_counting (GMarkupParseContext *context)
1936 * CounterData *data = g_markup_parse_context_pop (context);
1939 * result = data->tag_count;
1940 * g_slice_free (CounterData, data);
1946 * The subparser would then be used as follows:
1949 * static void start_element (context, element_name, ...)
1951 * if (strcmp (element_name, "count-these") == 0)
1952 * start_counting (context);
1954 * /* else, handle other tags... */
1957 * static void end_element (context, element_name, ...)
1959 * if (strcmp (element_name, "count-these") == 0)
1960 * g_print ("Counted %d tags\n", end_counting (context));
1962 * /* else, handle other tags... */
1969 g_markup_parse_context_push (GMarkupParseContext *context,
1970 const GMarkupParser *parser,
1973 GMarkupRecursionTracker *tracker;
1975 tracker = g_slice_new (GMarkupRecursionTracker);
1976 tracker->prev_element = context->subparser_element;
1977 tracker->prev_parser = context->parser;
1978 tracker->prev_user_data = context->user_data;
1980 context->subparser_element = current_element (context);
1981 context->parser = parser;
1982 context->user_data = user_data;
1984 context->subparser_stack = g_slist_prepend (context->subparser_stack,
1989 * g_markup_parse_context_pop:
1990 * @context: a #GMarkupParseContext
1992 * Completes the process of a temporary sub-parser redirection.
1994 * This function exists to collect the user_data allocated by a
1995 * matching call to g_markup_parse_context_push(). It must be called
1996 * in the end_element handler corresponding to the start_element
1997 * handler during which g_markup_parse_context_push() was called. You
1998 * must not call this function from the error callback -- the
1999 * @user_data is provided directly to the callback in that case.
2001 * This function is not intended to be directly called by users
2002 * interested in invoking subparsers. Instead, it is intended to be
2003 * used by the subparsers themselves to implement a higher-level
2006 * Returns: the user_data passed to g_markup_parse_context_push().
2011 g_markup_parse_context_pop (GMarkupParseContext *context)
2015 if (!context->awaiting_pop)
2016 possibly_finish_subparser (context);
2018 g_assert (context->awaiting_pop);
2020 context->awaiting_pop = FALSE;
2022 /* valgrind friendliness */
2023 user_data = context->held_user_data;
2024 context->held_user_data = NULL;
2030 append_escaped_text (GString *str,
2039 end = text + length;
2044 next = g_utf8_next_char (p);
2049 g_string_append (str, "&");
2053 g_string_append (str, "<");
2057 g_string_append (str, ">");
2061 g_string_append (str, "'");
2065 g_string_append (str, """);
2069 c = g_utf8_get_char (p);
2070 if ((0x1 <= c && c <= 0x8) ||
2071 (0xb <= c && c <= 0xc) ||
2072 (0xe <= c && c <= 0x1f) ||
2073 (0x7f <= c && c <= 0x84) ||
2074 (0x86 <= c && c <= 0x9f))
2075 g_string_append_printf (str, "&#x%x;", c);
2077 g_string_append_len (str, p, next - p);
2086 * g_markup_escape_text:
2087 * @text: some valid UTF-8 text
2088 * @length: length of @text in bytes, or -1 if the text is nul-terminated
2090 * Escapes text so that the markup parser will parse it verbatim.
2091 * Less than, greater than, ampersand, etc. are replaced with the
2092 * corresponding entities. This function would typically be used
2093 * when writing out a file to be parsed with the markup parser.
2095 * Note that this function doesn't protect whitespace and line endings
2096 * from being processed according to the XML rules for normalization
2097 * of line endings and attribute values.
2099 * Note also that this function will produce character references in
2100 * the range of &#x1; ... &#x1f; for all control sequences
2101 * except for tabstop, newline and carriage return. The character
2102 * references in this range are not valid XML 1.0, but they are
2103 * valid XML 1.1 and will be accepted by the GMarkup parser.
2105 * Return value: a newly allocated string with the escaped text
2108 g_markup_escape_text (const gchar *text,
2113 g_return_val_if_fail (text != NULL, NULL);
2116 length = strlen (text);
2118 /* prealloc at least as long as original text */
2119 str = g_string_sized_new (length);
2120 append_escaped_text (str, text, length);
2122 return g_string_free (str, FALSE);
2127 * @format: a printf-style format string
2128 * @after: location to store a pointer to the character after
2129 * the returned conversion. On a %NULL return, returns the
2130 * pointer to the trailing NUL in the string
2132 * Find the next conversion in a printf-style format string.
2133 * Partially based on code from printf-parser.c,
2134 * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
2136 * Return value: pointer to the next conversion in @format,
2137 * or %NULL, if none.
2140 find_conversion (const char *format,
2143 const char *start = format;
2146 while (*start != '\0' && *start != '%')
2163 /* Test for positional argument. */
2164 if (*cp >= '0' && *cp <= '9')
2168 for (np = cp; *np >= '0' && *np <= '9'; np++)
2174 /* Skip the flags. */
2188 /* Skip the field width. */
2193 /* Test for positional argument. */
2194 if (*cp >= '0' && *cp <= '9')
2198 for (np = cp; *np >= '0' && *np <= '9'; np++)
2206 for (; *cp >= '0' && *cp <= '9'; cp++)
2210 /* Skip the precision. */
2216 /* Test for positional argument. */
2217 if (*cp >= '0' && *cp <= '9')
2221 for (np = cp; *np >= '0' && *np <= '9'; np++)
2229 for (; *cp >= '0' && *cp <= '9'; cp++)
2234 /* Skip argument type/size specifiers. */
2235 while (*cp == 'h' ||
2244 /* Skip the conversion character. */
2252 * g_markup_vprintf_escaped:
2253 * @format: printf() style format string
2254 * @args: variable argument list, similar to vprintf()
2256 * Formats the data in @args according to @format, escaping
2257 * all string and character arguments in the fashion
2258 * of g_markup_escape_text(). See g_markup_printf_escaped().
2260 * Return value: newly allocated result from formatting
2261 * operation. Free with g_free().
2266 g_markup_vprintf_escaped (const char *format,
2271 GString *result = NULL;
2272 gchar *output1 = NULL;
2273 gchar *output2 = NULL;
2274 const char *p, *op1, *op2;
2277 /* The technique here, is that we make two format strings that
2278 * have the identical conversions in the identical order to the
2279 * original strings, but differ in the text in-between. We
2280 * then use the normal g_strdup_vprintf() to format the arguments
2281 * with the two new format strings. By comparing the results,
2282 * we can figure out what segments of the output come from
2283 * the the original format string, and what from the arguments,
2284 * and thus know what portions of the string to escape.
2286 * For instance, for:
2288 * g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2290 * We form the two format strings "%sX%dX" and %sY%sY". The results
2291 * of formatting with those two strings are
2293 * "%sX%dX" => "Susan & FredX5X"
2294 * "%sY%dY" => "Susan & FredY5Y"
2296 * To find the span of the first argument, we find the first position
2297 * where the two arguments differ, which tells us that the first
2298 * argument formatted to "Susan & Fred". We then escape that
2299 * to "Susan & Fred" and join up with the intermediate portions
2300 * of the format string and the second argument to get
2301 * "Susan & Fred ate 5 apples".
2304 /* Create the two modified format strings
2306 format1 = g_string_new (NULL);
2307 format2 = g_string_new (NULL);
2312 const char *conv = find_conversion (p, &after);
2316 g_string_append_len (format1, conv, after - conv);
2317 g_string_append_c (format1, 'X');
2318 g_string_append_len (format2, conv, after - conv);
2319 g_string_append_c (format2, 'Y');
2324 /* Use them to format the arguments
2326 G_VA_COPY (args2, args);
2328 output1 = g_strdup_vprintf (format1->str, args);
2335 output2 = g_strdup_vprintf (format2->str, args2);
2340 result = g_string_new (NULL);
2342 /* Iterate through the original format string again,
2343 * copying the non-conversion portions and the escaped
2344 * converted arguments to the output string.
2352 const char *output_start;
2353 const char *conv = find_conversion (p, &after);
2356 if (!conv) /* The end, after points to the trailing \0 */
2358 g_string_append_len (result, p, after - p);
2362 g_string_append_len (result, p, conv - p);
2364 while (*op1 == *op2)
2370 escaped = g_markup_escape_text (output_start, op1 - output_start);
2371 g_string_append (result, escaped);
2380 g_string_free (format1, TRUE);
2381 g_string_free (format2, TRUE);
2386 return g_string_free (result, FALSE);
2392 * g_markup_printf_escaped:
2393 * @format: printf() style format string
2394 * @Varargs: the arguments to insert in the format string
2396 * Formats arguments according to @format, escaping
2397 * all string and character arguments in the fashion
2398 * of g_markup_escape_text(). This is useful when you
2399 * want to insert literal strings into XML-style markup
2400 * output, without having to worry that the strings
2401 * might themselves contain markup.
2404 * const char *store = "Fortnum & Mason";
2405 * const char *item = "Tea";
2408 * output = g_markup_printf_escaped ("<purchase>"
2409 * "<store>%s</store>"
2410 * "<item>%s</item>"
2411 * "</purchase>",
2415 * Return value: newly allocated result from formatting
2416 * operation. Free with g_free().
2421 g_markup_printf_escaped (const char *format, ...)
2426 va_start (args, format);
2427 result = g_markup_vprintf_escaped (format, args);
2434 g_markup_parse_boolean (const char *string,
2437 char const * const falses[] = { "false", "f", "no", "n", "0" };
2438 char const * const trues[] = { "true", "t", "yes", "y", "1" };
2441 for (i = 0; i < G_N_ELEMENTS (falses); i++)
2443 if (g_ascii_strcasecmp (string, falses[i]) == 0)
2452 for (i = 0; i < G_N_ELEMENTS (trues); i++)
2454 if (g_ascii_strcasecmp (string, trues[i]) == 0)
2467 * GMarkupCollectType:
2468 * @G_MARKUP_COLLECT_INVALID: used to terminate the list of attributes
2470 * @G_MARKUP_COLLECT_STRING: collect the string pointer directly from
2471 * the attribute_values[] array. Expects a
2472 * parameter of type (const char **). If
2473 * %G_MARKUP_COLLECT_OPTIONAL is specified
2474 * and the attribute isn't present then the
2475 * pointer will be set to %NULL.
2476 * @G_MARKUP_COLLECT_STRDUP: as with %G_MARKUP_COLLECT_STRING, but
2477 * expects a parameter of type (char **) and
2478 * g_strdup()s the returned pointer. The
2479 * pointer must be freed with g_free().
2480 * @G_MARKUP_COLLECT_BOOLEAN: expects a parameter of type (gboolean *)
2481 * and parses the attribute value as a
2482 * boolean. Sets %FALSE if the attribute
2483 * isn't present. Valid boolean values
2484 * consist of (case insensitive) "false",
2485 * "f", "no", "n", "0" and "true", "t",
2487 * @G_MARKUP_COLLECT_TRISTATE: as with %G_MARKUP_COLLECT_BOOLEAN, but
2488 * in the case of a missing attribute a
2489 * value is set that compares equal to
2490 * neither %FALSE nor %TRUE.
2491 * G_MARKUP_COLLECT_OPTIONAL is implied.
2492 * @G_MARKUP_COLLECT_OPTIONAL: can be bitwise ORed with the other
2493 * fields. If present, allows the
2494 * attribute not to appear. A default
2495 * value is set depending on what value
2498 * A mixed enumerated type and flags field. You must specify one type
2499 * (string, strdup, boolean, tristate). Additionally, you may
2500 * optionally bitwise OR the type with the flag
2501 * %G_MARKUP_COLLECT_OPTIONAL.
2503 * It is likely that this enum will be extended in the future to
2504 * support other types.
2508 * g_markup_collect_attributes:
2509 * @element_name: the current tag name
2510 * @attribute_names: the attribute names
2511 * @attribute_values: the attribute values
2512 * @error: a pointer to a #GError or %NULL
2513 * @first_type: the #GMarkupCollectType of the
2515 * @first_attr: the name of the first attribute
2516 * @...: a pointer to the storage location of the
2517 * first attribute (or %NULL), followed by
2518 * more types names and pointers, ending
2519 * with %G_MARKUP_COLLECT_INVALID.
2521 * Collects the attributes of the element from the
2522 * data passed to the #GMarkupParser start_element
2523 * function, dealing with common error conditions
2524 * and supporting boolean values.
2526 * This utility function is not required to write
2527 * a parser but can save a lot of typing.
2529 * The @element_name, @attribute_names,
2530 * @attribute_values and @error parameters passed
2531 * to the start_element callback should be passed
2532 * unmodified to this function.
2534 * Following these arguments is a list of
2535 * "supported" attributes to collect. It is an
2536 * error to specify multiple attributes with the
2537 * same name. If any attribute not in the list
2538 * appears in the @attribute_names array then an
2539 * unknown attribute error will result.
2541 * The #GMarkupCollectType field allows specifying
2542 * the type of collection to perform and if a
2543 * given attribute must appear or is optional.
2545 * The attribute name is simply the name of the
2546 * attribute to collect.
2548 * The pointer should be of the appropriate type
2549 * (see the descriptions under
2550 * #GMarkupCollectType) and may be %NULL in case a
2551 * particular attribute is to be allowed but
2554 * This function deals with issuing errors for missing attributes
2555 * (of type %G_MARKUP_ERROR_MISSING_ATTRIBUTE), unknown attributes
2556 * (of type %G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE) and duplicate
2557 * attributes (of type %G_MARKUP_ERROR_INVALID_CONTENT) as well
2558 * as parse errors for boolean-valued attributes (again of type
2559 * %G_MARKUP_ERROR_INVALID_CONTENT). In all of these cases %FALSE
2560 * will be returned and @error will be set as appropriate.
2562 * Return value: %TRUE if successful
2567 g_markup_collect_attributes (const gchar *element_name,
2568 const gchar **attribute_names,
2569 const gchar **attribute_values,
2571 GMarkupCollectType first_type,
2572 const gchar *first_attr,
2575 GMarkupCollectType type;
2587 va_start (ap, first_attr);
2588 while (type != G_MARKUP_COLLECT_INVALID)
2593 mandatory = !(type & G_MARKUP_COLLECT_OPTIONAL);
2594 type &= (G_MARKUP_COLLECT_OPTIONAL - 1);
2596 /* tristate records a value != TRUE and != FALSE
2597 * for the case where the attribute is missing
2599 if (type == G_MARKUP_COLLECT_TRISTATE)
2602 for (i = 0; attribute_names[i]; i++)
2603 if (i >= 40 || !(collected & (G_GUINT64_CONSTANT(1) << i)))
2604 if (!strcmp (attribute_names[i], attr))
2607 /* ISO C99 only promises that the user can pass up to 127 arguments.
2608 * Subtracting the first 4 arguments plus the final NULL and dividing
2609 * by 3 arguments per collected attribute, we are left with a maximum
2610 * number of supported attributes of (127 - 5) / 3 = 40.
2612 * In reality, nobody is ever going to call us with anywhere close to
2613 * 40 attributes to collect, so it is safe to assume that if i > 40
2614 * then the user has given some invalid or repeated arguments. These
2615 * problems will be caught and reported at the end of the function.
2617 * We know at this point that we have an error, but we don't know
2618 * what error it is, so just continue...
2621 collected |= (G_GUINT64_CONSTANT(1) << i);
2623 value = attribute_values[i];
2625 if (value == NULL && mandatory)
2627 g_set_error (error, G_MARKUP_ERROR,
2628 G_MARKUP_ERROR_MISSING_ATTRIBUTE,
2629 "element '%s' requires attribute '%s'",
2630 element_name, attr);
2638 case G_MARKUP_COLLECT_STRING:
2640 const char **str_ptr;
2642 str_ptr = va_arg (ap, const char **);
2644 if (str_ptr != NULL)
2649 case G_MARKUP_COLLECT_STRDUP:
2653 str_ptr = va_arg (ap, char **);
2655 if (str_ptr != NULL)
2656 *str_ptr = g_strdup (value);
2660 case G_MARKUP_COLLECT_BOOLEAN:
2661 case G_MARKUP_COLLECT_TRISTATE:
2666 bool_ptr = va_arg (ap, gboolean *);
2668 if (bool_ptr != NULL)
2670 if (type == G_MARKUP_COLLECT_TRISTATE)
2671 /* constructivists rejoice!
2672 * neither false nor true...
2676 else /* G_MARKUP_COLLECT_BOOLEAN */
2682 if (!g_markup_parse_boolean (value, va_arg (ap, gboolean *)))
2684 g_set_error (error, G_MARKUP_ERROR,
2685 G_MARKUP_ERROR_INVALID_CONTENT,
2686 "element '%s', attribute '%s', value '%s' "
2687 "cannot be parsed as a boolean value",
2688 element_name, attr, value);
2698 g_assert_not_reached ();
2701 type = va_arg (ap, GMarkupCollectType);
2702 attr = va_arg (ap, const char *);
2707 /* ensure we collected all the arguments */
2708 for (i = 0; attribute_names[i]; i++)
2709 if ((collected & (G_GUINT64_CONSTANT(1) << i)) == 0)
2711 /* attribute not collected: could be caused by two things.
2713 * 1) it doesn't exist in our list of attributes
2714 * 2) it existed but was matched by a duplicate attribute earlier
2720 for (j = 0; j < i; j++)
2721 if (strcmp (attribute_names[i], attribute_names[j]) == 0)
2725 /* j is now the first occurrence of attribute_names[i] */
2727 g_set_error (error, G_MARKUP_ERROR,
2728 G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
2729 "attribute '%s' invalid for element '%s'",
2730 attribute_names[i], element_name);
2732 g_set_error (error, G_MARKUP_ERROR,
2733 G_MARKUP_ERROR_INVALID_CONTENT,
2734 "attribute '%s' given multiple times for element '%s'",
2735 attribute_names[i], element_name);
2743 /* replay the above to free allocations */
2747 va_start (ap, first_attr);
2748 while (type != G_MARKUP_COLLECT_INVALID)
2752 ptr = va_arg (ap, gpointer);
2757 switch (type & (G_MARKUP_COLLECT_OPTIONAL - 1))
2759 case G_MARKUP_COLLECT_STRDUP:
2761 g_free (*(char **) ptr);
2763 case G_MARKUP_COLLECT_STRING:
2764 *(char **) ptr = NULL;
2767 case G_MARKUP_COLLECT_BOOLEAN:
2768 *(gboolean *) ptr = FALSE;
2771 case G_MARKUP_COLLECT_TRISTATE:
2772 *(gboolean *) ptr = -1;
2776 type = va_arg (ap, GMarkupCollectType);
2777 attr = va_arg (ap, const char *);