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;
86 GMarkupParseState state;
93 const gchar *current_text;
94 gssize current_text_len;
95 const gchar *current_text_end;
97 GString *leftover_char_portion;
99 /* used to save the start of the last interesting thingy */
104 guint document_empty : 1;
106 guint awaiting_pop : 1;
109 /* subparser support */
110 GSList *subparser_stack; /* (GMarkupRecursionTracker *) */
111 const char *subparser_element;
112 gpointer held_user_data;
116 * g_markup_parse_context_new:
117 * @parser: a #GMarkupParser
118 * @flags: one or more #GMarkupParseFlags
119 * @user_data: user data to pass to #GMarkupParser functions
120 * @user_data_dnotify: user data destroy notifier called when the parse context is freed
122 * Creates a new parse context. A parse context is used to parse
123 * marked-up documents. You can feed any number of documents into
124 * a context, as long as no errors occur; once an error occurs,
125 * the parse context can't continue to parse text (you have to free it
126 * and create a new parse context).
128 * Return value: a new #GMarkupParseContext
130 GMarkupParseContext *
131 g_markup_parse_context_new (const GMarkupParser *parser,
132 GMarkupParseFlags flags,
134 GDestroyNotify user_data_dnotify)
136 GMarkupParseContext *context;
138 g_return_val_if_fail (parser != NULL, NULL);
140 context = g_new (GMarkupParseContext, 1);
142 context->parser = parser;
143 context->flags = flags;
144 context->user_data = user_data;
145 context->dnotify = user_data_dnotify;
147 context->line_number = 1;
148 context->char_number = 1;
150 context->partial_chunk = NULL;
152 context->state = STATE_START;
153 context->tag_stack = NULL;
154 context->attr_names = NULL;
155 context->attr_values = NULL;
156 context->cur_attr = -1;
157 context->alloc_attrs = 0;
159 context->current_text = NULL;
160 context->current_text_len = -1;
161 context->current_text_end = NULL;
162 context->leftover_char_portion = NULL;
164 context->start = NULL;
165 context->iter = NULL;
167 context->document_empty = TRUE;
168 context->parsing = FALSE;
170 context->awaiting_pop = FALSE;
171 context->subparser_stack = NULL;
172 context->subparser_element = NULL;
174 /* this is only looked at if awaiting_pop = TRUE. initialise anyway. */
175 context->held_user_data = NULL;
177 context->balance = 0;
183 * g_markup_parse_context_free:
184 * @context: a #GMarkupParseContext
186 * Frees a #GMarkupParseContext. Can't be called from inside
187 * one of the #GMarkupParser functions. Can't be called while
188 * a subparser is pushed.
191 g_markup_parse_context_free (GMarkupParseContext *context)
193 g_return_if_fail (context != NULL);
194 g_return_if_fail (!context->parsing);
195 g_return_if_fail (!context->subparser_stack);
196 g_return_if_fail (!context->awaiting_pop);
198 if (context->dnotify)
199 (* context->dnotify) (context->user_data);
201 g_strfreev (context->attr_names);
202 g_strfreev (context->attr_values);
204 g_slist_foreach (context->tag_stack, (GFunc)g_free, NULL);
205 g_slist_free (context->tag_stack);
207 if (context->partial_chunk)
208 g_string_free (context->partial_chunk, TRUE);
210 if (context->leftover_char_portion)
211 g_string_free (context->leftover_char_portion, TRUE);
216 static void pop_subparser_stack (GMarkupParseContext *context);
219 mark_error (GMarkupParseContext *context,
222 context->state = STATE_ERROR;
224 if (context->parser->error)
225 (*context->parser->error) (context, error, context->user_data);
227 /* report the error all the way up to free all the user-data */
228 while (context->subparser_stack)
230 pop_subparser_stack (context);
231 context->awaiting_pop = FALSE; /* already been freed */
233 if (context->parser->error)
234 (*context->parser->error) (context, error, context->user_data);
238 static void set_error (GMarkupParseContext *context,
242 ...) G_GNUC_PRINTF (4, 5);
245 set_error_literal (GMarkupParseContext *context,
248 const gchar *message)
252 tmp_error = g_error_new_literal (G_MARKUP_ERROR, code, message);
254 g_prefix_error (&tmp_error,
255 _("Error on line %d char %d: "),
256 context->line_number,
257 context->char_number);
259 mark_error (context, tmp_error);
261 g_propagate_error (error, tmp_error);
265 set_error (GMarkupParseContext *context,
275 va_start (args, format);
276 s = g_strdup_vprintf (format, args);
279 /* Make sure that the GError message is valid UTF-8 even if it is
280 * complaining about invalid UTF-8 in the markup: */
281 s_valid = _g_utf8_make_valid (s);
282 set_error_literal (context, error, code, s);
289 propagate_error (GMarkupParseContext *context,
293 if (context->flags & G_MARKUP_PREFIX_ERROR_POSITION)
294 g_prefix_error (&src,
295 _("Error on line %d char %d: "),
296 context->line_number,
297 context->char_number);
299 mark_error (context, src);
301 g_propagate_error (dest, src);
304 /* To make these faster, we first use the ascii-only tests, then check
305 * for the usual non-alnum name-end chars, and only then call the
306 * expensive unicode stuff. Nobody uses non-ascii in XML tag/attribute
307 * names, so this is a reasonable hack that virtually always avoids
310 #define IS_COMMON_NAME_END_CHAR(c) \
311 ((c) == '=' || (c) == '/' || (c) == '>' || (c) == ' ')
314 is_name_start_char (const gchar *p)
316 if (g_ascii_isalpha (*p) ||
317 (!IS_COMMON_NAME_END_CHAR (*p) &&
320 g_unichar_isalpha (g_utf8_get_char (p)))))
327 is_name_char (const gchar *p)
329 if (g_ascii_isalnum (*p) ||
330 (!IS_COMMON_NAME_END_CHAR (*p) &&
335 g_unichar_isalpha (g_utf8_get_char (p)))))
343 char_str (gunichar c,
347 g_unichar_to_utf8 (c, buf);
352 utf8_str (const gchar *utf8,
355 char_str (g_utf8_get_char (utf8), buf);
360 set_unescape_error (GMarkupParseContext *context,
362 const gchar *remaining_text,
363 const gchar *remaining_text_end,
371 gint remaining_newlines;
374 remaining_newlines = 0;
376 while (p != remaining_text_end)
379 ++remaining_newlines;
383 va_start (args, format);
384 s = g_strdup_vprintf (format, args);
387 tmp_error = g_error_new (G_MARKUP_ERROR,
389 _("Error on line %d: %s"),
390 context->line_number - remaining_newlines,
395 mark_error (context, tmp_error);
397 g_propagate_error (error, tmp_error);
403 USTATE_AFTER_AMPERSAND,
404 USTATE_INSIDE_ENTITY_NAME,
405 USTATE_AFTER_CHARREF_HASH
410 GMarkupParseContext *context;
414 const gchar *text_end;
415 const gchar *entity_start;
419 unescape_text_state_inside_text (UnescapeContext *ucontext,
424 gboolean normalize_attribute;
426 if (ucontext->context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
427 ucontext->context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
428 normalize_attribute = TRUE;
430 normalize_attribute = FALSE;
434 while (p != ucontext->text_end)
440 else if (normalize_attribute && (*p == '\t' || *p == '\n'))
442 g_string_append_len (ucontext->str, start, p - start);
443 g_string_append_c (ucontext->str, ' ');
444 p = g_utf8_next_char (p);
449 g_string_append_len (ucontext->str, start, p - start);
450 g_string_append_c (ucontext->str, normalize_attribute ? ' ' : '\n');
451 p = g_utf8_next_char (p);
452 if (p != ucontext->text_end && *p == '\n')
453 p = g_utf8_next_char (p);
457 p = g_utf8_next_char (p);
461 g_string_append_len (ucontext->str, start, p - start);
463 if (p != ucontext->text_end && *p == '&')
465 p = g_utf8_next_char (p);
466 ucontext->state = USTATE_AFTER_AMPERSAND;
473 unescape_text_state_after_ampersand (UnescapeContext *ucontext,
477 ucontext->entity_start = NULL;
481 p = g_utf8_next_char (p);
483 ucontext->entity_start = p;
484 ucontext->state = USTATE_AFTER_CHARREF_HASH;
486 else if (!is_name_start_char (p))
490 set_unescape_error (ucontext->context, error,
491 p, ucontext->text_end,
492 G_MARKUP_ERROR_PARSE,
493 _("Empty entity '&;' seen; valid "
494 "entities are: & " < > '"));
500 set_unescape_error (ucontext->context, error,
501 p, ucontext->text_end,
502 G_MARKUP_ERROR_PARSE,
503 _("Character '%s' is not valid at "
504 "the start of an entity name; "
505 "the & character begins an entity; "
506 "if this ampersand isn't supposed "
507 "to be an entity, escape it as "
514 ucontext->entity_start = p;
515 ucontext->state = USTATE_INSIDE_ENTITY_NAME;
522 unescape_text_state_inside_entity_name (UnescapeContext *ucontext,
526 while (p != ucontext->text_end)
530 else if (!is_name_char (p))
534 set_unescape_error (ucontext->context, error,
535 p, ucontext->text_end,
536 G_MARKUP_ERROR_PARSE,
537 _("Character '%s' is not valid "
538 "inside an entity name"),
543 p = g_utf8_next_char (p);
546 if (ucontext->context->state != STATE_ERROR)
548 if (p != ucontext->text_end)
550 gint len = p - ucontext->entity_start;
552 /* move to after semicolon */
553 p = g_utf8_next_char (p);
554 ucontext->state = USTATE_INSIDE_TEXT;
556 if (strncmp (ucontext->entity_start, "lt", len) == 0)
557 g_string_append_c (ucontext->str, '<');
558 else if (strncmp (ucontext->entity_start, "gt", len) == 0)
559 g_string_append_c (ucontext->str, '>');
560 else if (strncmp (ucontext->entity_start, "amp", len) == 0)
561 g_string_append_c (ucontext->str, '&');
562 else if (strncmp (ucontext->entity_start, "quot", len) == 0)
563 g_string_append_c (ucontext->str, '"');
564 else if (strncmp (ucontext->entity_start, "apos", len) == 0)
565 g_string_append_c (ucontext->str, '\'');
570 name = g_strndup (ucontext->entity_start, len);
571 set_unescape_error (ucontext->context, error,
572 p, ucontext->text_end,
573 G_MARKUP_ERROR_PARSE,
574 _("Entity name '%s' is not known"),
581 set_unescape_error (ucontext->context, error,
582 /* give line number of the & */
583 ucontext->entity_start, ucontext->text_end,
584 G_MARKUP_ERROR_PARSE,
585 _("Entity did not end with a semicolon; "
586 "most likely you used an ampersand "
587 "character without intending to start "
588 "an entity - escape ampersand as &"));
597 unescape_text_state_after_charref_hash (UnescapeContext *ucontext,
601 gboolean is_hex = FALSE;
604 start = ucontext->entity_start;
609 p = g_utf8_next_char (p);
613 while (p != ucontext->text_end && *p != ';')
614 p = g_utf8_next_char (p);
616 if (p != ucontext->text_end)
618 g_assert (*p == ';');
620 /* digit is between start and p */
629 l = strtoul (start, &end, 16);
631 l = strtoul (start, &end, 10);
633 if (end != p || errno != 0)
635 set_unescape_error (ucontext->context, error,
636 start, ucontext->text_end,
637 G_MARKUP_ERROR_PARSE,
638 _("Failed to parse '%-.*s', which "
639 "should have been a digit "
640 "inside a character reference "
641 "(ê for example) - perhaps "
642 "the digit is too large"),
647 /* characters XML 1.1 permits */
648 if ((0 < l && l <= 0xD7FF) ||
649 (0xE000 <= l && l <= 0xFFFD) ||
650 (0x10000 <= l && l <= 0x10FFFF))
653 g_string_append (ucontext->str, char_str (l, buf));
657 set_unescape_error (ucontext->context, error,
658 start, ucontext->text_end,
659 G_MARKUP_ERROR_PARSE,
660 _("Character reference '%-.*s' does not "
661 "encode a permitted character"),
666 /* Move to next state */
667 p = g_utf8_next_char (p); /* past semicolon */
668 ucontext->state = USTATE_INSIDE_TEXT;
672 set_unescape_error (ucontext->context, error,
673 start, ucontext->text_end,
674 G_MARKUP_ERROR_PARSE,
675 _("Empty character reference; "
676 "should include a digit such as "
682 set_unescape_error (ucontext->context, error,
683 start, ucontext->text_end,
684 G_MARKUP_ERROR_PARSE,
685 _("Character reference did not end with a "
687 "most likely you used an ampersand "
688 "character without intending to start "
689 "an entity - escape ampersand as &"));
696 unescape_text (GMarkupParseContext *context,
698 const gchar *text_end,
702 UnescapeContext ucontext;
705 ucontext.context = context;
706 ucontext.text = text;
707 ucontext.text_end = text_end;
708 ucontext.entity_start = NULL;
710 ucontext.str = g_string_sized_new (text_end - text);
712 ucontext.state = USTATE_INSIDE_TEXT;
715 while (p != text_end && context->state != STATE_ERROR)
717 g_assert (p < text_end);
719 switch (ucontext.state)
721 case USTATE_INSIDE_TEXT:
723 p = unescape_text_state_inside_text (&ucontext,
729 case USTATE_AFTER_AMPERSAND:
731 p = unescape_text_state_after_ampersand (&ucontext,
738 case USTATE_INSIDE_ENTITY_NAME:
740 p = unescape_text_state_inside_entity_name (&ucontext,
746 case USTATE_AFTER_CHARREF_HASH:
748 p = unescape_text_state_after_charref_hash (&ucontext,
755 g_assert_not_reached ();
760 if (context->state != STATE_ERROR)
762 switch (ucontext.state)
764 case USTATE_INSIDE_TEXT:
766 case USTATE_AFTER_AMPERSAND:
767 case USTATE_INSIDE_ENTITY_NAME:
768 set_unescape_error (context, error,
770 G_MARKUP_ERROR_PARSE,
771 _("Unfinished entity reference"));
773 case USTATE_AFTER_CHARREF_HASH:
774 set_unescape_error (context, error,
776 G_MARKUP_ERROR_PARSE,
777 _("Unfinished character reference"));
782 if (context->state == STATE_ERROR)
784 g_string_free (ucontext.str, TRUE);
790 *unescaped = ucontext.str;
795 static inline gboolean
796 advance_char (GMarkupParseContext *context)
798 context->iter = g_utf8_next_char (context->iter);
799 context->char_number += 1;
801 if (context->iter == context->current_text_end)
805 else if (*context->iter == '\n')
807 context->line_number += 1;
808 context->char_number = 1;
814 static inline gboolean
817 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
821 skip_spaces (GMarkupParseContext *context)
825 if (!xml_isspace (*context->iter))
828 while (advance_char (context));
832 advance_to_name_end (GMarkupParseContext *context)
836 if (!is_name_char (context->iter))
839 while (advance_char (context));
843 add_to_partial (GMarkupParseContext *context,
844 const gchar *text_start,
845 const gchar *text_end)
847 if (context->partial_chunk == NULL)
848 context->partial_chunk = g_string_sized_new (text_end - text_start);
850 if (text_start != text_end)
851 g_string_append_len (context->partial_chunk, text_start,
852 text_end - text_start);
854 /* Invariant here that partial_chunk exists */
858 truncate_partial (GMarkupParseContext *context)
860 if (context->partial_chunk != NULL)
862 context->partial_chunk = g_string_truncate (context->partial_chunk, 0);
867 current_element (GMarkupParseContext *context)
869 return context->tag_stack->data;
873 pop_subparser_stack (GMarkupParseContext *context)
875 GMarkupRecursionTracker *tracker;
877 g_assert (context->subparser_stack);
879 tracker = context->subparser_stack->data;
881 context->awaiting_pop = TRUE;
882 context->held_user_data = context->user_data;
884 context->user_data = tracker->prev_user_data;
885 context->parser = tracker->prev_parser;
886 context->subparser_element = tracker->prev_element;
887 g_slice_free (GMarkupRecursionTracker, tracker);
889 context->subparser_stack = g_slist_delete_link (context->subparser_stack,
890 context->subparser_stack);
894 possibly_finish_subparser (GMarkupParseContext *context)
896 if (current_element (context) == context->subparser_element)
897 pop_subparser_stack (context);
901 ensure_no_outstanding_subparser (GMarkupParseContext *context)
903 if (context->awaiting_pop)
904 g_critical ("During the first end_element call after invoking a "
905 "subparser you must pop the subparser stack and handle "
906 "the freeing of the subparser user_data. This can be "
907 "done by calling the end function of the subparser. "
908 "Very probably, your program just leaked memory.");
910 /* let valgrind watch the pointer disappear... */
911 context->held_user_data = NULL;
912 context->awaiting_pop = FALSE;
916 current_attribute (GMarkupParseContext *context)
918 g_assert (context->cur_attr >= 0);
919 return context->attr_names[context->cur_attr];
923 find_current_text_end (GMarkupParseContext *context)
925 /* This function must be safe (non-segfaulting) on invalid UTF8.
926 * It assumes the string starts with a character start
928 const gchar *end = context->current_text + context->current_text_len;
932 g_assert (context->current_text_len > 0);
934 p = g_utf8_find_prev_char (context->current_text, end);
936 g_assert (p != NULL); /* since current_text was a char start */
938 /* p is now the start of the last character or character portion. */
940 next = g_utf8_next_char (p); /* this only touches *p, nothing beyond */
944 /* whole character */
945 context->current_text_end = end;
950 context->leftover_char_portion = g_string_new_len (p, end - p);
951 context->current_text_len -= (end - p);
952 context->current_text_end = p;
958 add_attribute (GMarkupParseContext *context, char *name)
960 if (context->cur_attr + 2 >= context->alloc_attrs)
962 context->alloc_attrs += 5; /* silly magic number */
963 context->attr_names = g_realloc (context->attr_names, sizeof(char*)*context->alloc_attrs);
964 context->attr_values = g_realloc (context->attr_values, sizeof(char*)*context->alloc_attrs);
967 context->attr_names[context->cur_attr] = name;
968 context->attr_values[context->cur_attr] = NULL;
969 context->attr_names[context->cur_attr+1] = NULL;
970 context->attr_values[context->cur_attr+1] = NULL;
974 * g_markup_parse_context_parse:
975 * @context: a #GMarkupParseContext
976 * @text: chunk of text to parse
977 * @text_len: length of @text in bytes
978 * @error: return location for a #GError
980 * Feed some data to the #GMarkupParseContext. The data need not
981 * be valid UTF-8; an error will be signaled if it's invalid.
982 * The data need not be an entire document; you can feed a document
983 * into the parser incrementally, via multiple calls to this function.
984 * Typically, as you receive data from a network connection or file,
985 * you feed each received chunk of data into this function, aborting
986 * the process if an error occurs. Once an error is reported, no further
987 * data may be fed to the #GMarkupParseContext; all errors are fatal.
989 * Return value: %FALSE if an error occurred, %TRUE on success
992 g_markup_parse_context_parse (GMarkupParseContext *context,
997 const gchar *first_invalid;
999 g_return_val_if_fail (context != NULL, FALSE);
1000 g_return_val_if_fail (text != NULL, FALSE);
1001 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1002 g_return_val_if_fail (!context->parsing, FALSE);
1005 text_len = strlen (text);
1010 context->parsing = TRUE;
1012 if (context->leftover_char_portion)
1014 const gchar *first_char;
1016 if ((*text & 0xc0) != 0x80)
1019 first_char = g_utf8_find_next_char (text, text + text_len);
1023 /* leftover_char_portion was completed. Parse it. */
1024 GString *portion = context->leftover_char_portion;
1026 g_string_append_len (context->leftover_char_portion,
1027 text, first_char - text);
1029 /* hacks to allow recursion */
1030 context->parsing = FALSE;
1031 context->leftover_char_portion = NULL;
1033 if (!g_markup_parse_context_parse (context,
1034 portion->str, portion->len,
1037 g_assert (context->state == STATE_ERROR);
1040 g_string_free (portion, TRUE);
1041 context->parsing = TRUE;
1043 /* Skip the fraction of char that was in this text */
1044 text_len -= (first_char - text);
1049 /* another little chunk of the leftover char; geez
1050 * someone is inefficient.
1052 g_string_append_len (context->leftover_char_portion,
1055 if (context->leftover_char_portion->len > 7)
1057 /* The leftover char portion is too big to be
1060 set_error_literal (context,
1062 G_MARKUP_ERROR_BAD_UTF8,
1063 _("Invalid UTF-8 encoded text - overlong sequence"));
1070 context->current_text = text;
1071 context->current_text_len = text_len;
1072 context->iter = context->current_text;
1073 context->start = context->iter;
1075 /* Nothing left after finishing the leftover char, or nothing
1076 * passed in to begin with.
1078 if (context->current_text_len == 0)
1081 /* find_current_text_end () assumes the string starts at
1082 * a character start, so we need to validate at least
1083 * that much. It doesn't assume any following bytes
1086 if ((*context->current_text & 0xc0) == 0x80) /* not a char start */
1088 set_error_literal (context,
1090 G_MARKUP_ERROR_BAD_UTF8,
1091 _("Invalid UTF-8 encoded text - not a start char"));
1095 /* Initialize context->current_text_end, possibly adjusting
1096 * current_text_len, and add any leftover char portion
1098 find_current_text_end (context);
1100 /* Validate UTF8 (must be done after we find the end, since
1101 * we could have a trailing incomplete char)
1103 if (!g_utf8_validate (context->current_text,
1104 context->current_text_len,
1109 gchar *current_text_dup;
1111 q = p = context->current_text;
1112 while (p != first_invalid)
1118 context->char_number = 1;
1123 context->line_number += newlines;
1124 context->char_number += g_utf8_strlen (q, first_invalid - q);
1126 current_text_dup = g_strndup (context->current_text, context->current_text_len);
1129 G_MARKUP_ERROR_BAD_UTF8,
1130 _("Invalid UTF-8 encoded text - not valid '%s'"),
1132 g_free (current_text_dup);
1136 while (context->iter != context->current_text_end)
1138 switch (context->state)
1141 /* Possible next state: AFTER_OPEN_ANGLE */
1143 g_assert (context->tag_stack == NULL);
1145 /* whitespace is ignored outside of any elements */
1146 skip_spaces (context);
1148 if (context->iter != context->current_text_end)
1150 if (*context->iter == '<')
1152 /* Move after the open angle */
1153 advance_char (context);
1155 context->state = STATE_AFTER_OPEN_ANGLE;
1157 /* this could start a passthrough */
1158 context->start = context->iter;
1160 /* document is now non-empty */
1161 context->document_empty = FALSE;
1165 set_error_literal (context,
1167 G_MARKUP_ERROR_PARSE,
1168 _("Document must begin with an element (e.g. <book>)"));
1173 case STATE_AFTER_OPEN_ANGLE:
1174 /* Possible next states: INSIDE_OPEN_TAG_NAME,
1175 * AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1177 if (*context->iter == '?' ||
1178 *context->iter == '!')
1180 /* include < in the passthrough */
1181 const gchar *openangle = "<";
1182 add_to_partial (context, openangle, openangle + 1);
1183 context->start = context->iter;
1184 context->balance = 1;
1185 context->state = STATE_INSIDE_PASSTHROUGH;
1187 else if (*context->iter == '/')
1190 advance_char (context);
1192 context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1194 else if (is_name_start_char (context->iter))
1196 context->state = STATE_INSIDE_OPEN_TAG_NAME;
1198 /* start of tag name */
1199 context->start = context->iter;
1207 G_MARKUP_ERROR_PARSE,
1208 _("'%s' is not a valid character following "
1209 "a '<' character; it may not begin an "
1211 utf8_str (context->iter, buf));
1215 /* The AFTER_CLOSE_ANGLE state is actually sort of
1216 * broken, because it doesn't correspond to a range
1217 * of characters in the input stream as the others do,
1218 * and thus makes things harder to conceptualize
1220 case STATE_AFTER_CLOSE_ANGLE:
1221 /* Possible next states: INSIDE_TEXT, STATE_START */
1222 if (context->tag_stack == NULL)
1224 context->start = NULL;
1225 context->state = STATE_START;
1229 context->start = context->iter;
1230 context->state = STATE_INSIDE_TEXT;
1234 case STATE_AFTER_ELISION_SLASH:
1235 /* Possible next state: AFTER_CLOSE_ANGLE */
1238 /* We need to pop the tag stack and call the end_element
1239 * function, since this is the close tag
1241 GError *tmp_error = NULL;
1243 g_assert (context->tag_stack != NULL);
1245 possibly_finish_subparser (context);
1248 if (context->parser->end_element)
1249 (* context->parser->end_element) (context,
1250 context->tag_stack->data,
1254 ensure_no_outstanding_subparser (context);
1258 mark_error (context, tmp_error);
1259 g_propagate_error (error, tmp_error);
1263 if (*context->iter == '>')
1265 /* move after the close angle */
1266 advance_char (context);
1267 context->state = STATE_AFTER_CLOSE_ANGLE;
1275 G_MARKUP_ERROR_PARSE,
1276 _("Odd character '%s', expected a '>' character "
1277 "to end the empty-element tag '%s'"),
1278 utf8_str (context->iter, buf),
1279 current_element (context));
1283 g_free (context->tag_stack->data);
1284 context->tag_stack = g_slist_delete_link (context->tag_stack,
1285 context->tag_stack);
1289 case STATE_INSIDE_OPEN_TAG_NAME:
1290 /* Possible next states: BETWEEN_ATTRIBUTES */
1292 /* if there's a partial chunk then it's the first part of the
1293 * tag name. If there's a context->start then it's the start
1294 * of the tag name in current_text, the partial chunk goes
1295 * before that start though.
1297 advance_to_name_end (context);
1299 if (context->iter == context->current_text_end)
1301 /* The name hasn't necessarily ended. Merge with
1302 * partial chunk, leave state unchanged.
1304 add_to_partial (context, context->start, context->iter);
1308 /* The name has ended. Combine it with the partial chunk
1309 * if any; push it on the stack; enter next state.
1311 add_to_partial (context, context->start, context->iter);
1312 context->tag_stack =
1313 g_slist_prepend (context->tag_stack,
1314 g_string_free (context->partial_chunk,
1317 context->partial_chunk = NULL;
1319 context->state = STATE_BETWEEN_ATTRIBUTES;
1320 context->start = NULL;
1324 case STATE_INSIDE_ATTRIBUTE_NAME:
1325 /* Possible next states: AFTER_ATTRIBUTE_NAME */
1327 advance_to_name_end (context);
1328 add_to_partial (context, context->start, context->iter);
1330 /* read the full name, if we enter the equals sign state
1331 * then add the attribute to the list (without the value),
1332 * otherwise store a partial chunk to be prepended later.
1334 if (context->iter != context->current_text_end)
1335 context->state = STATE_AFTER_ATTRIBUTE_NAME;
1338 case STATE_AFTER_ATTRIBUTE_NAME:
1339 /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1341 skip_spaces (context);
1343 if (context->iter != context->current_text_end)
1345 /* The name has ended. Combine it with the partial chunk
1346 * if any; push it on the stack; enter next state.
1348 add_attribute (context, g_string_free (context->partial_chunk, FALSE));
1350 context->partial_chunk = NULL;
1351 context->start = NULL;
1353 if (*context->iter == '=')
1355 advance_char (context);
1356 context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1364 G_MARKUP_ERROR_PARSE,
1365 _("Odd character '%s', expected a '=' after "
1366 "attribute name '%s' of element '%s'"),
1367 utf8_str (context->iter, buf),
1368 current_attribute (context),
1369 current_element (context));
1375 case STATE_BETWEEN_ATTRIBUTES:
1376 /* Possible next states: AFTER_CLOSE_ANGLE,
1377 * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1379 skip_spaces (context);
1381 if (context->iter != context->current_text_end)
1383 if (*context->iter == '/')
1385 advance_char (context);
1386 context->state = STATE_AFTER_ELISION_SLASH;
1388 else if (*context->iter == '>')
1391 advance_char (context);
1392 context->state = STATE_AFTER_CLOSE_ANGLE;
1394 else if (is_name_start_char (context->iter))
1396 context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1397 /* start of attribute name */
1398 context->start = context->iter;
1406 G_MARKUP_ERROR_PARSE,
1407 _("Odd character '%s', expected a '>' or '/' "
1408 "character to end the start tag of "
1409 "element '%s', or optionally an attribute; "
1410 "perhaps you used an invalid character in "
1411 "an attribute name"),
1412 utf8_str (context->iter, buf),
1413 current_element (context));
1416 /* If we're done with attributes, invoke
1417 * the start_element callback
1419 if (context->state == STATE_AFTER_ELISION_SLASH ||
1420 context->state == STATE_AFTER_CLOSE_ANGLE)
1422 const gchar *start_name;
1423 /* Ugly, but the current code expects an empty array instead of NULL */
1424 const gchar *empty = NULL;
1425 const gchar **attr_names = ∅
1426 const gchar **attr_values = ∅
1429 /* Call user callback for element start */
1430 start_name = current_element (context);
1432 if (context->cur_attr >= 0)
1434 attr_names = (const gchar**)context->attr_names;
1435 attr_values = (const gchar**)context->attr_values;
1439 if (context->parser->start_element)
1440 (* context->parser->start_element) (context,
1442 (const gchar **)attr_names,
1443 (const gchar **)attr_values,
1447 /* Go ahead and free the attributes. */
1448 for (; context->cur_attr >= 0; context->cur_attr--)
1450 int pos = context->cur_attr;
1451 g_free (context->attr_names[pos]);
1452 g_free (context->attr_values[pos]);
1453 context->attr_names[pos] = context->attr_values[pos] = NULL;
1455 g_assert (context->cur_attr == -1);
1456 g_assert (context->attr_names == NULL ||
1457 context->attr_names[0] == NULL);
1458 g_assert (context->attr_values == NULL ||
1459 context->attr_values[0] == NULL);
1461 if (tmp_error != NULL)
1462 propagate_error (context, error, tmp_error);
1467 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1468 /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1470 skip_spaces (context);
1472 if (context->iter != context->current_text_end)
1474 if (*context->iter == '"')
1476 advance_char (context);
1477 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1478 context->start = context->iter;
1480 else if (*context->iter == '\'')
1482 advance_char (context);
1483 context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1484 context->start = context->iter;
1492 G_MARKUP_ERROR_PARSE,
1493 _("Odd character '%s', expected an open quote mark "
1494 "after the equals sign when giving value for "
1495 "attribute '%s' of element '%s'"),
1496 utf8_str (context->iter, buf),
1497 current_attribute (context),
1498 current_element (context));
1503 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1504 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1505 /* Possible next states: BETWEEN_ATTRIBUTES */
1509 if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ)
1520 if (*context->iter == delim)
1523 while (advance_char (context));
1525 if (context->iter == context->current_text_end)
1527 /* The value hasn't necessarily ended. Merge with
1528 * partial chunk, leave state unchanged.
1530 add_to_partial (context, context->start, context->iter);
1534 /* The value has ended at the quote mark. Combine it
1535 * with the partial chunk if any; set it for the current
1540 add_to_partial (context, context->start, context->iter);
1542 g_assert (context->cur_attr >= 0);
1544 if (unescape_text (context,
1545 context->partial_chunk->str,
1546 context->partial_chunk->str +
1547 context->partial_chunk->len,
1551 /* success, advance past quote and set state. */
1552 context->attr_values[context->cur_attr] = g_string_free (unescaped, FALSE);
1553 advance_char (context);
1554 context->state = STATE_BETWEEN_ATTRIBUTES;
1555 context->start = NULL;
1558 truncate_partial (context);
1562 case STATE_INSIDE_TEXT:
1563 /* Possible next states: AFTER_OPEN_ANGLE */
1566 if (*context->iter == '<')
1569 while (advance_char (context));
1571 /* The text hasn't necessarily ended. Merge with
1572 * partial chunk, leave state unchanged.
1575 add_to_partial (context, context->start, context->iter);
1577 if (context->iter != context->current_text_end)
1579 GString *unescaped = NULL;
1581 /* The text has ended at the open angle. Call the text
1585 if (unescape_text (context,
1586 context->partial_chunk->str,
1587 context->partial_chunk->str +
1588 context->partial_chunk->len,
1592 GError *tmp_error = NULL;
1594 if (context->parser->text)
1595 (*context->parser->text) (context,
1601 g_string_free (unescaped, TRUE);
1603 if (tmp_error == NULL)
1605 /* advance past open angle and set state. */
1606 advance_char (context);
1607 context->state = STATE_AFTER_OPEN_ANGLE;
1608 /* could begin a passthrough */
1609 context->start = context->iter;
1612 propagate_error (context, error, tmp_error);
1615 truncate_partial (context);
1619 case STATE_AFTER_CLOSE_TAG_SLASH:
1620 /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1621 if (is_name_start_char (context->iter))
1623 context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1625 /* start of tag name */
1626 context->start = context->iter;
1634 G_MARKUP_ERROR_PARSE,
1635 _("'%s' is not a valid character following "
1636 "the characters '</'; '%s' may not begin an "
1638 utf8_str (context->iter, buf),
1639 utf8_str (context->iter, buf));
1643 case STATE_INSIDE_CLOSE_TAG_NAME:
1644 /* Possible next state: AFTER_CLOSE_TAG_NAME */
1645 advance_to_name_end (context);
1646 add_to_partial (context, context->start, context->iter);
1648 if (context->iter != context->current_text_end)
1649 context->state = STATE_AFTER_CLOSE_TAG_NAME;
1652 case STATE_AFTER_CLOSE_TAG_NAME:
1653 /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1655 skip_spaces (context);
1657 if (context->iter != context->current_text_end)
1661 /* The name has ended. Combine it with the partial chunk
1662 * if any; check that it matches stack top and pop
1663 * stack; invoke proper callback; enter next state.
1665 close_name = g_string_free (context->partial_chunk, FALSE);
1666 context->partial_chunk = NULL;
1668 if (*context->iter != '>')
1674 G_MARKUP_ERROR_PARSE,
1675 _("'%s' is not a valid character following "
1676 "the close element name '%s'; the allowed "
1677 "character is '>'"),
1678 utf8_str (context->iter, buf),
1681 else if (context->tag_stack == NULL)
1685 G_MARKUP_ERROR_PARSE,
1686 _("Element '%s' was closed, no element "
1687 "is currently open"),
1690 else if (strcmp (close_name, current_element (context)) != 0)
1694 G_MARKUP_ERROR_PARSE,
1695 _("Element '%s' was closed, but the currently "
1696 "open element is '%s'"),
1698 current_element (context));
1703 advance_char (context);
1704 context->state = STATE_AFTER_CLOSE_ANGLE;
1705 context->start = NULL;
1707 possibly_finish_subparser (context);
1709 /* call the end_element callback */
1711 if (context->parser->end_element)
1712 (* context->parser->end_element) (context,
1717 ensure_no_outstanding_subparser (context);
1719 /* Pop the tag stack */
1720 g_free (context->tag_stack->data);
1721 context->tag_stack = g_slist_delete_link (context->tag_stack,
1722 context->tag_stack);
1725 propagate_error (context, error, tmp_error);
1728 g_free (close_name);
1732 case STATE_INSIDE_PASSTHROUGH:
1733 /* Possible next state: AFTER_CLOSE_ANGLE */
1736 if (*context->iter == '<')
1738 if (*context->iter == '>')
1744 add_to_partial (context, context->start, context->iter);
1745 context->start = context->iter;
1747 str = context->partial_chunk->str;
1748 len = context->partial_chunk->len;
1750 if (str[1] == '?' && str[len - 1] == '?')
1752 if (strncmp (str, "<!--", 4) == 0 &&
1753 strcmp (str + len - 2, "--") == 0)
1755 if (strncmp (str, "<![CDATA[", 9) == 0 &&
1756 strcmp (str + len - 2, "]]") == 0)
1758 if (strncmp (str, "<!DOCTYPE", 9) == 0 &&
1759 context->balance == 0)
1763 while (advance_char (context));
1765 if (context->iter == context->current_text_end)
1767 /* The passthrough hasn't necessarily ended. Merge with
1768 * partial chunk, leave state unchanged.
1770 add_to_partial (context, context->start, context->iter);
1774 /* The passthrough has ended at the close angle. Combine
1775 * it with the partial chunk if any. Call the passthrough
1776 * callback. Note that the open/close angles are
1777 * included in the text of the passthrough.
1779 GError *tmp_error = NULL;
1781 advance_char (context); /* advance past close angle */
1782 add_to_partial (context, context->start, context->iter);
1784 if (context->flags & G_MARKUP_TREAT_CDATA_AS_TEXT &&
1785 strncmp (context->partial_chunk->str, "<![CDATA[", 9) == 0)
1787 if (context->parser->text)
1788 (*context->parser->text) (context,
1789 context->partial_chunk->str + 9,
1790 context->partial_chunk->len - 12,
1794 else if (context->parser->passthrough)
1795 (*context->parser->passthrough) (context,
1796 context->partial_chunk->str,
1797 context->partial_chunk->len,
1801 truncate_partial (context);
1803 if (tmp_error == NULL)
1805 context->state = STATE_AFTER_CLOSE_ANGLE;
1806 context->start = context->iter; /* could begin text */
1809 propagate_error (context, error, tmp_error);
1818 g_assert_not_reached ();
1824 context->parsing = FALSE;
1826 return context->state != STATE_ERROR;
1830 * g_markup_parse_context_end_parse:
1831 * @context: a #GMarkupParseContext
1832 * @error: return location for a #GError
1834 * Signals to the #GMarkupParseContext that all data has been
1835 * fed into the parse context with g_markup_parse_context_parse().
1836 * This function reports an error if the document isn't complete,
1837 * for example if elements are still open.
1839 * Return value: %TRUE on success, %FALSE if an error was set
1842 g_markup_parse_context_end_parse (GMarkupParseContext *context,
1845 g_return_val_if_fail (context != NULL, FALSE);
1846 g_return_val_if_fail (!context->parsing, FALSE);
1847 g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1849 if (context->partial_chunk != NULL)
1851 g_string_free (context->partial_chunk, TRUE);
1852 context->partial_chunk = NULL;
1855 if (context->document_empty)
1857 set_error_literal (context, error, G_MARKUP_ERROR_EMPTY,
1858 _("Document was empty or contained only whitespace"));
1862 context->parsing = TRUE;
1864 switch (context->state)
1870 case STATE_AFTER_OPEN_ANGLE:
1871 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1872 _("Document ended unexpectedly just after an open angle bracket '<'"));
1875 case STATE_AFTER_CLOSE_ANGLE:
1876 if (context->tag_stack != NULL)
1878 /* Error message the same as for INSIDE_TEXT */
1879 set_error (context, error, G_MARKUP_ERROR_PARSE,
1880 _("Document ended unexpectedly with elements still open - "
1881 "'%s' was the last element opened"),
1882 current_element (context));
1886 case STATE_AFTER_ELISION_SLASH:
1887 set_error (context, error, G_MARKUP_ERROR_PARSE,
1888 _("Document ended unexpectedly, expected to see a close angle "
1889 "bracket ending the tag <%s/>"), current_element (context));
1892 case STATE_INSIDE_OPEN_TAG_NAME:
1893 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1894 _("Document ended unexpectedly inside an element name"));
1897 case STATE_INSIDE_ATTRIBUTE_NAME:
1898 case STATE_AFTER_ATTRIBUTE_NAME:
1899 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1900 _("Document ended unexpectedly inside an attribute name"));
1903 case STATE_BETWEEN_ATTRIBUTES:
1904 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1905 _("Document ended unexpectedly inside an element-opening "
1909 case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1910 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1911 _("Document ended unexpectedly after the equals sign "
1912 "following an attribute name; no attribute value"));
1915 case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1916 case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1917 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1918 _("Document ended unexpectedly while inside an attribute "
1922 case STATE_INSIDE_TEXT:
1923 g_assert (context->tag_stack != NULL);
1924 set_error (context, error, G_MARKUP_ERROR_PARSE,
1925 _("Document ended unexpectedly with elements still open - "
1926 "'%s' was the last element opened"),
1927 current_element (context));
1930 case STATE_AFTER_CLOSE_TAG_SLASH:
1931 case STATE_INSIDE_CLOSE_TAG_NAME:
1932 case STATE_AFTER_CLOSE_TAG_NAME:
1933 set_error (context, error, G_MARKUP_ERROR_PARSE,
1934 _("Document ended unexpectedly inside the close tag for "
1935 "element '%s'"), current_element (context));
1938 case STATE_INSIDE_PASSTHROUGH:
1939 set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1940 _("Document ended unexpectedly inside a comment or "
1941 "processing instruction"));
1946 g_assert_not_reached ();
1950 context->parsing = FALSE;
1952 return context->state != STATE_ERROR;
1956 * g_markup_parse_context_get_element:
1957 * @context: a #GMarkupParseContext
1958 * @returns: the name of the currently open element, or %NULL
1960 * Retrieves the name of the currently open element.
1962 * If called from the start_element or end_element handlers this will
1963 * give the element_name as passed to those functions. For the parent
1964 * elements, see g_markup_parse_context_get_element_stack().
1968 G_CONST_RETURN gchar *
1969 g_markup_parse_context_get_element (GMarkupParseContext *context)
1971 g_return_val_if_fail (context != NULL, NULL);
1973 if (context->tag_stack == NULL)
1976 return current_element (context);
1980 * g_markup_parse_context_get_element_stack:
1981 * @context: a #GMarkupParseContext
1983 * Retrieves the element stack from the internal state of the parser.
1984 * The returned #GSList is a list of strings where the first item is
1985 * the currently open tag (as would be returned by
1986 * g_markup_parse_context_get_element()) and the next item is its
1989 * This function is intended to be used in the start_element and
1990 * end_element handlers where g_markup_parse_context_get_element()
1991 * would merely return the name of the element that is being
1994 * Returns: the element stack, which must not be modified
1998 G_CONST_RETURN GSList *
1999 g_markup_parse_context_get_element_stack (GMarkupParseContext *context)
2001 g_return_val_if_fail (context != NULL, NULL);
2003 return context->tag_stack;
2007 * g_markup_parse_context_get_position:
2008 * @context: a #GMarkupParseContext
2009 * @line_number: return location for a line number, or %NULL
2010 * @char_number: return location for a char-on-line number, or %NULL
2012 * Retrieves the current line number and the number of the character on
2013 * that line. Intended for use in error messages; there are no strict
2014 * semantics for what constitutes the "current" line number other than
2015 * "the best number we could come up with for error messages."
2019 g_markup_parse_context_get_position (GMarkupParseContext *context,
2023 g_return_if_fail (context != NULL);
2026 *line_number = context->line_number;
2029 *char_number = context->char_number;
2033 * g_markup_parse_context_get_user_data:
2034 * @context: a #GMarkupParseContext
2036 * Returns the user_data associated with @context. This will either
2037 * be the user_data that was provided to g_markup_parse_context_new()
2038 * or to the most recent call of g_markup_parse_context_push().
2040 * Returns: the provided user_data. The returned data belongs to
2041 * the markup context and will be freed when g_markup_context_free()
2047 g_markup_parse_context_get_user_data (GMarkupParseContext *context)
2049 return context->user_data;
2053 * g_markup_parse_context_push:
2054 * @context: a #GMarkupParseContext
2055 * @parser: a #GMarkupParser
2056 * @user_data: user data to pass to #GMarkupParser functions
2058 * Temporarily redirects markup data to a sub-parser.
2060 * This function may only be called from the start_element handler of
2061 * a #GMarkupParser. It must be matched with a corresponding call to
2062 * g_markup_parse_context_pop() in the matching end_element handler
2063 * (except in the case that the parser aborts due to an error).
2065 * All tags, text and other data between the matching tags is
2066 * redirected to the subparser given by @parser. @user_data is used
2067 * as the user_data for that parser. @user_data is also passed to the
2068 * error callback in the event that an error occurs. This includes
2069 * errors that occur in subparsers of the subparser.
2071 * The end tag matching the start tag for which this call was made is
2072 * handled by the previous parser (which is given its own user_data)
2073 * which is why g_markup_parse_context_pop() is provided to allow "one
2074 * last access" to the @user_data provided to this function. In the
2075 * case of error, the @user_data provided here is passed directly to
2076 * the error callback of the subparser and g_markup_parse_context()
2077 * should not be called. In either case, if @user_data was allocated
2078 * then it ought to be freed from both of these locations.
2080 * This function is not intended to be directly called by users
2081 * interested in invoking subparsers. Instead, it is intended to be
2082 * used by the subparsers themselves to implement a higher-level
2085 * As an example, see the following implementation of a simple
2086 * parser that counts the number of tags encountered.
2095 * counter_start_element (GMarkupParseContext *context,
2096 * const gchar *element_name,
2097 * const gchar **attribute_names,
2098 * const gchar **attribute_values,
2099 * gpointer user_data,
2102 * CounterData *data = user_data;
2104 * data->tag_count++;
2108 * counter_error (GMarkupParseContext *context,
2110 * gpointer user_data)
2112 * CounterData *data = user_data;
2114 * g_slice_free (CounterData, data);
2117 * static GMarkupParser counter_subparser =
2119 * counter_start_element,
2127 * In order to allow this parser to be easily used as a subparser, the
2128 * following interface is provided:
2132 * start_counting (GMarkupParseContext *context)
2134 * CounterData *data = g_slice_new (CounterData);
2136 * data->tag_count = 0;
2137 * g_markup_parse_context_push (context, &counter_subparser, data);
2141 * end_counting (GMarkupParseContext *context)
2143 * CounterData *data = g_markup_parse_context_pop (context);
2146 * result = data->tag_count;
2147 * g_slice_free (CounterData, data);
2153 * The subparser would then be used as follows:
2156 * static void start_element (context, element_name, ...)
2158 * if (strcmp (element_name, "count-these") == 0)
2159 * start_counting (context);
2161 * /* else, handle other tags... */
2164 * static void end_element (context, element_name, ...)
2166 * if (strcmp (element_name, "count-these") == 0)
2167 * g_print ("Counted %d tags\n", end_counting (context));
2169 * /* else, handle other tags... */
2176 g_markup_parse_context_push (GMarkupParseContext *context,
2177 GMarkupParser *parser,
2180 GMarkupRecursionTracker *tracker;
2182 tracker = g_slice_new (GMarkupRecursionTracker);
2183 tracker->prev_element = context->subparser_element;
2184 tracker->prev_parser = context->parser;
2185 tracker->prev_user_data = context->user_data;
2187 context->subparser_element = current_element (context);
2188 context->parser = parser;
2189 context->user_data = user_data;
2191 context->subparser_stack = g_slist_prepend (context->subparser_stack,
2196 * g_markup_parse_context_pop:
2197 * @context: a #GMarkupParseContext
2199 * Completes the process of a temporary sub-parser redirection.
2201 * This function exists to collect the user_data allocated by a
2202 * matching call to g_markup_parse_context_push(). It must be called
2203 * in the end_element handler corresponding to the start_element
2204 * handler during which g_markup_parse_context_push() was called. You
2205 * must not call this function from the error callback -- the
2206 * @user_data is provided directly to the callback in that case.
2208 * This function is not intended to be directly called by users
2209 * interested in invoking subparsers. Instead, it is intended to be
2210 * used by the subparsers themselves to implement a higher-level
2213 * Returns: the user_data passed to g_markup_parse_context_push().
2218 g_markup_parse_context_pop (GMarkupParseContext *context)
2222 if (!context->awaiting_pop)
2223 possibly_finish_subparser (context);
2225 g_assert (context->awaiting_pop);
2227 context->awaiting_pop = FALSE;
2229 /* valgrind friendliness */
2230 user_data = context->held_user_data;
2231 context->held_user_data = NULL;
2237 append_escaped_text (GString *str,
2246 end = text + length;
2251 next = g_utf8_next_char (p);
2256 g_string_append (str, "&");
2260 g_string_append (str, "<");
2264 g_string_append (str, ">");
2268 g_string_append (str, "'");
2272 g_string_append (str, """);
2276 c = g_utf8_get_char (p);
2277 if ((0x1 <= c && c <= 0x8) ||
2278 (0xb <= c && c <= 0xc) ||
2279 (0xe <= c && c <= 0x1f) ||
2280 (0x7f <= c && c <= 0x84) ||
2281 (0x86 <= c && c <= 0x9f))
2282 g_string_append_printf (str, "&#x%x;", c);
2284 g_string_append_len (str, p, next - p);
2293 * g_markup_escape_text:
2294 * @text: some valid UTF-8 text
2295 * @length: length of @text in bytes, or -1 if the text is nul-terminated
2297 * Escapes text so that the markup parser will parse it verbatim.
2298 * Less than, greater than, ampersand, etc. are replaced with the
2299 * corresponding entities. This function would typically be used
2300 * when writing out a file to be parsed with the markup parser.
2302 * Note that this function doesn't protect whitespace and line endings
2303 * from being processed according to the XML rules for normalization
2304 * of line endings and attribute values.
2306 * Note also that if given a string containing them, this function
2307 * will produce character references in the range of &#x1; ..
2308 * &#x1f; for all control sequences except for tabstop, newline
2309 * and carriage return. The character references in this range are
2310 * not valid XML 1.0, but they are valid XML 1.1 and will be accepted
2311 * by the GMarkup parser.
2313 * Return value: a newly allocated string with the escaped text
2316 g_markup_escape_text (const gchar *text,
2321 g_return_val_if_fail (text != NULL, NULL);
2324 length = strlen (text);
2326 /* prealloc at least as long as original text */
2327 str = g_string_sized_new (length);
2328 append_escaped_text (str, text, length);
2330 return g_string_free (str, FALSE);
2335 * @format: a printf-style format string
2336 * @after: location to store a pointer to the character after
2337 * the returned conversion. On a %NULL return, returns the
2338 * pointer to the trailing NUL in the string
2340 * Find the next conversion in a printf-style format string.
2341 * Partially based on code from printf-parser.c,
2342 * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
2344 * Return value: pointer to the next conversion in @format,
2345 * or %NULL, if none.
2348 find_conversion (const char *format,
2351 const char *start = format;
2354 while (*start != '\0' && *start != '%')
2371 /* Test for positional argument. */
2372 if (*cp >= '0' && *cp <= '9')
2376 for (np = cp; *np >= '0' && *np <= '9'; np++)
2382 /* Skip the flags. */
2396 /* Skip the field width. */
2401 /* Test for positional argument. */
2402 if (*cp >= '0' && *cp <= '9')
2406 for (np = cp; *np >= '0' && *np <= '9'; np++)
2414 for (; *cp >= '0' && *cp <= '9'; cp++)
2418 /* Skip the precision. */
2424 /* Test for positional argument. */
2425 if (*cp >= '0' && *cp <= '9')
2429 for (np = cp; *np >= '0' && *np <= '9'; np++)
2437 for (; *cp >= '0' && *cp <= '9'; cp++)
2442 /* Skip argument type/size specifiers. */
2443 while (*cp == 'h' ||
2452 /* Skip the conversion character. */
2460 * g_markup_vprintf_escaped:
2461 * @format: printf() style format string
2462 * @args: variable argument list, similar to vprintf()
2464 * Formats the data in @args according to @format, escaping
2465 * all string and character arguments in the fashion
2466 * of g_markup_escape_text(). See g_markup_printf_escaped().
2468 * Return value: newly allocated result from formatting
2469 * operation. Free with g_free().
2474 g_markup_vprintf_escaped (const char *format,
2479 GString *result = NULL;
2480 gchar *output1 = NULL;
2481 gchar *output2 = NULL;
2482 const char *p, *op1, *op2;
2485 /* The technique here, is that we make two format strings that
2486 * have the identical conversions in the identical order to the
2487 * original strings, but differ in the text in-between. We
2488 * then use the normal g_strdup_vprintf() to format the arguments
2489 * with the two new format strings. By comparing the results,
2490 * we can figure out what segments of the output come from
2491 * the the original format string, and what from the arguments,
2492 * and thus know what portions of the string to escape.
2494 * For instance, for:
2496 * g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2498 * We form the two format strings "%sX%dX" and %sY%sY". The results
2499 * of formatting with those two strings are
2501 * "%sX%dX" => "Susan & FredX5X"
2502 * "%sY%dY" => "Susan & FredY5Y"
2504 * To find the span of the first argument, we find the first position
2505 * where the two arguments differ, which tells us that the first
2506 * argument formatted to "Susan & Fred". We then escape that
2507 * to "Susan & Fred" and join up with the intermediate portions
2508 * of the format string and the second argument to get
2509 * "Susan & Fred ate 5 apples".
2512 /* Create the two modified format strings
2514 format1 = g_string_new (NULL);
2515 format2 = g_string_new (NULL);
2520 const char *conv = find_conversion (p, &after);
2524 g_string_append_len (format1, conv, after - conv);
2525 g_string_append_c (format1, 'X');
2526 g_string_append_len (format2, conv, after - conv);
2527 g_string_append_c (format2, 'Y');
2532 /* Use them to format the arguments
2534 G_VA_COPY (args2, args);
2536 output1 = g_strdup_vprintf (format1->str, args);
2543 output2 = g_strdup_vprintf (format2->str, args2);
2548 result = g_string_new (NULL);
2550 /* Iterate through the original format string again,
2551 * copying the non-conversion portions and the escaped
2552 * converted arguments to the output string.
2560 const char *output_start;
2561 const char *conv = find_conversion (p, &after);
2564 if (!conv) /* The end, after points to the trailing \0 */
2566 g_string_append_len (result, p, after - p);
2570 g_string_append_len (result, p, conv - p);
2572 while (*op1 == *op2)
2578 escaped = g_markup_escape_text (output_start, op1 - output_start);
2579 g_string_append (result, escaped);
2588 g_string_free (format1, TRUE);
2589 g_string_free (format2, TRUE);
2594 return g_string_free (result, FALSE);
2600 * g_markup_printf_escaped:
2601 * @format: printf() style format string
2602 * @Varargs: the arguments to insert in the format string
2604 * Formats arguments according to @format, escaping
2605 * all string and character arguments in the fashion
2606 * of g_markup_escape_text(). This is useful when you
2607 * want to insert literal strings into XML-style markup
2608 * output, without having to worry that the strings
2609 * might themselves contain markup.
2612 * const char *store = "Fortnum & Mason";
2613 * const char *item = "Tea";
2616 * output = g_markup_printf_escaped ("<purchase>"
2617 * "<store>%s</store>"
2618 * "<item>%s</item>"
2619 * "</purchase>",
2623 * Return value: newly allocated result from formatting
2624 * operation. Free with g_free().
2629 g_markup_printf_escaped (const char *format, ...)
2634 va_start (args, format);
2635 result = g_markup_vprintf_escaped (format, args);
2642 g_markup_parse_boolean (const char *string,
2645 char const * const falses[] = { "false", "f", "no", "n", "0" };
2646 char const * const trues[] = { "true", "t", "yes", "y", "1" };
2649 for (i = 0; i < G_N_ELEMENTS (falses); i++)
2651 if (g_ascii_strcasecmp (string, falses[i]) == 0)
2660 for (i = 0; i < G_N_ELEMENTS (trues); i++)
2662 if (g_ascii_strcasecmp (string, trues[i]) == 0)
2675 * GMarkupCollectType:
2676 * @G_MARKUP_COLLECT_INVALID: used to terminate the list of attributes
2678 * @G_MARKUP_COLLECT_STRING: collect the string pointer directly from
2679 * the attribute_values[] array. Expects a
2680 * parameter of type (const char **). If
2681 * %G_MARKUP_COLLECT_OPTIONAL is specified
2682 * and the attribute isn't present then the
2683 * pointer will be set to %NULL.
2684 * @G_MARKUP_COLLECT_STRDUP: as with %G_MARKUP_COLLECT_STRING, but
2685 * expects a paramter of type (char **) and
2686 * g_strdup()s the returned pointer. The
2687 * pointer must be freed with g_free().
2688 * @G_MARKUP_COLLECT_BOOLEAN: expects a parameter of type (gboolean *)
2689 * and parses the attribute value as a
2690 * boolean. Sets %FALSE if the attribute
2691 * isn't present. Valid boolean values
2692 * consist of (case insensitive) "false",
2693 * "f", "no", "n", "0" and "true", "t",
2695 * @G_MARKUP_COLLECT_TRISTATE: as with %G_MARKUP_COLLECT_BOOLEAN, but
2696 * in the case of a missing attribute a
2697 * value is set that compares equal to
2698 * neither %FALSE nor %TRUE.
2699 * G_MARKUP_COLLECT_OPTIONAL is implied.
2700 * @G_MARKUP_COLLECT_OPTIONAL: can be bitwise ORed with the other
2701 * fields. If present, allows the
2702 * attribute not to appear. A default
2703 * value is set depending on what value
2706 * A mixed enumerated type and flags field. You must specify one type
2707 * (string, strdup, boolean, tristate). Additionally, you may
2708 * optionally bitwise OR the type with the flag
2709 * %G_MARKUP_COLLECT_OPTIONAL.
2711 * It is likely that this enum will be extended in the future to
2712 * support other types.
2716 * g_markup_collect_attributes:
2717 * @element_name: the current tag name
2718 * @attribute_names: the attribute names
2719 * @attribute_values: the attribute values
2720 * @error: a pointer to a #GError or %NULL
2721 * @first_type: the #GMarkupCollectType of the
2723 * @first_attr: the name of the first attribute
2724 * @...: a pointer to the storage location of the
2725 * first attribute (or %NULL), followed by
2726 * more types names and pointers, ending
2727 * with %G_MARKUP_COLLECT_INVALID.
2729 * Collects the attributes of the element from the
2730 * data passed to the #GMarkupParser start_element
2731 * function, dealing with common error conditions
2732 * and supporting boolean values.
2734 * This utility function is not required to write
2735 * a parser but can save a lot of typing.
2737 * The @element_name, @attribute_names,
2738 * @attribute_values and @error parameters passed
2739 * to the start_element callback should be passed
2740 * unmodified to this function.
2742 * Following these arguments is a list of
2743 * "supported" attributes to collect. It is an
2744 * error to specify multiple attributes with the
2745 * same name. If any attribute not in the list
2746 * appears in the @attribute_names array then an
2747 * unknown attribute error will result.
2749 * The #GMarkupCollectType field allows specifying
2750 * the type of collection to perform and if a
2751 * given attribute must appear or is optional.
2753 * The attribute name is simply the name of the
2754 * attribute to collect.
2756 * The pointer should be of the appropriate type
2757 * (see the descriptions under
2758 * #GMarkupCollectType) and may be %NULL in case a
2759 * particular attribute is to be allowed but
2762 * This function deals with issuing errors for missing attributes
2763 * (of type %G_MARKUP_ERROR_MISSING_ATTRIBUTE), unknown attributes
2764 * (of type %G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE) and duplicate
2765 * attributes (of type %G_MARKUP_ERROR_INVALID_CONTENT) as well
2766 * as parse errors for boolean-valued attributes (again of type
2767 * %G_MARKUP_ERROR_INVALID_CONTENT). In all of these cases %FALSE
2768 * will be returned and @error will be set as appropriate.
2770 * Return value: %TRUE if successful
2775 g_markup_collect_attributes (const gchar *element_name,
2776 const gchar **attribute_names,
2777 const gchar **attribute_values,
2779 GMarkupCollectType first_type,
2780 const gchar *first_attr,
2783 GMarkupCollectType type;
2795 va_start (ap, first_attr);
2796 while (type != G_MARKUP_COLLECT_INVALID)
2801 mandatory = !(type & G_MARKUP_COLLECT_OPTIONAL);
2802 type &= (G_MARKUP_COLLECT_OPTIONAL - 1);
2804 /* tristate records a value != TRUE and != FALSE
2805 * for the case where the attribute is missing
2807 if (type == G_MARKUP_COLLECT_TRISTATE)
2810 for (i = 0; attribute_names[i]; i++)
2811 if (i >= 40 || !(collected & (G_GUINT64_CONSTANT(1) << i)))
2812 if (!strcmp (attribute_names[i], attr))
2815 /* ISO C99 only promises that the user can pass up to 127 arguments.
2816 * Subtracting the first 4 arguments plus the final NULL and dividing
2817 * by 3 arguments per collected attribute, we are left with a maximum
2818 * number of supported attributes of (127 - 5) / 3 = 40.
2820 * In reality, nobody is ever going to call us with anywhere close to
2821 * 40 attributes to collect, so it is safe to assume that if i > 40
2822 * then the user has given some invalid or repeated arguments. These
2823 * problems will be caught and reported at the end of the function.
2825 * We know at this point that we have an error, but we don't know
2826 * what error it is, so just continue...
2829 collected |= (G_GUINT64_CONSTANT(1) << i);
2831 value = attribute_values[i];
2833 if (value == NULL && mandatory)
2835 g_set_error (error, G_MARKUP_ERROR,
2836 G_MARKUP_ERROR_MISSING_ATTRIBUTE,
2837 "element '%s' requires attribute '%s'",
2838 element_name, attr);
2846 case G_MARKUP_COLLECT_STRING:
2848 const char **str_ptr;
2850 str_ptr = va_arg (ap, const char **);
2852 if (str_ptr != NULL)
2857 case G_MARKUP_COLLECT_STRDUP:
2861 str_ptr = va_arg (ap, char **);
2863 if (str_ptr != NULL)
2864 *str_ptr = g_strdup (value);
2868 case G_MARKUP_COLLECT_BOOLEAN:
2869 case G_MARKUP_COLLECT_TRISTATE:
2874 bool_ptr = va_arg (ap, gboolean *);
2876 if (bool_ptr != NULL)
2878 if (type == G_MARKUP_COLLECT_TRISTATE)
2879 /* constructivists rejoice!
2880 * neither false nor true...
2884 else /* G_MARKUP_COLLECT_BOOLEAN */
2890 if (!g_markup_parse_boolean (value, va_arg (ap, gboolean *)))
2892 g_set_error (error, G_MARKUP_ERROR,
2893 G_MARKUP_ERROR_INVALID_CONTENT,
2894 "element '%s', attribute '%s', value '%s' "
2895 "cannot be parsed as a boolean value",
2896 element_name, attr, value);
2906 g_assert_not_reached ();
2909 type = va_arg (ap, GMarkupCollectType);
2910 attr = va_arg (ap, const char *);
2915 /* ensure we collected all the arguments */
2916 for (i = 0; attribute_names[i]; i++)
2917 if ((collected & (G_GUINT64_CONSTANT(1) << i)) == 0)
2919 /* attribute not collected: could be caused by two things.
2921 * 1) it doesn't exist in our list of attributes
2922 * 2) it existed but was matched by a duplicate attribute earlier
2928 for (j = 0; j < i; j++)
2929 if (strcmp (attribute_names[i], attribute_names[j]) == 0)
2933 /* j is now the first occurance of attribute_names[i] */
2935 g_set_error (error, G_MARKUP_ERROR,
2936 G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
2937 "attribute '%s' invalid for element '%s'",
2938 attribute_names[i], element_name);
2940 g_set_error (error, G_MARKUP_ERROR,
2941 G_MARKUP_ERROR_INVALID_CONTENT,
2942 "attribute '%s' given multiple times for element '%s'",
2943 attribute_names[i], element_name);
2951 /* replay the above to free allocations */
2955 va_start (ap, first_attr);
2956 while (type != G_MARKUP_COLLECT_INVALID)
2960 ptr = va_arg (ap, gpointer);
2965 switch (type & (G_MARKUP_COLLECT_OPTIONAL - 1))
2967 case G_MARKUP_COLLECT_STRDUP:
2969 g_free (*(char **) ptr);
2971 case G_MARKUP_COLLECT_STRING:
2972 *(char **) ptr = NULL;
2975 case G_MARKUP_COLLECT_BOOLEAN:
2976 *(gboolean *) ptr = FALSE;
2979 case G_MARKUP_COLLECT_TRISTATE:
2980 *(gboolean *) ptr = -1;
2984 type = va_arg (ap, GMarkupCollectType);
2985 attr = va_arg (ap, const char *);
2995 #define __G_MARKUP_C__
2996 #include "galiasdef.c"